Commit Graph
50 Commits
  • fix(inbounds): allow negative subSortIndex for subscription order (#6465)
    * fix(inbounds): allow negative subSortIndex for subscription order
    
    Preserve explicitly set negative indices so primary inbounds can sort
    ahead of the default without renumbering peers; keep 0/omitted → 1.
    
    * fix(inbounds): gofumpt model.go and trim subSortIndex comments
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • feat(outbounds): support custom subscription user agents (#6398)
    Some subscription providers require a client-specific User-Agent before returning outbound links. Persist an optional value per subscription and use it for refreshes and previews while preserving the existing default for blank values.
  • fix(mtproto): use hosts for public share links (#6369)
    * fix(mtproto): use hosts for public share links
    
    Generate MTProto subscription, client, copy, QR, and export links from managed Hosts so reverse-proxied public ports are advertised correctly. Migrate the redundant legacy custom share address into a Host and keep old imports compatible.
    
    Closes #5126.
    
    * fix(mtproto): keep host share links lossless and consistent
    
    Address review on the MTProto hosts share-link change.
    
    The migration no longer drops a legacy custom share address: an unrelated
    (or disabled) Host stopped suppressing it, so only a Host already advertising
    the same address does. An imported address now clears the same validation the
    strict normalizer applies to every other protocol before it becomes a Host.
    
    Panel and subscription agree on the endpoint a Host advertises: a portless host
    string inherits the inbound port rather than the group's, and a port-only host
    inherits the inbound address instead of emitting server=%3A8443.
    
    LinksForClient prefers host endpoints for every protocol, the way getSubs and
    inboundLinks already do, so the client-links API no longer ignores managed
    hosts.
    
    * fix(mtproto): migrate legacy share address past unusable hosts
    
    The seeder skipped the conversion whenever any Host already carried the
    address, including one that is disabled or excludes the raw sub type.
    hostEndpoints drops those, so nothing advertised the address afterwards and
    the marker committed with no way back. The duplicate check now mirrors that
    same predicate.
    
    UpdateInbound cleared a legacy MTProto shareAddr without the Host conversion
    AddInbound runs, so re-applying an inbound definition through the API dropped
    the public address silently. Both paths share one capture helper now.
    
    Refresh the generated clients API reference for the summary reworded in the
    previous commit.
    
    * fix(inbounds): wait for the hosts list before building mtproto links
    
    The page destructured only `hosts` from useHostsQuery, and that list reads
    empty both while /panel/api/hosts/list is in flight and after it fails.
    withMtprotoHostEndpoints then returns the inbound untouched, so Copy, QR and
    Export advertise the internal listen port — the endpoint this branch exists to
    replace. It is worse than not fixing it: the seeder has already moved a legacy
    custom share address into a Host, so the fallback is the panel's own hostname
    instead of the operator's address, and the Go generators reading the same rows
    from the DB stay correct, so the two disagree for one inbound.
    
    Fold the query into the page's existing readiness gate, the same way
    useInbounds and HostsPage already consume that hook, so an empty list means
    "no hosts" rather than "not loaded yet". The error branch fires only when
    nothing is cached, so a refetch failing on window focus does not blank a page
    whose host rows are still perfectly usable.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(xray): update xray-core to v26.9.8 and adapt panel
    Bump xtls/xray-core to 37ceb8b4b6 (v26.9.8) and the three binary pins
    (DockerInit.sh, release.yml Linux + Windows) in lockstep. No deleted
    symbols; the impact is entirely on the JSON config surface.
    
    Outbound "proxySettings" is now refused by the config loader (moved to
    streamSettings.sockopt.dialerProxy) and a freedom outbound rejects
    sockopt.addressPortStrategy. Either key in a stored template would keep
    the core from starting after the upgrade, so a new OutboundRemovedKeysFix
    seeder rewrites xrayTemplateConfig once: proxySettings.tag becomes
    sockopt.dialerProxy (an existing dialerProxy wins) and addressPortStrategy
    is dropped from freedom outbounds. Template saves and outbound
    subscriptions already run through the vendored loader, so the new
    refusals surface there with the core's own message.
    
    REALITY no longer applies a built-in minClientVer (26.3.27) when the
    field is empty. The form placeholder and the min/max hints in all 13
    locales now say that empty means no minimum.
    
    New upstream keys the Zod schemas would otherwise strip, with form
    support where a sibling field already had it:
    - blackhole response type "custom" with base64 customResponseData
    - realm finalmask ipMode (dual/v4/v6) and portMapping (UPnP / NAT-PMP)
    - quicParams brutalDisableLossCompensation, disableChromeParrot,
      disableGSO, disableStatelessReset
    - hysteria masquerade proxy xForwarded
    - wireguard outbound remoteDNS
    - routing rule localOS
    
    freedom.domainStrategy is only deprecated upstream (auto-migrated to
    sockopt.domainStrategy with a warning) and is left untouched.
  • fix(database): keep the SQLite store owner-only (#6390)
    * fix(database): keep the SQLite store owner-only
    
    InitDB created the data directory 0755 and let SQLite create x-ui.db
    and its -wal/-shm side files under the default umask, so on a stock
    install they are world-readable. The store holds client UUIDs, Reality
    private keys and the admin password hash, so any local account could
    read them.
    
    Create the directory 0700 and chmod the database files to 0600 right
    after opening. SQLite gives -wal/-shm the mode of the main file, so
    files created later inherit it; existing installs are tightened on the
    next start. PostgreSQL deployments are untouched.
    
    Assisted-by: Claude Code:claude-fable-5-1
    
    * fix(database): tolerate chmod failures, keep the dump and install dir owner-only
    
    Review follow-ups. A store the panel cannot chmod (root_squash NFS, a
    foreign uid in a container) refused to start, which is worse than the
    0644 it had before; log and continue instead, as the backup-directory
    cleanup above already does. install.sh reset /etc/x-ui to 0755 right
    after the binary created it 0700, so the directory hunk was inert on
    real installs; create it 0700 there too. The migrate-db dump in the same
    directory is a plaintext copy of the same secrets and was written 0644.
    
    Assisted-by: Claude Code:claude-fable-5-1
  • fix(sub): randomize fresh panel subscription paths (#6375)
    * fix(sub): randomize fresh panel subscription paths
    
    Seed distinct cryptographically random paths for base64, JSON, and Clash subscriptions when a panel database is first created. Persist them so restarts keep published URLs stable while upgrades preserve existing settings.
    
    Generated-by: OpenCode:gpt-5.6-sol
    
    * fix(sub): regenerate paths on settings reset
    
    Keep subscription paths unpredictable after a factory reset, close the test database on failure, and update the builder, OpenAPI, and localized docs to describe panel-specific paths instead of obsolete fixed defaults.
    
    Generated-by: OpenCode:gpt-5.6-sol
  • 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>
  • perf(clients): write client_inbounds deltas and check identity from the clients table
    Client CRUD latency scaled with the number of client-inbound edges rather
    than with the size of the change. On a 5k-client / 8-inbound / ~56k-edge
    PostgreSQL panel, creating one client took 60-120s (#6252).
    
    Two independent causes, both confirmed by the reporter's pg_stat_statements
    and reproduced locally at their topology.
    
    SyncInbound deleted every client_inbounds row for an inbound and re-inserted
    the whole set, so a one-client edit rewrote thousands of unrelated rows. The
    dominant caller was not user CRUD: the node traffic poll re-syncs every node
    inbound from its snapshot every 5s, so the panel churned the entire
    membership table continuously in the background. SyncInbound now reads the
    current links and writes only the difference - insert missing, update a
    changed flow_override, delete departed. Callers are unchanged, so every
    reconciliation path benefits, and the four hot client CRUD paths additionally
    pass only the clients they touched via ApplyInboundClientDelta.
    
    The insert needs clause.OnConflict: the unconditional delete it replaces also
    serialized concurrent syncs of one inbound, and the node poll commits in its
    own transaction outside the serialized writer, where a duplicate key would
    abort the whole poll on PostgreSQL.
    
    Identity and membership questions expanded every inbound's settings.clients
    JSON - 5.75s per call under the reporter's load. They now read the indexed
    clients and client_inbounds tables, which every read path already trusts,
    over just the emails being checked. A LOWER(email) expression index keeps
    the case-insensitive matching indexed; a struct tag cannot declare one.
    
    Measured on PostgreSQL 17 at 8 inbounds x 6000 clients, rows written to
    client_inbounds per operation, before -> after:
    
      create across 8 inbounds   48008 ins / 48000 del  ->  8 ins / 0 del
      update the client          48008 ins / 48008 del  ->  0 ins / 0 del
      detach from 4 inbounds     24000 ins / 24004 del  ->  0 ins / 4 del
      delete the client          24000 ins / 24004 del  ->  0 ins / 4 del
    
    Two behavior changes worth naming. An email seen with two different subIds
    across two inbounds' JSON used to be locked so that no add could claim it,
    including the one with the correct subId; the clients row now adjudicates.
    And on an install whose settings JSON holds an email with no matching link,
    "is this email on another inbound" now answers no, so deleting it elsewhere
    purges its traffic rows; compactOrphans and the startup heal already
    converge such drift.
    
    Every added test was verified against a hand-written mutation of this change,
    so none of them pass regardless of the fix. One mutation survives on purpose:
    swapping OnConflict DoUpdates for DoNothing is only observable when two
    transactions race the same row, and a timing-dependent test would be flaky.
    
    Per-node batching of remote pushes and the metadata-only inbounds list from
    the same report are deliberately not in this change.
    
    Closes #6252
  • Add per-client external link controls (#5650)
    * Add enable toggle for external client links
    
    * Document external link enable API fields
    
    * Extend external client link metadata
    
    * Fix external subscription cache status updates
    
    * fix(sub): address the review on per-client external link controls
    
    Blocking: the expiry filter dropped legacy rows. expiry_time was added
    without a default, so AutoMigrate makes it nullable and backfills NULL,
    and `expiry_time = 0 OR expiry_time > ?` is false for NULL under
    three-valued logic — every external link written before the upgrade
    vanished from all subscriptions. Add `default:0` on expiry_time and
    last_fetch_at, make the predicate NULL-tolerant, and backfill the NULLs
    a pre-fix build could already have written.
    
    Rework fetch-status recording. It ran inside the singleflight in-flight
    window, so every goroutine parked on the shared fetch waited for a DB
    write to commit on the public, unauthenticated subscription path — and
    because it was keyed on the row id, waiters and cache hits recorded
    nothing, leaving rows that lost the race stuck on "Not fetched yet"
    forever. fetchSubscriptionLinks now reports whether it did the network
    fetch and expandEntry records afterwards, off the serving path, keyed on
    kind+value so every row sharing the URL is stamped by the one fetch.
    Keying on value also closes the recycled-rowid hazard: saves delete and
    re-insert rows, and SQLite reuses rowids, so an in-flight write could
    land on an unrelated client's row. The write no longer discards its
    error either.
    
    Drop the inert id round-trip. The panel never sent it, and the byId
    branch was guarded by the exact kind+value equality that byKindValue
    already keys on, so it could not change an outcome. Matching on
    kind+value alone is what actually preserves fetch status across saves.
    
    Reject a negative expiryTime instead of storing a row that is silently
    invisible in every subscription — elsewhere a negative expiryTime means
    "a duration from first use", so an API caller reusing that convention
    got no error and no links.
    
    Drop the ~50 lines of .client-form-* / .client-inbounds-field CSS that
    no component renders; it is leftover from the WireGuard PR this one was
    split from.
    
    i18n: reuse the already-translated pages.inbounds.leaveBlankToNeverExpire
    instead of shipping an English duplicate under pages.clients, and
    translate namePrefix, lastFetchAt, lastFetchError and neverFetched into
    all 12 non-English locales.
    
    Cover the persistence path that had no test: the fetch-status writer over
    a real DB against a failing then a succeeding server, a cache hit writing
    nothing, and the negative-expiry rejection.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(clients): give each client its own traffic reset cycle (#6240)
    * feat(clients): give each client its own traffic reset cycle
    
    Traffic reset is configured on the inbound, so every client sharing an
    inbound resets together. An operator running a monthly 1000GB plan and a
    weekly 200GB plan side by side has to press Reset Traffic by hand.
    
    Clients now carry the same trafficReset / trafficResetDay pair the
    inbound already has, with the same vocabulary and the same monthly
    due-day rule, and PeriodicTrafficResetJob makes a second pass over the
    clients whose own cycle matches the period it is running for. A client
    that leaves the field at never behaves exactly as before: only its
    inbound's schedule can reset it.
    
    The fields live on ClientRecord as well as in the inbound settings JSON,
    so an ordinary edit does not write the cycle back as empty, and an
    unknown period is rejected rather than coerced, since a coerced value
    would read as configured while no job would ever select the client.
    
    Cron expressions and a custom post-reset quota from the issue are left
    out: both are separate decisions, and neither has an inbound-level
    counterpart to stay consistent with.
    
    * fix(clients): make the per-client reset cycle editable and safe to run
    
    Review found three things wrong with the first cut, one of them mine and
    worse than the bug it replaced.
    
    The cycle could only be set at creation. ClientService.Update writes the
    columns directly only for a client with no inbounds; the normal path goes
    through SyncInbound and applyClientRecordMerge, which this change had not
    extended, so an edit updated the settings JSON while the clients column
    kept the old value and the job kept applying the old cycle. The earlier
    test passed because it asserted the value survived an unrelated edit,
    which it did precisely because nothing ever wrote it. Replaced with a
    test that changes the cycle and switches it off again.
    
    Avoiding the re-enable that ResetTrafficByEmail performs was wrong.
    Depletion disables clients.enable and the settings JSON as well as
    client_traffics.enable, so lifting only the quota gate left a depleted
    client out of the generated config with zeroed counters, which no longer
    match the depleted predicate: locked out permanently. The rule is now
    about cause, not state — a client the quota switched off is restored, one
    disabled below its quota was switched off by hand and is skipped.
    
    The bulk path also bypassed node propagation and the MTProto sidecar
    quota that ResetTrafficByEmail handles, so it silently did nothing on
    node-backed inbounds. Dropped in favour of the integrated path, whose
    needRestart is now collected and turned into a single SetToNeedRestart.
    
    Also adds the AutoMigrate NULL backfill, guards the merge so a stale node
    snapshot cannot erase a configured cycle, validates the bulk-create and
    import paths, normalizes the day the way the inbound path does, marks the
    fields omitempty so existing clients match the published contract, and
    shares one TRAFFIC_RESETS tuple between the three forms.
    
    * fix(clients): validate renew fields on the bulk and import paths too
    
    BulkCreate and ImportClients insert client records without going through
    Create, so the resetDay/resetMax checks added with the calendar renewal
    (#6239) and the renew cap (#6238) never ran there. An API caller could
    store resetDay 45 or a negative resetMax, values the renewal query then
    mishandles silently. Mirror Create's validation on both batch paths, next
    to the trafficReset check they already carry.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • 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(api): scoped, optionally expiring API tokens (#6201)
    * security(api): add scoped expiring API tokens
    
    * security(api): make scoped token lifecycle enforceable
    
    ---------
    
    Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.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>
  • fix(database): keep IP limits when the fail2ban probe is inconclusive (#6176)
    * fix(database): keep IP limits when the fail2ban probe is inconclusive
    
    ResetIpLimitNoFail2ban clears limitIp on every client — inbound settings JSON
    and the clients table — whenever fail2banCanEnforce() returns false, then
    records itself in the seeder history so it never re-evaluates. The probe was a
    single `fail2ban-client -h` run, so it answered false both when fail2ban is
    genuinely absent and when the command merely failed that once: a panel that
    starts before fail2ban is up, or in a container where it is installed a moment
    later, permanently loses every configured limit with no log line and no way
    back.
    
    Separate the two. A missing binary still means "absent" and the cleanup runs as
    before; a binary that exists but will not run is reported as unknown, leaves the
    configured values untouched, logs why, and does not record the seeder, so the
    next start decides again.
    
    * test(database): cover fail2ban reset safeguards
    
    ---------
    
    Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
  • fix(node): stop the node sync from deleting clients it never meant to
    A client that hit its quota or expiry was disabled, then destroyed on both
    panels a few seconds later. Five defects fed the same hard delete.
    
    ReconcileNode pushed buildRuntimeInboundForAPI, which strips disabled
    clients. Every other call site targets an in-memory Xray config, where
    dropping a user is harmless; a node target is a peer panel's DATABASE, so
    the node deleted the row, stopped reporting it, and the master mirrored that
    deletion back. Split the builder in two: buildInboundForNodePush injects
    fallbacks only, buildInboundForLocalRuntime adds the strip on top. The names
    now say which targets they are safe for.
    
    setRemoteTrafficLocked trusted a config_dirty the caller sampled before the
    snapshot round-trip. A client added inside that window commits on the same
    serialized writer and marks the node dirty, but the merge still treated the
    older snapshot as authoritative and deleted it. Re-read the flag inside the
    writer.
    
    In "selected" sync mode, FilterNodeSnapshot strips a deselected tag, but the
    sweep loaded every inbound with node_id set, so deselecting a tag read as
    "the node deleted it" and wiped an inbound the node still serves. Skip tags
    outside the node's managed set.
    
    A failed SyncInbound was logged and swallowed; on SQLite the transaction
    still commits, and the sweep then deleted the innocent clients whose links
    that failure had left unbuilt. Skip the sweep for such an inbound, and close
    the trigger: SyncInbound now stores the trimmed email it looks up by, and
    email validation rejects every unicode space rather than only U+0020.
    
    ClientService.Delete tombstones up front and deliberately keeps the record
    when an inbound fails, so the next attempt can retry the leftovers. The
    tombstone did not lift with it, so the next merge dropped the client from
    the synced settings and finished the deletion this path had refused. Add
    withdrawClientTombstones on every failure path, in BulkDelete too.
    
    Finally, make the sweep itself recoverable. "Ended the merge unattached" is
    true for a real remote deletion and equally true for a bad merge, so it now
    stamps sync_orphaned_at instead of deleting; any later merge that sees the
    client attached clears the mark, and a reaper removes only what stayed
    orphaned past the grace period. The traffic row survives that window too, or
    a reclaimed client would come back with its usage, quota and expiry reset.
    The mark is written by this sweep alone, so orphans from any other cause
    keep their existing manual-cleanup semantics.
  • fix(database): create SQLite backup snapshots online (#6137)
    * fix(database): snapshot SQLite backups online
    
    Use SQLite's online backup API for downloadable backups and SQLite migration exports instead of checkpointing then reading the live database file. The regression test validates a backup made while writes continue.
    
    * style(database): group SQLite driver imports
    
    * fix(database): bound online backup retries
    
    Use a single backup step and a bounded connection-acquisition/retry context. Tighten temporary-file cleanup and regression assertions while removing the unused checkpoint helper.
    
    * test(database): cover existing backup destinations
    
    * fix(database): harden SQLite snapshot lifecycle
    
    Sweep interrupted snapshot directories at SQLite startup, keep rollback-journal backups incremental, and make caller-owned cleanup explicit. Reuse one scheduled Telegram snapshot across administrators and make the direct SQLite driver dependency explicit.
    
    ---------
    
    Co-authored-by: PathGao <gaoyanbo@gaoyanbodeMacBook-Air.local>
  • feat(api): add GET endpoint to look up clients by Telegram ID (#5945)
    * feat(api): add GET endpoint to look up clients by Telegram ID
    
    GET /panel/api/clients/getByTgId/:tgId returns all clients matching the given Telegram user ID. tgId is not unique, so the response is an array of {client, inboundIds, externalLinks, usedTraffic} objects.
    
    * fix: guard tgId=0 sentinel, index tg_id, deduplicate enrichment in getByTgId
    
    Three issues from the code review on the new GET /panel/api/clients/getByTgId/:tgId
    endpoint: the lookup did not short-circuit tgId <= 0 (this codebase's sentinel
    for 'no Telegram ID'), had no index on clients.tg_id causing a full table scan
    on every call, and duplicated the per-record enrichment (inbound IDs, external
    links, effective flow, traffic) identically between get and getByTgId.
    
    - Reject tgId <= 0 in GetRecordsByTgId with a clear error, matching the
      '0 = none' convention used elsewhere in the codebase.
    - Add index:idx_clients_tg_id to ClientRecord.TgID (struct tag + idempotent
      startup migration for existing databases).
    - Extract buildClientPayload helper used by both get and getByTgId.
    - Update client_lookup_test.go to verify sentinel rejection instead of
      expecting tgId=0 to be a valid lookup.
    
    * refactor(api): move Telegram client lookup under /get/tgId/:tgId
    
    Nest the Telegram-ID lookup beside the email lookup as /get/tgId/:tgId
    instead of the flat /getByTgId/:tgId, so both client fetch routes share the
    /get prefix. Gin resolves the static tgId segment ahead of the :email
    wildcard, so /get/:email keeps matching plain email lookups, including a
    literal 'tgId' email. The endpoint is unreleased, so no compatibility
    concern.
  • fix(hosts): assign group ids to imported hosts and repair empty ones
    Host rows created from a legacy streamSettings.externalProxy during
    inbound import got an empty group_id, and the one-time HostGroupIds
    seeder had already been gated off, so the UI rendered them under a
    synthetic fallback_<id> group the update/delete API could not resolve,
    failing every edit with "host group not found".
    
    Assign a real group id in externalProxyEntryToHost at creation, and
    replace the seeder with backfillEmptyHostGroupIds, an idempotent
    startup repair that runs on every boot so rows from older builds and
    restored backups are healed too. Also rename the leaked internal
    error "host group not found" to "host not found" since groups are not
    a user-facing concept.
  • Bug-label issue sweep: 16 fixes (#6083)
    * fix(xray): block private-range egress in default freedom finalRules (#6037)
    
    With domainStrategy AsIs the router never resolves domains, so a domain
    with a private A record (e.g. 127-0-0-1.nip.io) sails past the
    geoip:private routing block and freedom's allow-all finalRules let it
    reach loopback services such as the xray gRPC API and metrics listener.
    
    Prepend a block rule for geoip:private to the default template and add
    the FreedomFinalRulesPrivateEgressBlock seeder so existing installs
    still carrying the stock allow-only (or legacy private-only-allow)
    finalRules are upgraded in place; customized rules are left untouched.
    
    * fix(sub): version-gate unencrypted-outbound drops in outbound subscriptions (#6033)
    
    Commit d38c912d taught CheckXrayConfig to keep unencrypted vless/trojan
    outbounds when the running core predates the v26.7.11 rejection, but
    filterOutboundsRejectedByCore still consulted the embedded validator
    unconditionally, so outbound subscriptions kept silently dropping those
    outbounds even on downgraded cores.
    
    Apply the same shouldSkipLegacyUnencryptedOutboundRejection gate when
    filtering fetched subscription outbounds.
    
    * fix(xray): resolve geodata assets before building outbound configs (#5928)
    
    Saving routing or template settings validates each outbound through the
    embedded config loader, and a freedom outbound whose finalRules
    reference geoip:private opens geoip.dat during that build. Unlike
    ApplyRoutingConfig, ValidateOutboundConfig and AddOutbound never pointed
    the in-process loader at the bin folder, so xray-core resolved the file
    relative to the panel executable and saving failed with
    'stat /usr/local/x-ui/geoip.dat: no such file or directory'.
    
    Call ensureXrayAssetLocation before both build paths.
    
    * fix(api): use a real i18n key in the client get handler (#5911)
    
    The client fetch endpoint localized its error prefix with the bare key
    'get', which exists in no translation file, so every lookup of a deleted
    client's email logged 'message "get" not found in language ...' noise
    alongside the expected record-not-found warning. Reuse the same
    pages.inbounds.toasts.obtain key the sibling list handler uses.
    
    * fix(sub): carry host record Host header and path into Clash/JSON output (#5944)
    
    The raw-link path overrides the host/path share params from a Host
    record via applyEndpointHostPath, but the Clash and JSON renderers read
    the transport settings object, which applyHostStreamOverrides never
    touched — so a Host record's WebSocket Host header (and path) silently
    vanished from Clash/Mihomo and JSON subscriptions whenever the inbound's
    own ws settings left them empty.
    
    Inject hostHeader/path into the ws/httpupgrade/xhttp settings of the
    per-host stream, mirroring the raw-link override.
    
    * fix(metrics): accept Unicode outbound tags in the observatory (#5972)
    
    The observatory validator whitelisted ASCII word characters, so any
    outbound whose tag carries a flag emoji or other non-ASCII text was
    silently dropped from the metrics snapshot, delay history, and health
    notifications. The history store is an in-process map, so the strict
    charset bought nothing.
    
    Validate tags as non-empty, bounded, control-character-free UTF-8
    instead, keeping spaces and emoji while still rejecting garbage input on
    the query path.
    
    * fix(database): default sqlite to WAL to stop background-job lock storms (#6057, #6068)
    
    With journal_mode=DELETE every write serializes the whole database and
    blocks readers, so under normal multi-job load (traffic sampling, node
    sync, mtproto reconcile) transactions regularly outwaited the 10s busy
    timeout and jobs failed with 'database is locked'.
    
    Move to WAL by default: readers no longer block writers and vice versa,
    which removes the observed contention while writer-writer access still
    serializes safely. The single-file-at-rest property is preserved where
    it matters — Checkpoint() now issues wal_checkpoint(TRUNCATE), so panel
    and Telegram backups read a complete main file, and sqlite folds the WAL
    back into the db on clean shutdown. XUI_DB_JOURNAL_MODE=DELETE restores
    the previous behavior for setups that copy the live file directly.
    
    * fix(database): strip finalmask.tcp from REALITY inbounds on upgrade (#6038)
    
    validateFinalMaskRealityCombo blocks saving finalmask.tcp together with
    REALITY because that combination crashes Xray-core 26.7.11 on the first
    connection (XTLS/Xray-core#6453), but it only runs on add/update. An
    inbound saved before the validator existed sailed through the upgrade
    untouched and took the core down at boot.
    
    Add the InboundRealityFinalmaskTcpStrip seeder: one-time scan that
    removes finalmask.tcp from REALITY inbounds (other finalmask transports
    survive), so upgraded panels start cleanly.
    
    * fix(xray): stop deleting hand-written direct routing rules on save (#6056)
    
    The DNS allow-rule sync recognized 'its' rules purely by shape
    (type=field, ip, port, outboundTag=direct, nothing else), so any manual
    rule of that shape — e.g. routing a LAN CIDR to a NAS port over direct —
    was silently stripped on every settings save.
    
    Mark managed rules with ruleTag=xui-dns-allow (round-tripped untouched
    by both xray-core and the Routing tab editor) and only strip rules that
    carry the tag. Untagged legacy managed rules are adopted when their
    exact ip-set/port matches a currently configured private DNS endpoint;
    anything else is left alone. A stale pre-tag managed rule whose DNS
    server was removed now lingers until deleted manually — the safe side of
    the trade against eating user rules.
    
    * fix(clients): resolve email lookups through client_inbounds after a move (#6059)
    
    GetClientInboundByEmail trusted the client_traffics.inbound_id pointer
    whenever that inbound still existed, but a client moved between inbounds
    leaves the row pointing at its old (still existing) inbound. The lookup
    then searched the wrong inbound's clients and failed with 'Client Not
    Found In Inbound For Email', which broke the Telegram bot's link and QR
    generation for moved clients.
    
    When the pointed-at inbound no longer carries the email, re-resolve
    through the authoritative client_inbounds link to the inbound that
    actually hosts the client.
    
    * fix(nodes): replicate inbound fallbacks to nodes (#5963)
    
    Fallbacks live in the inbound_fallbacks table and were only merged into
    settings by the master's local config builder; the runtime inbound
    pushed to nodes rebuilt settings without them, and the reconcile job
    additionally fingerprinted the raw DB row, so fallback edits neither
    reached nodes nor triggered a re-push.
    
    Inject settings.fallbacks in buildRuntimeInboundForAPI (mirroring the
    local builder, gated on inboundCanHostFallbacks) and make ReconcileNode
    push and fingerprint that same runtime-built payload, aligning the
    interactive and reconcile paths.
    
    * fix(database): survive PostgreSQL outages without a runaway restart loop (#6023)
    
    A PostgreSQL that was down or still starting made InitDB fail instantly;
    the process exited with a generic startup error and systemd restarted it
    every 5s forever, flooding the journal.
    
    Retry the initial postgres connection with backoff (~70s total) and log
    the real driver error on every attempt, and cap the systemd units with
    StartLimitIntervalSec/StartLimitBurst so a persistently unreachable
    database stops the unit instead of looping indefinitely.
    
    * fix(xray): force a full restart when REALITY stream settings change (#6010)
    
    A changed inbound is normally hot-swapped over gRPC as RemoveInbound +
    AddInbound, but xray-core does not reliably rebuild a REALITY listener's
    authenticator on a runtime re-add — key or shortId edits appeared
    applied yet clients kept authenticating against the old parameters until
    someone restarted the core manually, on nodes in particular.
    
    Treat any non-client change to an inbound that uses (or starts using)
    REALITY as not hot-appliable so the panel restarts the core instead.
    Client-only edits on REALITY inbounds keep flowing through the per-user
    AlterInbound path and still avoid restarts.
    
    * feat(sub): allow insecure TLS for outbound subscription fetches (#6067)
    
    An outbound subscription served over HTTPS with a self-signed or
    private-CA certificate could never be fetched: the fetch client had no
    TLS options, so refreshes died with 'x509: certificate signed by unknown
    authority' and there was nothing the admin could toggle.
    
    Add a per-subscription 'Allow insecure' switch (persisted as
    allow_insecure, default off) that sets InsecureSkipVerify on the fetch
    transport — including when the fetch is routed through the panel egress
    proxy. The SSRF-guarded dialer and redirect re-validation stay in force
    either way.
    
    * fix(reality): send PROXY protocol header in the target scanner when xver is set (#6082)
    
    The REALITY target scanner always probed with a plain TLS handshake, so
    a target fronted by an Nginx listener that requires the PROXY protocol
    (matching the inbound's xver>=1) reset the connection and the panel
    reported a false 'TLS handshake failed'.
    
    Thread the inbound's xver into the scan request and, when it is >=1,
    lead with the matching PROXY protocol header (v1 for xver 1, binary v2
    for xver 2) built from the dialed connection's own address pair. Batch
    candidate scans against public sites are unaffected (xver 0).
    
    * fix(frontend): default sockopt fields when editing a stored inbound (#5956)
    
    Opening an existing inbound ran rawInboundToFormValues over the raw DB
    row, and only xhttpSettings was re-parsed through its Zod schema to fill
    defaults. A sockopt object saved before the TProxy control existed has
    no tproxy key, so the Select rendered blank; picking Off didn't help
    because the wire normalizer drops tproxy=off, recreating the missing
    key on the next edit.
    
    Re-parse streamSettings.sockopt through SockoptStreamSettingsSchema on
    load, mirroring the xhttpSettings handling, so absent keys (tproxy,
    tcpcongestion, …) get their schema defaults every time the form opens.
  • fix(database): repair legacy string tgId in inbound settings on upgrade
    Old panel builds and external tools writing directly to the DB store
    tgId as a JSON string; parsing such settings into the strict int64
    Client model fails with "json: cannot unmarshal string into Go struct
    field Client.tgId of type int64" and blocks every client operation on
    that inbound. The one-shot InboundClientTgIdFix seeder already ran on
    existing installs, so the repair is re-registered as
    InboundClientTgIdFix2 to run once more on upgrade, and it now preserves
    numeric string ids instead of zeroing them. The Client model itself
    stays number-only.
  • 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>
  • fix(database): make cross-db migration lossless, transactional, and pre-checked
    migrationModels was missing ClientGroup and ClientGlobalTraffic, so both
    migration directions silently dropped client groups and global client
    traffic; the model list is now extracted to allModels and a parity test
    keeps the two lists from drifting again. MigrateData runs its truncate
    and copy inside one transaction so a failed import rolls back instead of
    leaving the destination truncated (sequences resync after commit since
    setval is non-transactional). New PrepareSQLiteForMigration rejects
    uploads that are not a panel database and AutoMigrates old backups so
    their missing tables cannot break the row copy.
  • feat(xray): update xray-core to v26.7.11 and adapt panel
    Bump xtls/xray-core to 50231eaf (v26.7.11) and the three binary pins
    (DockerInit.sh, release.yml x2) in lockstep.
    
    Adapt the panel to the upstream changes:
    
    - Shadowsocks "none"/"plain" and VMess "none"/"zero" were removed from
      the core. A migration rewrites stored none/plain SS methods to a
      supported cipher and none/zero VMess security to "auto" (on both the
      clients column and inbound settings JSON); the SS build-time heal does
      the same so a row injected after boot cannot brick startup. The removed
      values are dropped from every frontend option list, schema and adapter,
      and coerced to "auto" at the Go link/sub/Clash emit sites and both link
      importers. Fix the CipherType_NONE sentinel that no longer compiles.
    
    - Unencrypted vless/trojan outbounds to a public address are now refused
      by the core. Validate outbounds through the vendored config loader when
      saving the xray template and when storing/merging outbound
      subscriptions, so one such outbound cannot keep the core from starting.
    
    - New TCP finalmask type "xmc" (Minecraft mimicry): add it to the sub
      link allowlist, the frontend enum and the FinalMask form (hostname,
      usernames, required password), and document it.
    
    - streamSettings gained a "method" alias for "network"; canonicalize it
      to "network" at inbound save time and in the form adapters/schema so a
      method-keyed config keeps its transport.
    
    - New root "env" config key is passed through xray.Config, compared in
      Equals, and forces a restart in the hot diff.
    
    - REALITY now defaults minClientVer to 26.3.27; update the form
      placeholder.
  • fix(node): never sweep a node's inbounds before their first adoption
    Adding a node imports nothing; its pre-existing inbounds only become
    central rows on the first clean traffic-sync tick. But any save of the
    node (switching sync mode, picking tags after "Load inbounds from
    node") marks it config-dirty, and the next tick then ran ReconcileNode
    before that first adoption: with zero central rows the delete sweep saw
    every remote tag as undesired and destroyed the node's real inbounds -
    in "all" mode all of them - disconnecting live clients with no
    confirmation, and the master then reported "record not found".
    
    Track the first completed clean sync in nodes.inbounds_adopted_at and
    skip the sweep (pushes still run) until it is set, so "absent locally"
    can no longer be conflated with "deleted on the master". A node that
    has synced before still sweeps normally, including the offline
    last-inbound-deleted case. Existing nodes are seeded as adopted on
    upgrade to keep their behavior unchanged.
    
    Closes #5898
  • fix(database): drop the legacy UNIQUE constraint on inbounds.port
    Inbound.Port carried a unique gorm tag before multi-node existed; the
    tag was removed from the model long ago, but AutoMigrate never drops a
    constraint, so SQLite databases created in that era still physically
    enforce global port uniqueness. On such installs the node-scoped port
    conflict logic is correct yet the raw insert fails - manual "Deploy to
    node" saves and setRemoteTraffic's central-inbound adoption both die
    with "UNIQUE constraint failed: inbounds.port" when two nodes use the
    same port.
    
    Add a SQLite-only migration that drops an explicit unique index on port
    directly, and rebuilds the table (create from the current model, copy
    shared columns, swap) when the constraint is inline, since SQLite can't
    ALTER it away. Fresh databases and Postgres are untouched.
    
    Closes #5894
  • feat(hosts): bulk-add multiple hosts to multiple inbounds (#5677)
    * feat(hosts): bulk-add multiple hosts to multiple inbounds
    
    Allow users to select multiple inbound IDs and enter multiple host
    addresses (with optional per-host port override) in a single form
    submission.
    
    - Add BulkAddHostReq entity and POST /panel/api/hosts/bulk/add endpoint
    - Add AddHostsBulk service with GORM transaction safety
    - Add parseHostAndPort helper (IPv4, bracketed/bracketless IPv6, port)
    - Update HostFormModal to multi-select inbounds and tag-input hosts
    - Wire bulkCreate mutation in HostsPage with existing-host suggestions
    - Register endpoint in api-docs/endpoints.ts and regenerate OpenAPI/Zod
    
    * feat(hosts): group override records by group_id and support group editing
    
    * fix: import Popover in HostList
    
    * fix: use messageApi in HostFormModal
    
    * fix(hosts): resolve 4 bugs found in host-group code review
    
    - fix(schema): allow empty hosts array in BulkAddHostSchema so users can
      save a host without an address (inherits inbound endpoint). The old
      .min(1) was never enforced at runtime since the schema is only used for
      type inference, but the type was incorrect.
    
    - fix(service): validate new inbound IDs in UpdateHostGroup before deleting
      old rows, matching the same check already present in AddHostGroup. Prevents
      orphaned host rows when an invalid inbound ID is supplied on edit.
    
    - fix(service): replace full-table scan in GetHostsByInbound with two
      targeted queries (DISTINCT group_id WHERE inbound_id=?, then
      WHERE group_id IN ?) to avoid loading every host in the DB.
    
    - fix(mutations): remove unused createMut / create export from
      useHostMutations. The /hosts/add endpoint is identical to /hosts/bulk/add;
      only bulkCreate is used by the UI.
    
    * fix(hosts): address code review feedback (optimize bulk inserts, add validation tests, and remove comments)
    
    * fix(fmt): apply gofumpt formatting to model.go and db.go
    
    The previous merge commit incorrectly applied gofmt (tab-aligned) to
    these files. The repository's golangci config requires gofumpt+goimports
    which produces space-aligned struct fields. This commit restores the
    correct gofumpt formatting that matches upstream/main.
    
    * chore(frontend): regenerate API schemas and update lockfile
    
    * fix
    
    * refactor(hosts): dedupe host-group service and tidy frontend
    
    AddHostGroup and UpdateHostGroup shared an identical ~35-field
    model.Host construction and hand-rolled transaction boilerplate
    (tx.Begin plus a committed flag plus a deferred recover/rollback).
    Extract buildHostRows, validateInboundsExist and formatHostAddr, and
    run every mutation through db.Transaction. groupHosts collapses its
    duplicated address/port formatting and create/append fork into one
    path using slices.Contains. Behavior-preserving: host.go drops ~90
    lines with the existing service/controller tests green.
    
    Frontend: drop the Partial union and two as-casts in HostsPage.onSave
    (the modal always passes a full BulkAddHostValues), and remove the
    movable index map in HostList in favor of the table render index arg.
    
    ---------
    
    Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(mtproto): stop persisting a vestigial inbound-level secret
    MTProto is multi-client: mtg's [secrets] config and every share link read only the per-client secrets. The old HealMtprotoSecret regenerated an inbound-level secret on every save, and seedMtprotoSecretsToClients only dropped it for legacy single-secret inbounds, so multi-client inbounds kept a dead secret. That value once leaked into stale links imported into Telegram, which mtg then rejected as "incorrect client random".
    
    Replace HealMtprotoSecret with StripMtprotoInboundSecret (removes the key), strip on save in normalizeMtprotoSecret, and add a one-time stripMtprotoInboundSecrets migration that runs after the seeder so a legacy secret is first preserved onto a client before the inbound-level copy is dropped.
  • feat(mtproto): adopt dolonet/mtg-multi and make MTProto inbounds multi-client
    Replace the upstream 9seconds/mtg sidecar with the dolonet/mtg-multi fork so a single MTProto inbound can serve many per-user secrets. Each panel client is now one named FakeTLS secret in the fork's [secrets] section: clients are first-class (attach/detach, limits, expiry, per-client tg:// links) exactly like every other protocol, mirroring the WireGuard multi-client model. Per-client traffic and online status come from the fork's /stats JSON API (its Prometheus output has no per-user label), fed into the existing email-keyed client_traffics accumulator; an optional throttle caps concurrent connections. A one-time seeder converts each legacy single-secret inbound into a one-client inbound.
    
    The fork ships only linux/darwin amd64/arm64 binaries but is pure Go, so provisioning builds it from source for every supported platform (release.yml, DockerInit.sh) while keeping the panel-expected mtg-<os>-<arch> filename and the 'run' verb, so process.go is untouched. Also fixes a pre-existing update.sh gap that never renamed the mtg binary for armv6/armv7 updates.
  • fix(client): stop duplicate client entries accumulating in inbound settings
    Adding a user to multi-node inbounds could leave 3-6 identical entries
    in one inbound's settings.clients array: addInboundClient appended
    incoming clients unconditionally, and the duplicate-email precheck
    exempts a matching subId (so one identity can span several inbounds),
    so a retried or raced add of the same client re-appended it to an
    inbound that already carried it - on the master and, since nodes run
    the same code, on every node, whose snapshot adoption then copied the
    duplicates back verbatim. The normalized clients/client_inbounds tables
    stayed clean (unique constraints), which is why the phantom rows only
    showed in settings-driven views like the Detach clients modal, where
    duplicate React keys also broke the selection counter.
    
    Three layers: addInboundClient now skips incoming clients whose email
    is already on the target inbound (idempotent re-adds instead of
    duplication), node snapshot adoption collapses duplicate emails before
    writing the central row, and an idempotent startup repair rewrites any
    inbound whose settings still carry duplicates from older builds.
    
    Closes #5770
  • fix(db): clamp traffic counters below int64 max and repair overflowed rows
    A counter pushed past int64 (multi-node setups hit this via historic
    delta-compounding bugs) makes SQLite silently promote the INTEGER cell
    to REAL. From then on the column no longer scans into the Go int64
    field and every reader of client_traffics fails at once: the inbounds
    page, xray restarts, and node traffic sync all return "converting
    driver.Value type float64 to int64".
    
    Two-part fix: every unbounded "up = up + ?" add (local traffic, node
    delta merge, inbound counters, plus the Go-side outbound accumulation)
    now saturates at TrafficMax, a cap safely below math.MaxInt64 so one
    more delta cannot overflow; and a startup repair casts REAL-promoted
    cells back to INTEGER and clamps all traffic counters into
    [0, TrafficMax] across client_traffics, inbounds, outbound_traffics
    and node_client_traffics, restoring access to already-corrupted panels
    without manual sqlite surgery.
    
    Closes #5762
  • fix(node): stop one rejected inbound from starving a node's traffic sync
    A legacy socks inbound (predating the socks-to-mixed protocol rename) fails the node's request validation when pushed. ReconcileNode aborted on the first failed inbound and syncOne then skipped the traffic snapshot entirely and never cleared ConfigDirty, so the whole node re-failed every tick and the master stopped deducting traffic for every client on that node, exactly as reported in #5685.
    
    Three-part fix: ReconcileNode now pushes every inbound and runs the delete sweep even past individual failures, returning the failures joined; syncOne logs a failed reconcile but continues with the traffic pull (dirty stays set, so reconcile retries and the merge stays in its conservative mode); and a migration renames legacy socks inbounds to mixed, which has an identical settings shape, removing the known trigger.
    
    Closes #5685
  • fix(settings): repair legacy path settings that block every settings save
    A subJsonPath (or subPath/subClashPath/webBasePath) stored without its
    leading/trailing slash — written before the slash rules existed, or
    restored from an old backup — fails the frontend's whole-form validation,
    so every save on the Settings page is rejected client-side. The backend's
    CheckValid would normalize the value, but a save request never reaches it,
    leaving the panel wedged until someone edits the database by hand.
    
    Normalize the stored path rows at startup, mirroring CheckValid's slash
    rules. The pass is idempotent and not seeder-gated, since a restored
    backup can reintroduce bad values at any time.
    
    Also add the missing pages.settings.validation.pathLeadingSlash key to
    all 13 locales — the validation error used to render as its raw key.
    
    Closes #5726
  • fix(database): stop noisy per-startup errors in the Postgres server log
    Two statements failed server-side on every panel start after a SQLite to
    Postgres migration, flooding the postgres log even though the Go side
    suppressed them:
    
    - resyncPostgresSequences issued SELECT MAX(id) against client_inbounds,
      whose composite primary key has no id column; Postgres validates the
      SELECT list at parse time, so the WHERE pg_get_serial_sequence(...) guard
      never got a chance to no-op it. Skip models whose GORM schema maps no id
      column before issuing the statement.
    
    - AutoMigrate detects existing columns via information_schema filtered by
      table_catalog = CURRENT_DATABASE(), which misdetects on some setups and
      re-issues ALTER TABLE ... ADD for columns that already exist. HasColumn/
      HasIndex query without that filter and are reliable (the existing
      duplicate-column suppressor depends on exactly that), so skip AutoMigrate
      outright when the table, every column, and every index already exist.
    
    Closes #5665
  • feat(wireguard): multi-client support
    WireGuard inbounds now manage per-client peers using xray-core's native WireGuard users (AddUser/RemoveUser). Each client lives in settings.clients (canonical, like every other protocol) and is projected to peers[] only when emitting the xray config, at level 0 so the dispatcher's per-user traffic/online counters work with no extra plumbing.
    
    Backend: internal/util/wireguard gains KeyToHex (base64 to hex for the gRPC path), PublicKeyFromPrivate and GenerateWireguardPSK; xray/api.go builds a wireguard account in AddUser with hex keys (RemoveUser already worked); client CRUD generates a keypair and allocates a unique tunnel address per client and never rotates keys on edit; an idempotent migration converts legacy settings.peers into managed clients; WireGuard is included in the raw subscription.
    
    Frontend: WireGuard in the add-client modal with keys on the credential tab, client schema, per-client QR/link/.conf, inbound form reduced to server settings; i18n added across 13 locales.
    
    Fix: guard the settings[clients] assertion in add/update so a legacy WireGuard inbound stored without a clients key no longer panics.
  • 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.
  • fix(inbound): convert legacy externalProxy to hosts on import
    An inbound exported from a build that predated the hosts table carries
    its external proxies inline in streamSettings.externalProxy. The startup
    migration that converts those to host rows runs once and is gated off
    afterwards, so it never sees a freshly imported inbound, leaving its
    external proxies stranded in streamSettings (never surfaced as Hosts).
    
    Extract the migration's per-inbound conversion into a shared
    database.CreateHostsFromExternalProxy and run it inside the AddInbound
    transaction. No-op for inbounds without externalProxy (everything the
    current UI builds), so it only fires on such imports.
  • fix(settings): normalize API token timestamps (#5599)
    * fix(settings): normalize API token timestamps
    
    * refactor(api-token): share timestamp threshold
    
    ---------
    
    Co-authored-by: Tomilla <5007859+Tomilla@users.noreply.github.com>
  • feat(iplimit): gate IP limit on fail2ban and reset stale limits
    Per-client IP limit only enforces where fail2ban is installed, so the panel now reports enforceability and disables the field otherwise:
    
    - Add GET /panel/api/server/fail2banStatus (enabled/installed/usable/windows), cached 30s.
    - ClientFormModal and ClientBulkAddModal disable the IP Limit input when not usable and show a hover tooltip; Windows gets a platform-specific message instead of the bash-menu hint.
    - One-time migration ResetIpLimitNoFail2ban zeroes existing client limitIp (inbound settings JSON + clients table) on hosts without fail2ban, where the limit never applied.
    - Drop the recurring '[LimitIP] Fail2Ban is not installed' warning.
    - Add limitIpFail2banMissing/limitIpFail2banWindows/limitIpDisabled across all 13 locales.
  • feat(tls,reality): port xray TLS/REALITY fields, cert-hash helpers, fallback UX
    TLS: add verifyPeerCertByName (vcn) to inbound settings + emit in both share-link generators (frontend + Go sub) and outbound parser; the allowInsecure replacement xray removed after 2026-06-01. Add server-side curvePreferences, masterKeyLog, echSockopt (passthrough + form) at tlsSettings top-level so they survive the panel-only settings strip.
    
    REALITY: add limitFallbackUpload/Download (afterBytes/bytesPerSec/burstBytesPerSec) with per-field tooltips, plus masterKeyLog. Verified field names/semantics against pinned xray v1.260327.1 (bytesPerSec=0 disables).
    
    Hosts: fix verify_peer_cert_by_name column bool->string (xray expects comma-separated names) with an idempotent, history-gate-free migration (SQLite typeof blank; Postgres ALTER once); emit vcn for hosts/external proxies.
    
    Server: add getCertHash (local cert DER SHA-256) and getRemoteCertHash (xray tls ping) endpoints + api-docs; wire pinned-cert field buttons. Drop the meaningless random-hash button.
    
    Xray UI: metrics endpoint (listen/tag) config in Basics; import/export for routing rules and outbounds.
    
    Fallbacks card: compact empty state, header-aligned actions, responsive labeled grid rows.
    
    i18n: add all new keys to every locale; drop unused generateRandomPin.
  • perf(scale): speed up traffic, auto-renew, and node bulk ops at 50k-100k clients
    Local hot paths:
    - autoRenewClients: replace the O(clients x expired) inner scan with an
      email->traffic map lookup (quadratic at scale).
    - node traffic sync: scope the client_traffics email-membership query to the
      snapshot's emails instead of plucking the whole table every poll.
    - add a (expiry_time, reset) index for the per-tick auto-renew filter.
    - SQLite: add cache_size/mmap_size/temp_store pragmas (env-tunable); keep the
      single-file DELETE journal and synchronous=FULL defaults.
    - scale benchmarks now run on SQLite too via XUI_SCALE_TEST=1 (shared
      setupScaleDB/resetScaleTables helpers), not just Postgres.
    
    Node paths:
    - bulk add/delete/adjust on a node-attached inbound folded one HTTP RPC per
      client; above nodeBulkPushThreshold (32) mark the node dirty and let one
      ReconcileNode push converge it instead of O(M) sequential round-trips.
      Small ops keep the live per-client path. Also hoist nodePushPlan out of the
      per-email delete loop.
    - ReconcileNode skips inbounds whose wire payload is unchanged (per-tag
      fingerprint on Remote), guarded by node-side tag presence so a restarted
      node is still re-seeded.
    
    Tests: auto-renew multi-inbound correctness, node-path dispatch (large ops
    fold to dirty, small ops push live) via a manager runtime override seam, and
    reconcile delta-skip.
  • chore(db): use DELETE journal mode so sqlite stays a single file
    Switch sqlite from WAL to DELETE journal mode so the database no longer
    keeps -shm/-wal sidecar files; only x-ui.db remains at rest. Pair with
    synchronous=FULL for crash-safe durability in rollback-journal mode.
    
    The startup PRAGMA journal_mode=DELETE converts existing WAL databases
    and removes their leftover sidecar files on first run, so upgrades need
    no manual cleanup. busy_timeout and _txlock=immediate are unchanged.
  • feat(hosts): managed Hosts for per-host subscription link overrides (#5409)
    * test(sub): characterize current link output (externalProxy + single-link baselines)
    
    Phase 0 of the Hosts feature. Locks current subscription-link output for the
    externalProxy paths (vless/vmess/trojan/ss exact, reality/hysteria by Contains)
    so the upcoming ShareEndpoint refactor can be proven behavior-preserving. These
    must stay green and unedited through every later phase.
    
    * refactor(sub): unify external-proxy link building behind ShareEndpoint (TDD, snapshot-locked)
    
    Phase 1 of the Hosts feature. Collapse the duplicated externalProxy link
    builders (param-form for vless/trojan/ss, object-form for vmess) onto a single
    ShareEndpoint abstraction so Phase 4 can add Host-driven links with ~zero new
    branching.
    
    Design: an externalProxy-derived endpoint carries the original entry map and
    applies it through the UNCHANGED applyExternalProxyTLS{Params,Obj} helpers, so
    output is provably byte-identical. buildExternalProxyURLLinks /
    buildVmessExternalProxyLinks become thin adapters; the genVless/Trojan/SS/Vmess
    call sites are untouched. genHysteriaLink is deliberately left on its own path
    (hex pinSHA256, not pcs). The no-externalProxy default tails are unchanged.
    
    TDD: N1-N4 (externalProxyToEndpoint, inboundDefaultEndpoint, buildEndpointLinks,
    buildEndpointVmessLinks) written failing-first against stubs, then implemented.
    
    Mutation sanity (performed + reverted): dropping the ep-carry in
    externalProxyToEndpoint makes the Phase-0 C1/C2 characterization snapshots go
    red (TLS overrides vanish), proving the snapshots guard the emitted output.
    
    Gate: go test ./internal/sub/... and go test ./... green with ZERO edits to the
    Phase-0 snapshots; go build ./... green on linux and windows; go vet clean.
    
    * feat(model): Host entity + automigrate + openapi codegen (TDD)
    
    Phase 2 of the Hosts feature. Adds the Host GORM model: an override endpoint
    attached to an inbound (address/port + TLS/transport/clash overrides + sub
    scoping), superseding the legacy externalProxy array functionally while leaving
    it intact.
    
    - model.Host with snake_case column tags, json serializer for slices, text for
      free-JSON (mux/sockopt/xhttp), validate tags (remark 1-40, port 0-65535,
      security + mihomoIpVersion enums); TableName "hosts". NodeGuids column is added
      now but unused (host->node scoping deferred to v2).
    - Registered in BOTH initModels() (db.go) and migrationModels() (migrate_data.go);
      the latter is required for cross-DB migration and is easy to miss. PG sequence
      resync iterates the initModels slice, so it is covered automatically.
    - pruneOrphanedHosts() deletes hosts whose inbound_id has no inbound, called
      alongside pruneOrphanedClientInbounds().
    - openapigen manifest: Host added to StructAllow with MuxParams/SockoptParams/
      XhttpExtraParams -> KindAny; regenerated frontend/src/generated/* + openapi.json.
    
    TDD: TestHostTableName, TestHostValidation, TestHostAutoMigrateCreatesColumns
    (+ _Postgres), TestPruneOrphanedHosts written failing-first against a wrong-name,
    untagged, unregistered stub, then implemented.
    
    Gate: go test ./... green on SQLite AND a real Postgres DSN (local container);
    go build/vet/gofmt clean; npm run gen succeeds with the new Host type/schema/
    example/zod; npm run typecheck + npm run test (542) green.
    
    * feat(api): Host CRUD service + controller + routes (TDD)
    
    Phase 3 of the Hosts feature.
    
    - service/host.go (HostService, empty struct + database.GetDB() like
      ClientService): GetHosts, GetHostsByInbound, GetHost, AddHost (verifies the
      inbound exists — no hard FK), UpdateHost (inbound + sort order immutable here),
      DeleteHost, SetHostEnable, SetHostsEnable, DeleteHosts, ReorderHosts (single
      driver-safe transaction), GetAllTags.
    - controller/host.go mirrors NodeController: routes under /panel/api/hosts
      (list/get/byInbound/tags + add/update/del/setEnable/reorder + bulk/setEnable,
      bulk/del), binds via middleware.BindAndValidate so the model validate tags are
      enforced, {success,msg,obj} envelopes.
    - Wired the hosts group into api.go after nodes (inherits checkAPIAuth + CSRF).
    - DelInbound now cascades: deleting an inbound deletes its hosts.
    - Documented all 11 routes in api-docs endpoints.ts (referencing the generated
      Host schema) and regenerated openapi.json; extended TestAPIRoutesDocumented's
      controller->basePath switch for host.go. Backend en toast keys added.
    
    TDD: service tests (Add/GetByInbound, RejectsUnknownInbound, Reorder, Set/Bulk
    enable, DeleteHosts, DeleteInboundCascadesHosts, GetAllTags) written failing-
    first against a nil-returning stub; controller test (AddListGetDelete envelope
    round-trip + AuthInherited 401) added.
    
    Gate: go test ./internal/web/... + go test ./... green; npm run gen + typecheck
    + lint + test (542) + build green.
    
    * feat(sub): render subscription links from hosts; legacy fallback when none (TDD, mutation-checked)
    
    Phase 4 of the Hosts feature. Inserts host resolution between inbound and link
    across all three subscription formats.
    
    Mechanism: hostEndpoints(inbound, format) loads the inbound's enabled hosts
    (filtered by ExcludeFromSubTypes, ordered by sort_order then id) and projects
    each onto the externalProxy entry shape the raw/json/clash renderers already
    consume. So a host fans out one link/proxy reusing the exact existing rendering
    (address/port/security/sni/fp/alpn/pins/ech) with zero new TLS code. Host header
    and path overrides are applied additively in the raw builders (no-op for legacy
    externalProxy, which never carries those keys — characterization snapshots stay
    green). Clash ip-version (MihomoIpVersion) is set last on the proxy.
    
    Integration points:
    - getSubs (raw): per inbound, hostEndpoints AFTER projectThroughFallbackMaster;
      len>0 -> linkFromHosts (renders only the hosts), else legacy GetLink.
    - GetJson/GetClash: inject the host endpoints into the inbound's externalProxy
      before the existing getConfig/getProxies loop.
    - Precedence: hosts win over any legacy externalProxy (injection replaces it).
    
    Backward compat: a zero-host inbound takes the legacy path -> byte-identical
    output (all Phase-0 characterization snapshots unchanged).
    
    TDD: 9 cycles (zero-hosts identical, N-links-ordered with host/path override,
    disabled skipped, host-vs-externalProxy precedence, no-dedup, sort composes with
    SubSortIndex, host-over-fallback, resolve-via-client-inbounds, ExcludeFromSubTypes
    per format) written failing-first against unwired helpers, then wired green.
    
    Mutation sanity (performed + reverted, documented here):
    - zero-hosts fallback: flipping the len(hostEps)>0 guard to >=0 makes
      TestSub_ZeroHosts_IdenticalOutput go red (host path yields "" for no hosts).
    - no-dedup: adding a remark-dedup in hostEndpoints makes TestSub_NHosts_NoDedup
      go red (two distinct hosts collapse to one link).
    
    Gate: go test ./internal/sub/... + go test ./... green with ZERO edits to the
    Phase-0 snapshots; go build green on linux and windows; go vet + gofmt clean.
    
    * feat(migration): seed hosts from inbound externalProxy (TDD, idempotent, dual-driver)
    
    Phase 5 of the Hosts feature. One-time migration so existing installs surface
    their legacy externalProxy entries as first-class Host rows.
    
    - seedHostsFromExternalProxy() is self-gated on a HistoryOfSeeders
      "HostsFromExternalProxy" row (run-once) and wired into runSeeders. For each
      inbound it parses StreamSettings, reads externalProxy[], and creates one Host
      per entry: forceTls->Security (unknown->same), dest->Address, port->Port,
      remark->Remark (generated when blank, capped at 40), sni/fingerprint/alpn/
      pinnedPeerCertSha256/echConfigList copied; SortOrder=index; InboundId set.
    - Additive: externalProxy is left intact in StreamSettings (rollback-safe; the
      sub layer prefers hosts when present, §Phase 4).
    - Postgres: GORM db.Create advances hosts_id_seq via the sequence, so no extra
      resync is needed beyond the existing startup resync.
    
    TDD: field-mapping, idempotency (second run no-op), no-externalProxy->no-hosts,
    externalProxy-kept-intact written failing-first against a stub; plus a
    Postgres counterpart that skips without XUI_DB_DSN.
    
    Gate: go test ./internal/web/service/... ./internal/database/... green on SQLite;
    the *_Postgres tests green against a real Postgres container; go build green on
    linux and windows; go vet + gofmt clean. (Running the whole database package
    under XUI_DB_TYPE=postgres is not supported — the SQLite-path tests share the one
    DSN — so only the t.Skip-gated *_Postgres tests run with the env set.)
    
    * feat(ui): Hosts page + schema + query hooks + link preview helper (TDD on schema/helpers)
    
    Phase 6 of the Hosts feature — the admin UI.
    
    - schemas/api/host.ts: HostFormSchema (validation: remark 1-40, tags ^[A-Z0-9_:]+$
      ≤10×≤36, port 0-65535, security/mihomoIpVersion enums, alpn/fingerprint reused
      from the shared primitives) + a loose HostRecordSchema/HostListSchema for reads.
    - lib/hosts/host-link.ts: hostToExternalProxyEntry — the frontend mirror of the
      backend hostToExternalProxyMap (security->forceTls, sni override rules, port
      inherit), for share-link previews.
    - api/queries/useHostsQuery.ts + useHostMutations.ts (mirror the node hooks):
      list/get + add/update/del/setEnable/reorder/bulk; queryKeys.hosts.* added;
      mutations invalidate keys.hosts.root().
    - pages/hosts/{HostsPage,HostList,HostFormModal}.tsx (+CSS) mirroring pages/nodes:
      list with remark · address:port · inbound · security · tags · enable Switch ·
      per-inbound move up/down (reorder) · bulk enable/disable/delete; form grouped
      into Basic / Advanced / Clash / Subscription-scope sections.
    - Route '/hosts' + sidebar item (Global icon); menu.hosts + pages.hosts.* added to
      the en-US bundle (other locales fall back to English until translated).
    
    TDD: HostFormSchema (10 cases) and hostToExternalProxyEntry (6 cases) written
    failing-first, then implemented. UI verified by lint/typecheck/test/build.
    
    Deferred (documented enhancement): the live in-form share-link preview (needs
    inbound+client context) and a per-host host/path override in JSON/Clash output
    (raw already overrides; JSON/Clash inherit the inbound's host/path).
    
    Gate: cd frontend && npm run lint && npm run typecheck && npm run test (557) &&
    npm run build all green; go build ./... + go test ./... still green.
    
    * refactor(ui): remove the External Proxy form from the inbound stream settings
    
    Hosts supersede the legacy externalProxy: the subscription renders from hosts
    (hosts win when both exist) and the migration converts existing externalProxy
    entries to hosts. externalProxy's only real consumers were the subscription
    (now covered) and this form's preview — the backend per-client copy-link never
    used it — so removing the editor has no functional regression.
    
    - Drop ExternalProxyForm + toggleExternalProxy from InboundFormModal and delete
      the orphaned form component + its export; remove its block test + snapshot.
    - KEEP the externalProxy schema field and backend parsing/link-generation: an
      existing inbound's externalProxy still round-trips through the form (not
      silently destroyed on edit) and still renders if a host was removed.
    
    Gate: cd frontend && npm run typecheck + lint + test (556) + build green.
    
    * fix(ui): use Alert `title` instead of deprecated `message` (antd 6)
    
    Ant Design 6 deprecated <Alert message=> in favor of <Alert title=>; the panel
    was mid-migration (21 Alerts already on title). Renamed the 7 remaining stragglers
    across 5 files (SubLinksModal, InboundFormModal, sockopt, EmailTab, TelegramTab),
    silencing the runtime deprecation warning. description= is unchanged.
    
    Pre-existing warning, surfaced while testing Hosts — not introduced by it.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): align Hosts page with Clients/Inbounds cards + reorder columns
    
    - page-shell.css never listed .hosts-page, so the Hosts page got no content
      padding / transparent-layout / summary-card spacing. Add a .hosts-page shell
      block (background, dark/ultra vars, content-area + summary-card padding). This
      is the actual "card spacing" bug.
    - HostList: match the Clients/Inbounds list card — hoverable + the toolbar moved
      into the card title as a .card-toolbar (Add when nothing selected; selected
      count + bulk enable/disable/delete on selection). Re-declare .card-toolbar in
      HostList.css since the shared rule lives in a lazily-loaded page stylesheet.
    - Reorder table columns as requested: Actions, Enable, then Remark, Endpoint,
      Inbound, Security, Tags. Added scroll x for narrow screens.
    - HostsPage: add a summary card (Total / Enabled / Disabled) like the other
      pages. New i18n keys: pages.hosts.selectedCount + pages.hosts.summary.*.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): use Tabs instead of Collapse in the Add/Edit Host form
    
    The Basic / Advanced / Clash / Subscription-scope sections are now tabs. Each
    pane sets forceRender so all fields stay mounted — required because the form
    uses preserve=false, so an unmounted tab's values would otherwise be dropped on
    submit (and a required field on a hidden tab still blocks submit).
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): split Host form into Security + Advanced tabs; drop unused JSON fields
    
    - Remove the Mux/Sockopt/XHTTP raw-JSON fields from the Host form: they were not
      wired into link generation and the inbound's structured editors are inbound-
      specific (not reusable). The DB columns + read schema + generated type stay, so
      they can get proper editors later. (HostFormSchema drops them; HostRecordSchema
      keeps them.)
    - Reorganize tabs to Basic / Security / Advanced / Clash / Subscription scope:
      Security holds the TLS/cert fields (security, sni, sni-overrides, alpn,
      fingerprint, pins, verify-by-name, ech); Advanced now holds the transport
      overrides (host header, path).
    - i18n: add pages.hosts.sections.security; drop the 3 unused field labels.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * style(ui): restore Mux/Sockopt/XHTTP fields in the Host Advanced tab
    
    Put the three free-JSON override fields back, in the Advanced tab next to host
    header / path (as JSON inputs — the inbound's structured editors aren't reusable
    here). Re-added to HostFormSchema + defaults + the i18n labels.
    
    Gate: npm run typecheck + lint + test (556) + build green.
    
    * feat(hosts): add allowInsecure (rendered) + serverDescription/mihomoX25519/vlessRouteId fields
    
    Closes most of the Remnawave-host gap analysis.
    
    - model.Host: + allowInsecure, serverDescription (≤64), vlessRouteId (0-65535),
      mihomoX25519. Auto-migrated (SQLite + Postgres verified); openapi regenerated.
    - allowInsecure is fully RENDERED into subscription output (TDD):
      - raw link: allowInsecure=1 (TLS/Reality, skipped for none) via the endpoint
        builder;
      - JSON/Clash: applyExternalProxyTLSToStream writes tlsSettings.settings.
        allowInsecure, and clash applySecurity now emits skip-cert-verify for the tls
        case (it previously only did so for Hysteria — a pre-existing gap, so inbound
        allowInsecure now renders for vless/trojan/ss clash too).
    - Frontend: the four fields added to the Host form (allowInsecure → Security,
      serverDescription → Basic, vlessRouteId → Advanced, mihomoX25519 → Clash);
      serverDescription shown under the remark in the list. Schema + i18n updated.
    
    serverDescription / vlessRouteId / mihomoX25519 are stored + editable; their
    deeper rendering (and per-host mux/sockopt/xhttp into JSON/Clash, plus a per-host
    xray JSON template) are tracked as follow-ups.
    
    Gate: go test ./... green (SQLite + Postgres for the host schema/migration);
    go build linux+windows; go vet + gofmt clean; npm run gen + typecheck + lint +
    test (556) + build green; generated files in sync.
    
    * feat(sub): render host sockopt + xhttp-extra params into JSON/Clash output (TDD)
    
    A host's sockoptParams and xhttpExtraParams (free-JSON) now take effect:
    applyHostStreamOverrides injects sockopt into the per-host stream (re-added since
    the base stream strips it) and merges xhttpExtraParams into xhttpSettings, called
    in both getConfig (JSON) and getProxies (Clash) right after the per-host TLS
    apply. No-op for legacy externalProxy entries (keys absent) — characterization
    snapshots unchanged.
    
    mux rendering is outbound-level (overrides outbound.Mux) and needs a genVless/
    genVnext/genServer signature change — deferred, along with the per-host xray
    JSON template.
    
    Gate: go test ./internal/sub/... + go test ./... green (snapshots unchanged);
    go build + vet + gofmt clean.
    
    * feat(sub): render host muxParams as a per-host JSON outbound mux override (TDD)
    
    genVnext/genVless/genServer take a muxOverride: a host's muxParams (when valid
    JSON) overrides the global mux on its JSON outbound; empty falls back to the
    panel mux (behavior unchanged for non-host configs). Completes the host
    mux/sockopt/xhttp trio. Test call sites updated for the new signature.
    
    Gate: go test ./internal/sub/... + go test ./... green (snapshots unchanged);
    go build + gofmt clean.
    
    * style(ui): show Host security fields conditionally per security (like externalProxy)
    
    * feat(sub): apply host SNI + fingerprint override for reality (TDD)
    
    A reality host now overrides SNI and fingerprint while inheriting publicKey/
    shortId from the inbound (reality keys can't be host-supplied). Previously the
    reality link kept the inbound's serverName because the TLS appliers are gated to
    security=="tls".
    
    - raw: applyEndpointRealityParams sets sni/fp on the params for reality;
    - JSON/Clash: applyHostStreamOverrides sets realitySettings.serverName +
      serverNames from the host SNI.
    
    Gated to host endpoints via an isHost marker on the synthesized ep, so the legacy
    externalProxy path stays byte-identical (characterization snapshots unchanged).
    The marker is internal and never emitted.
    
    Gate: go test ./internal/sub/... + go test ./... green; go build + vet + gofmt clean.
    
    * fix(ui): start the Host inbound select unselected instead of showing 0
    
    A new host left inboundId defaulting to 0, so the Select rendered "0". inboundId
    is now optional in the form (undefined until chosen), so it shows its
    placeholder ("Select an inbound"); the required rule still enforces a choice on
    save. Port keeps 0 (means "inherit the inbound's port").
    
    Gate: npm run typecheck + lint + build green.
    
    * fix(ui): drop redundant :port suffix from the Host inbound select label
    
    The inbound tag (e.g. in-59303-tcp) already carries the port, so the appended
    ":59303" was duplicated. Show just the remark/tag.
    
    Gate: npm run typecheck + lint + build green.
    
    * style(ui): apply the shared card hover shadows to the Hosts page
    
    page-cards.css scoped its card styling + hover shadows to each page class but
    not .hosts-page, so Hosts fell back to antd's default hoverable (a larger/blurry
    shadow + pointer cursor). Add a .hosts-page block matching the other pages.
    
    Gate: npm run build green.
    
    * feat(hosts): move Tags to Basic tab, add Nodes field, accept VLESS route ranges
    
    - Move the Tags field into the Host form's Basic tab and add a Nodes
      multi-select (visual-only assignment, backed by the existing node_guids
      column) so the Basic tab matches the reference layout.
    - Replace the single-port vlessRouteId integer with a free-form vlessRoute
      string that accepts comma-separated ports/ranges (e.g. 53,443,1000-2000);
      format-validated on the frontend, stored verbatim on the backend.
    - Regenerated frontend types/openapi from the changed model.
    
    * feat(hosts): structured editors for Mux/Sockopt/XHTTP + new Final Mask
    
    Replace the raw JSON textareas in the Host form's Advanced tab with the same
    structured editors used elsewhere, under a nested tabbed layout (General / Mux /
    Sockopt / XHTTP / Final Mask), mirroring the Sub-JSON settings tab:
    
    - Mux: the Sub-JSON mux editor (enable + concurrency/xudpConcurrency/xudp443).
    - Sockopt + XHTTP: reuse the outbound SockoptForm / XhttpForm, wrapped in an
      isolated form that serializes the edited subtree back to the host's JSON
      string (pruned so the override stays sparse).
    - Final Mask: new host field (model + column + JSON-render wiring that merges
      the masks into the host's JSON-subscription stream), edited via the shared
      FinalMaskForm like the Sub-JSON Final Mask editor.
    
    Each editor stays a controlled value/onChange component bound to its existing
    host JSON string field; backend rendering of mux/sockopt/xhttp is unchanged.
    
    * feat(hosts): drop XHTTP + Xray-JSON-template overrides; fix mobile form layout
    
    Remove the host's XHTTP extra-params and Xray-JSON-template overrides entirely
    (model fields + columns, JSON-subscription render paths incl. hostTemplateOutbound,
    schema, form tab/field, i18n, openapi codegen, and their tests) — they did not
    fit the host model. Mux, Sockopt and Final Mask stay as structured editors.
    
    Mobile fixes for the Edit Host modal:
    - responsive width (95vw on mobile, was a fixed 760px that overflowed the
      viewport and clipped the tabs/labels) + a scrollable body so the footer stays
      on screen;
    - Mux fields use responsive Row/Col (stack on mobile) instead of a fixed-width
      label grid.
    
    * fix(hosts): hide the spurious horizontal scrollbar in the Edit Host modal
    
    Setting overflowY:auto on the modal body forced overflow-x to auto too (CSS
    rule), so antd Row's negative gutter margins triggered a horizontal scrollbar.
    Pin overflowX:hidden.
    
    * feat(hosts): inbound-style responsive field layout + icon empty state
    
    - Host form (main form + Mux/Sockopt/Final Mask editors) now use the inbound
      form's label layout: label beside the input on desktop (labelCol sm span 8 /
      wrapperCol sm span 14, right-aligned), stacked label-above-input on mobile.
      Rewrote HostMuxForm onto an internal antd Form so it follows the same layout
      instead of a manual grid.
    - Empty hosts table now shows the host icon + the shared 'Nothing here yet'
      (noData) text, matching Nodes/Inbounds/Clients, replacing the bespoke
      'No hosts yet…' string.
    
    * fix(hosts): avoid nested <form> in the Edit Host modal
    
    The Mux/Sockopt/Final Mask editors each render their own antd Form inside the
    host's main Form, producing an invalid nested <form> DOM node (hydration
    warning). Render those inner forms with component={false} so they keep the form
    instance/context but emit no <form> element.
    
    * fix(hosts): make the Mux enable toggle work
    
    The Switch's checked state came from Form.useWatch('mux'), but the mux object
    field had no registered Form.Item while disabled, so setFieldValue never
    notified the watcher and the toggle stayed off. Bind the Switch to a real
    name='enabled' field (antd drives its checked state directly) and keep the
    sub-fields registered via hidden={!enabled}, serialized to the flat mux JSON.
    
    * refactor(hosts): reuse the outbound MuxForm instead of a bespoke Mux editor
    
    The Mux fields duplicated the outbound MuxForm. Reuse it through the same
    wrapper as Sockopt: generalize OutboundSubtreeJsonForm with defaultSubtree
    (pre-fill on enable) and a serialize hook, and have HostMuxForm render MuxForm
    at the ['mux'] path. The host keeps its inherit-when-off semantics by storing ''
    unless mux.enabled. Also drops the now-unused enableSwitch path from the
    wrapper (only the removed XHTTP editor used it).
    
    * style(hosts): use default-width Port input like the inbound form
    
    The host Port used width:100% (full width); the inbound's numeric inputs use
    antd's default width. Drop the override so Port matches. The Mux number inputs
    already use the default width via the reused MuxForm.
    
    * refactor(sockopt): readable customSockopt editor as a shared component
    
    The customSockopt rows were a single cramped Space.Compact line and duplicated
    verbatim in the inbound and outbound sockopt forms. Extract a shared
    CustomSockoptList that renders each entry as a titled group of labeled fields
    (System / Level / Opt / Type / Value), matching the rest of the form, and use it
    in both (and thus the host Sockopt editor).
    
    * fix(finalmask): drop the empty Custom Tables tag on a new sudoku mask
    
    The sudoku TCP-mask default seeded customTables: [''] (one empty string), which
    rendered as a blank removable tag. Seed [] instead.
    
    * fix(sockopt): make the outbound (and host) Sockopt client-only
    
    Per the XTLS sockopt docs, tproxy / acceptProxyProtocol / V6Only /
    trustedXForwardedFor only apply to an inbound (listening socket); they are
    meaningless on an outbound/dialer. Drop them from the outbound SockoptForm
    (which the host reuses). The Sockopt default object still seeds those keys, so
    the host also strips them on serialize, keeping its override honest to the
    server/client split. The inbound SockoptForm is left unchanged.
    
    * fix(sockopt): make the inbound Sockopt server-only
    
    Complete the server/client split: drop the outbound/dialer-only fields from the
    inbound SockoptForm — dialerProxy, domainStrategy, interface, addressPortStrategy,
    happyEyeballs, tcpMptcp (client-only since Go 1.24 auto-enables MPTCP on listen).
    mark stays (xray applies SO_MARK on inbound sockets too). Update the form-blocks
    snapshot to the server-side field set (intentional spec change).
    
    * feat(hosts): populate Sockopt dialerProxy with the panel's outbound tags
    
    The host Sockopt editor reused the outbound SockoptForm with outboundTags=[],
    so the dialerProxy dropdown was empty. Feed it the panel's outbound tags via
    the existing useOutboundTags hook (shares the cached xray-config query;
    blackhole excluded), so a host can chain through a subscription outbound by tag.
    
    * fix(hosts): empty-state styling on direct load + exclude balancers from dialerProxy
    
    - .card-empty was only defined in lazily-loaded Clients/Inbounds/Nodes
      stylesheets, so a direct /hosts refresh rendered the empty table state
      unstyled (faint + uncentered) until another page was visited. Re-declare it
      in HostList.css so it's correct on first load.
    - The Sockopt dialerProxy dropdown listed balancer tags (useOutboundTags merges
      them in for mtproto egress). dialerProxy chains a single outbound, so balancers
      aren't valid — switch to useOutboundTagGroups and use only the outbound group.
    
    * fix(outbounds): icon + 'Nothing here yet' empty state; stop fading other pages
    
    The Outbounds empty state was a faint '—', and OutboundsTab.css set the global
    .card-empty to opacity:0.4 — which leaked onto whichever page's empty state was
    shown after the Outbounds CSS had loaded (e.g. Hosts went faint after visiting
    Outbounds). Render the icon + noData ('Nothing here yet') like the other lists,
    and align .card-empty to the shared centered/secondary style (no opacity).
    
    * fix(outbounds): custom empty state on the desktop table too
    
    The desktop Outbounds Table had no locale.emptyText, so it showed antd's
    default 'No data' box. Add the same ExportOutlined + noData empty state as the
    card (mobile) view.
    
    * style(sidebar): use ExportOutlined for the Outbounds nav item
    
    The Outbounds sidebar item used UploadOutlined (an upload tray). Switch to
    ExportOutlined, matching the outbound icon now used in the routing target and
    the outbounds empty states.
    
    * feat(hosts): icons on the form tabs (icon-only on mobile)
    
    Wrap every Host form tab label (Basic/Security/Advanced/Clash/Subscription
    scope and the nested General/Mux/Sockopt/Final Mask) with catTabLabel, so the
    tabs show icon + text on desktop and just the icon (with a tooltip) on mobile,
    matching the Settings/Xray tab bars.
    
    * refactor(hosts): fold Exclude-from-formats into Advanced, drop the one-field tab
    
    The Subscription scope tab held only excludeFromSubTypes after Tags moved to
    Basic — a niche per-format scoping knob. Move it into the Advanced > General
    sub-tab and remove the standalone tab (and its now-unused subScope label/icon).
    
    * feat(sub): per-client remark template variables; drop the remark model & Show Usage Info
    
    * fix(migration): cap seeded host remark at the model's 256-char limit, not 40
  • feat(nodes): per-node client IP attribution for IP-limit
    Record each panel's own Xray IP observations under its panelGuid and merge each node's guid-keyed report on the master, so the panel can tell which node a client IP is connecting through (the flat inbound_client_ips union is pushed back to every node and cannot attribute). Adds the NodeClientIp model + migration, the clientIpsByGuid endpoint and node-sync merge, node-name labels in the client IP log, and cleanup on node deletion.
  • feat(sub): per-client external links and remote subscriptions
    Add a Links tab to the client form for attaching third-party share
    links and remote subscription URLs per client. They are merged into
    the client's raw/JSON/Clash subscription output: links are emitted
    verbatim and parsed for JSON/Clash; subscription URLs are fetched
    (cached, with a short timeout) and their configs merged in.
    
    i18n keys added across all 13 locales.
  • fix(tgbot): clear legacy panelProxy/tgBotProxy settings on upgrade
    v3.3.1 removed the Panel Proxy URL field from the UI but left the stored
    panelProxy/tgBotProxy values in the DB. The Telegram bot still reads
    tgBotProxy directly, so a stale value masked the panelOutbound egress
    fallback. Add a one-off seeder to drop both rows.
    
    Closes #5266
  • feat(sub): per-inbound sort order for subscription links
    Add a subSortIndex field to inbounds that controls the order of links
    in subscription output only: the raw sub body, the HTML sub page, and
    the JSON/Clash formats (all served from the same query). Lower values
    come first; ties keep id order. The panel inbound list is unaffected.
    
    The value is editable in the inbound form next to the share-address
    fields, propagates to nodes via wireInbound, and follows the usual
    node-sync rules (copied on import, mirrored while not dirty, never a
    structural change).
    
    Rescoped from #5214 by @Ponywka.
  • feat(node-sync): push global client usage to nodes for display and local enforcement
    A client attached to several panels has one aggregated row on each
    master, but a node only ever saw its local share: the node UI
    under-reported usage, and the node kept serving a client whose
    cross-panel total had already exceeded its quota — the master's disable
    push doesn't kill established connections unless the node restarts xray
    itself.
    
    Masters now push their aggregated per-client counters to each node from
    NodeTrafficSyncJob (throttled, scoped to the clients that node hosts).
    The node stores them in the new client_global_traffics side table keyed
    by (masterGuid, email), overwritten on every push so a master-side
    reset propagates, and:
    
    - overlays max(local, pushed) onto UI read paths (slim inbound list,
      inbound detail, clients list, WS stats, per-email lookups). The full
      /panel/api/inbounds/list stays un-overlaid on purpose: it doubles as
      the traffic snapshot masters poll, and overlaying it would corrupt
      every master's delta accounting;
    - trips disableInvalidClients when any master's pushed total exceeds
      the client's quota, so the existing RestartXrayOnClientDisable flow
      disconnects the client locally;
    - clears the side rows on traffic reset, auto-renew, and client
      delete, keeping a renewed quota window clean.
    
    Supersedes #5204, which folded pushed globals into client_traffics and
    compensated with read-back baselines — that double-counted first-sight
    emails and could not work with several masters sharing one node.
  • refactor: replace custom geo manager with Xray-core native geodata auto-update
    Remove the panel-side custom geo download feature (service, controller,
    /panel/api/custom-geo/* endpoints, CustomGeoResource model, UI tab) in
    favor of Xray-core's native geodata section
    (https://xtls.github.io/config/geodata.html).
    
    - pass the top-level "geodata" key through xray.Config so it survives
      the template round-trip into the generated config
    - add a Geodata Auto-Update section to the Xray Updates modal that
      edits geodata (cron schedule, download outbound, asset list) in the
      config template and restarts Xray on save
    - previously downloaded geo files in the bin folder keep working in
      ext: routing rules; the orphaned custom_geo_resources table is left
      in place so existing source URLs stay recoverable
  • 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.