Commit Graph
3110 Commits
  • fix(inbound): scope port-conflict check to the stored node on update (#5833)
    * fix(inbound): scope port-conflict check to the stored node on update
    
    UpdateInbound called checkPortConflict before restoring the inbound's NodeID
    from the database, so the check used the NodeID from the request body. That
    value is unreliable for edits: clients omit it (nodeId is `json:",omitempty"`)
    and the code already treats the stored NodeID as authoritative — an inbound
    can't be moved between nodes via edit. With a nil request NodeID a node inbound
    was mis-checked as a local/main-panel inbound and falsely collided with an
    unrelated inbound that happened to reuse the same port on the central panel (or
    another node). Symptom: editing a node inbound's listen address was rejected
    with "port <p> (tcp) already used by inbound ... " and silently discarded.
    
    Load the old inbound and restore inbound.NodeID *before* checkPortConflict, so
    the check runs against the node the inbound actually lives on. checkPortConflict
    already scopes candidates by node (sameNode); it was simply being fed the wrong
    NodeID.
    
    Add a regression test that seeds a main-panel and a node inbound on the same
    port and asserts the node inbound stays editable (fails before this change with
    the exact "already used" rejection).
    
    * style(inbound): trim inline comments from port-conflict scoping
    
    Repo convention forbids // line comments in committed Go; keep the scoping fix self-documenting.
  • fix(sub): include native WireGuard clients in Clash and JSON subscriptions (#5676)
    The Clash (buildProxy) and JSON (getConfig) subscription generators had no
    WireGuard branch, so a native WireGuard inbound's clients were silently
    dropped: buildProxy hit its default nil case, and getConfig emitted a config
    with no proxy outbound. Only the raw subscription (genWireguardLink) and
    external-link Clash path handled WireGuard.
    
    Add a WireGuard case to both generators, mirroring genWireguardLink: the peer
    public key is derived from the inbound secretKey, while the private key, tunnel
    address (mihomo ip/ipv6, Xray settings.address), pre-shared key and keep-alive
    come from the client. The peer routes the full tunnel (0.0.0.0/0, ::/0), which
    both mihomo and Xray also default to.
    
    Field names verified against the mihomo WireGuardOption source (private-key,
    public-key, pre-shared-key, persistent-keepalive, ip, ipv6, mtu, dns) and the
    Xray wireguard outbound schema (secretKey, address, peers[].publicKey/endpoint/
    preSharedKey/keepAlive/allowedIPs, mtu).
  • fix(wireguard): build peers in GenXrayInboundConfig so node reconcile keeps clients (#5684)
    Adding a WireGuard client on the master broke every WireGuard connection on
    the sub-node until Xray was manually restarted on the node. Adding the same
    client directly on the node worked.
    
    Root cause: the panel stores WireGuard clients under the settings key
    `clients` (the shape every other protocol uses), but xray-core's wireguard
    inbound is configured with `peers`. The `clients`->`peers` conversion lived
    only in the full-config generation path (XrayService.GetXrayConfig), which
    runs on a full Xray restart. The live gRPC AddInbound path goes through
    (*Inbound).GenXrayInboundConfig, which passed the WireGuard settings verbatim
    - with `clients` and no `peers`.
    
    Why the master path broke it and the node path did not:
    - Adding on the node is a single safe operation: AddInboundClient -> AddUser
      -> AlterInbound{AddUser} -> wireguard.Server.AddUser, which appends one peer
      via IPC without touching the others. The inbound is local (NodeID == nil),
      so nothing is marked dirty and no reconcile runs.
    - Adding on the master does two things: it pushes the client to the node
      (the same safe hot-add, which succeeds), and it marks the node dirty. The
      reconcile then pushes panel/api/inbounds/update/:id to the node, whose
      InboundService.UpdateInbound applies it live via DelInbound + AddInbound
      (buildRuntimeInboundForAPI -> Local.AddInbound -> GenXrayInboundConfig).
      That re-adds the wireguard inbound with zero peers, wiping the device and
      dropping every connected client. A manual restart regenerated the full
      config, converted clients to peers, and restored them - hence "only a
      restart fixes it".
    
    Fix: convert WireGuard `clients` to `peers` in GenXrayInboundConfig itself,
    the single chokepoint for every live AddInbound (create, edit, node
    reconcile). WireguardClientsToPeers always rebuilds `peers` from `clients`
    (matching GetXrayConfig field for field) and drops the `clients` key. It does
    not gate on `peers` being absent: the panel seeds every WireGuard inbound with
    an empty `peers: []` placeholder (frontend inbound-defaults), so a
    "skip if peers present" guard would match that placeholder and make the
    conversion never run, leaving the live path emitting zero peers. The
    conversion stays idempotent by removing `clients`, so a second call - or an
    inbound with no `clients` - is a no-op, leaving the full-config path
    unaffected. This also fixes plain WireGuard inbound edits on a standalone
    panel, which went through the same peerless rebuild.
  • ci(claude-bot): auto-fix trusted PRs and easy issue bugs
    Split the review-only handle-pr job into handle-pr-fix (owner/member/collaborator PRs: apply refactors and bug fixes directly, commit to the PR branch, no suggestion blocks) and handle-pr-review (external/fork PRs: one review-only comment, no suggestions, no code checkout).
    
    Upgrade handle-issue to open a fix PR for easy bugs (pushed via CLAUDE_BOT_PAT so pull_request CI runs on it), confirm the root cause and tag the maintainer for big bugs, and never open a PR for feature or enhancement requests.
  • 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(inbounds): apply runtime changes after the DB commit (#5768)
    * fix(inbounds): apply runtime changes after commit
    
    * ci: fix staticcheck findings
  • chore(frontend): bump dependencies
    Routine version bumps: i18next, msw, typescript-eslint, vitest and
    @vitest/coverage-v8 to their latest patch/minor releases, with the
    lockfile regenerated to match.
  • chore: add golangci-lint tasks and force LF on Go files
    Add VS Code tasks to run golangci-lint (with and without --fix) and mark
    *.go as text eol=lf so Go sources check out with LF, avoiding spurious
    CRLF lint failures on Windows. Also drop the now-redundant explicit
    DockerInit.sh/DockerEntrypoint.sh entries already covered by *.sh.
  • refactor: modernize Go with strings.SplitSeq and maps.Copy
    Replace strings.Split loops with strings.SplitSeq iterators in the CSV
    parsers (reality_scan and the scale-test helpers) and swap a manual map
    copy for maps.Copy in the MTProto traffic collector. No behavior change;
    these are the fixes the modernize analyzer reports.
  • fix(clients): surface bulk-reset auto-enable failures (#5763)
    * fix(clients): surface bulk-reset auto-enable failures
    
    BulkResetTraffic re-enables a disabled client before resetting its
    traffic, but discarded the s.Update result with `_, _ =`, so a failed
    re-enable was silent: the client stayed disabled with nothing logged,
    unlike the single-client ResetTraffic path which already warns on the
    same call. Check the error and log a warning to match, and add a
    regression test covering BulkResetTraffic's previously-untested
    re-enable path.
    
    * ci: update Go toolchain for govulncheck
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(clients): parse only settings.clients across protocols (#5855)
    * fix(clients): parse only settings.clients across protocols
    
    Several inbound settings readers decoded the whole settings object into map[string][]model.Client. Real protocol settings include scalar keys such as VLESS decryption and Hysteria version, so that shape can fail before callers reach settings.clients or leave them relying on decoder side effects.
    
    Add one shared helper that extracts only the clients field through json.RawMessage, then use it from GetClients, SearchClientTraffic and the IP-limit job fallback paths. Regression tests cover VLESS and Hysteria settings with scalar protocol fields.
    
    * fix(clients): reject empty inbound settings
  • fix(inbound): reject finalmask + REALITY combo (crashes Xray-core) (#5861)
    * fix(inbound): reject finalmask configured together with REALITY security
    
    finalmask wraps the connection before REALITY's own handshake takes
    over (TcpmaskManager.WrapListener -> WrapConnServer runs at Accept()
    time, ahead of reality.Server()). reality.Server() does an unchecked
    type assertion assuming a raw *net.TCPConn; with finalmask in front,
    that assertion panics and takes down the entire xray-core process on
    the very first connection to the inbound - not just that connection.
    
    Upstream (XTLS/Xray-core#6453) confirmed this will be documented as
    unsupported rather than made graceful, so the panel needs to stop this
    combination from being saved rather than relying on docs.
    
    AddInbound/UpdateInbound now reject streamSettings with
    security=reality and a non-empty finalmask.tcp/udp with a clear error
    instead of letting it reach Xray.
    
    Related: MHSanaei/3x-ui#5857
    
    * fix(inbound): heal legacy rows and narrow the finalmask+REALITY guard
    
    Per review feedback on #5861:
    
    - Narrow the check to finalmask.tcp only. xray-core's TcpmaskManager
      (the thing that wraps the TCP listener ahead of REALITY's handshake,
      the actual cause of the panic) is only constructed when tcp masks
      are present; a finalmask.udp-only config never touches that accept
      path and doesn't reproduce the crash, so it shouldn't be rejected.
      Extracted the shared check into finalMaskRealityTcpMasks() so both
      the save-time guard and the config-build heal below use one
      definition of "dangerous".
    
    - Heal already-saved bad rows in GetXrayConfig(), the same way
      liftXhttpSessionIDKeys and HealShadowsocksClientMethods heal other
      legacy data at config-build time. AddInbound/UpdateInbound only cover
      the two save paths - a row that already carries this combination
      (saved before this guard existed, synced from a node, restored from
      a backup, or edited directly in the DB) would still crash Xray-core
      on the next restart without this.
    
    - Add end-to-end tests exercising AddInbound, UpdateInbound, and
      GetXrayConfig directly (seeding rows through the real DB) rather
      than only unit-testing the extracted helper in isolation, so a
      wiring regression in any of the three call sites gets caught.
  • fix(routing): allow dns.servers on private IPs past the geoip:private block rule (#5774)
    * fix(routing): allow dns.servers on private IPs past the geoip:private block rule
    
    Xray's own DNS client traffic is dispatched through the same routing
    table as proxied client traffic. When dns.servers points at a private
    IP (e.g. a self-hosted AdGuard Home / Pi-hole reachable on the same
    Docker network as Xray) and the panel's default geoip:private block
    rule is active, Xray's own DNS lookups get silently dropped. Xray then
    falls back to dialing destinations by raw hostname once its internal
    DNS attempt times out (~4s), so proxied connections still work, just
    with a multi-second stall added to every new domain-based connection,
    with no error surfaced anywhere.
    
    EnsureDnsServerRouting keeps a managed "direct" allow-rule for any
    private literal IP found in dns.servers, inserted immediately before
    the geoip:private block rule (matched by shape, not position). It only
    acts when both ingredients are present, keeps the managed rule in sync
    as dns.servers changes across saves, and never touches manually
    authored rules.
    
    Fixes #5773
    
    * fix(routing): scope the DNS allow-rule to its port, guard against reorder/UI drift
    
    Addresses three review findings on the initial fix:
    
    1. The allow-rule now carries a "port" matcher (grouped by the
       dns.servers entries that share it), instead of opening every port
       on the private DNS IP to proxy-client traffic. A private resolver
       that also exposes an unauthenticated admin UI on the same address
       would otherwise become reachable through the proxy too.
    
    2. EnsureDnsServerRouting now strips every previously-managed rule and
       rebuilds the current set fresh, reinserted immediately before the
       (re-indexed) geoip:private block rule on every save. Comparing IP
       content alone missed the case where an admin drags the rule below
       the block rule in the Routing tab (or reorders something else and
       incidentally moves it) — silently reintroducing the exact stall
       this fix addresses, with nothing to notice or correct it.
    
    3. dnsAllowRuleShape now tolerates an "enabled" key as long as it's
       true, matching the existing EnsureStatsRouting precedent
       (xray_setting.go's `delete(apiRule, "enabled")`). The Routing tab's
       rule editor writes that key on every save regardless of whether
       anything changed, and its enabled switch writes it on a plain
       toggle — without this, either action permanently disowns the rule
       from management and a duplicate gets inserted next save. A rule
       explicitly disabled (enabled=false) is left alone and a fresh one
       is (re-)created, respecting the admin's choice instead of silently
       re-enabling it.
    
    No-op detection now compares rebuilt rules against the original
    routing.rules JSON (both decoded through encoding/json to a common
    type) rather than reflect.DeepEqual on the parsed Go values, which
    falsely reported changes for identical content stored as []any vs
    []string.
    
    5 new tests cover multi-port grouping, position drift, and both
    enabled-key cases; existing tests updated for the port field.
    
    * fix: avoid size-computation overflow in allocation hint
    
    CodeQL flagged make([]map[string]any, 0, len(clean)+len(managed)) as a
    potential integer-overflow risk in the capacity computation. Drop the
    addition and hint with len(clean) alone — it already covers most of
    the eventual size, and append still grows correctly for the rest.
    
    ---------
    
    Co-authored-by: Volov <volovdata@google.com>
  • fix(ldap): convert default total GB to bytes when auto-creating clients (#5854)
    * fix(ldap): convert default total GB to bytes when auto-creating clients
    
    LdapSyncJob.buildClient stored ldapDefaultTotalGB directly into
    Client.TotalGB without the GB-to-bytes conversion every other client
    creation path applies (client form's gbToBytes, tgbot's
    limitTraffic*1024^3, client_inbound_apply.go's totalGB*1024^3). A
    "Default total (GB)" of 10 was persisted as 10 bytes, depleting the
    client almost immediately.
    
    Closes #5852
    
    * test(ldap): pin the GB-to-bytes conversion in buildClient
    
    Per review feedback on #5854: the existing test only exercised
    defGB=0, so it wouldn't have caught the missing conversion.
  • feat(mtproto): enforce per-client quota & expiry via mtg-multi limits
    Map each mtproto client's totalGB and expiryTime onto mtg-multi's new
    [secret-limits] (quota/expires): emit them into the generated config and
    hot-apply through PUT /secrets so live connections survive. Quota is
    written as an exact "<n>B" byte count that round-trips through both the
    config and API parsers without the precision loss of a base-2 unit.
    
    The sidecar's quota counter is not pruned when a secret is dropped, so a
    panel-side traffic reset re-pushes the client's secret and then calls
    POST /secrets/{name}/reset-quota (wired into every reset path) so a
    renewed client is not immediately re-blocked.
    
    Resolve the mtg-multi binary from the fork's latest release tag in
    DockerInit.sh and release.yml instead of a hardcoded version pin, so the
    panel no longer needs a manual bump per fork release.
  • Frontend dev tooling (Husky, lint-staged, MSW, Storybook) + full React Hook Form migration (#5859)
    * chore(frontend): add husky + lint-staged pre-commit gate
    
    Wire a local pre-commit gate that runs eslint --fix on staged
    frontend TypeScript via lint-staged. Because the only package.json
    lives in frontend/ while the git root is one level up, the prepare
    script installs husky hooks at frontend/.husky from the repo root
    (cd .. && husky frontend/.husky), and the pre-commit hook cd's into
    frontend/ before invoking lint-staged so node_modules resolves.
    
    * test(frontend): add MSW request mocking
    
    Add Mock Service Worker so tests can exercise the real http-init.ts
    request pipeline (CSRF acquisition, 403 refetch-and-retry, body
    parsing) instead of only stubbing HttpUtil. A node setupServer is
    started for the vitest unit project with onUnhandledRequest bypass so
    the existing HttpUtil spies and 55 component tests are untouched; the
    browser worker is copied to public/ for Storybook and dev use.
    
    * chore(frontend): add Storybook + component stories
    
    Set up Storybook 10 on the React-Vite builder (compatible with the
    pinned Vite 8.1.3 and React 19). The preview decorator mirrors the
    vitest component harness: an Ant Design ConfigProvider with a
    light/dark toolbar toggle and an en-US i18next instance. main.ts
    neutralizes the app vite config bits that do not belong in a component
    workshop (the three-entry rollup input, renderBuiltUrl, and the shared
    dist outDir) so build-storybook can never clobber internal/web/dist.
    Seeds stories across the presentational library (viz, ui, clients,
    feedback). build-storybook is a local tool and is not wired into the
    CI gate.
    
    * feat(frontend): add React Hook Form primitives
    
    Introduce the shared RHF layer that AntD inputs bind through, ahead of
    migrating the forms off Ant Design's Form store:
    - FormField wraps a Controller in an Ant Design Form.Item shell,
      reconciling the value/onChange shapes of Input, Switch, InputNumber,
      Select and friends via normalizeAntdOnChange, with input/output
      transforms and Zod-issue-key error messages resolved through t().
    - useZodForm wires zodResolver (Zod 4) with the AntD-matching modes
      (validate on submit, then live) and shouldUnregister false so hidden
      and unmounted-tab fields keep their values.
    - rhfZodValidate covers the rare per-field rule sites.
    Covered by a FormField test exercising normalization, transforms, and
    resolver error surfacing.
    
    * refactor(frontend): migrate Pattern-B leaf forms to React Hook Form
    
    Move the controlled-useState leaf forms onto RHF via the FormField
    primitive, keeping Ant Design components and each form's exact submit
    behaviour (same safeParse, same toast on the first Zod issue, same
    payload building):
    - clients: ClientBulkAdjustModal, BulkAddToGroupModal, ClientBulkAddModal
    - xray: RuleFormModal, BalancerFormModal, WarpModal, NordModal
    
    Multi-control widgets that don't fit a single input (inbound dual
    select, subId regen, expiry branches, the balancer tag warning) stay as
    explicit Controller/setValue. Derived visibility now reads live values
    through useWatch. FormField gains a required prop so migrated fields keep
    their required-asterisk affordance.
    
    Settings tabs are intentionally excluded: they are control-panel
    components that live-patch a parent AllSetting via SettingListItem, not
    Ant Design Form submit-forms.
    
    * refactor(frontend): migrate LoginPage to React Hook Form
    
    Replace the Ant Design Form store + antdRule per-field validation with
    useForm + FormField. The AntD Form stays as the layout/submit wrapper,
    now driving methods.handleSubmit(onSubmit) via onFinish. Username and
    password validate through rhfZodValidate(LoginFormSchema.shape.*); the
    two-factor field keeps its conditional required rule (only registered
    when 2FA is enabled). Submit posts the same values to /login.
    
    * refactor(frontend): migrate ClientFormModal to React Hook Form
    
    Move the client add/edit form off controlled useState onto RHF while
    preserving exact submit behaviour (same ClientFormSchema /
    ClientCreateFormSchema safeParse, same toast, same payload + attach/
    detach diff + external-links build). expiryDate is stored as an epoch
    number (never a Dayjs) to survive RHF's value cloning, converted at the
    DateTimePicker boundary. externalLinks uses useFieldArray with stable
    ids. inboundIds and the derived show*/ss2022 visibility read live via
    useWatch. Space.Compact button-group widgets stay manual Controllers so
    the joined borders keep working.
    
    * refactor(frontend): migrate Node and DNS modals to React Hook Form
    
    Both are self-contained Pattern-A forms (no shared fragments). Replace
    Form.useForm with useForm + FormProvider, Form.useWatch with useWatch,
    setFieldValue with setValue, and partial validateFields([...]) with
    methods.trigger([...]). Per-field antdRule becomes rhfZodValidate rules;
    the Node scheme->tlsVerify cascade moves to FormField onAfterChange; the
    DNS domains/expectIPs/unexpectIPs string arrays are driven by
    useWatch + setValue. Submit runs through handleSubmit on the modal OK
    button, preserving each form's exact validation, payload build, and
    save/onConfirm behaviour.
    
    * refactor(frontend): migrate HostFormModal to React Hook Form
    
    The host external-proxy editor's outer form moves to useForm +
    FormProvider. Security/tab visibility reads via useWatch; the three
    json-form editors (HostMuxForm/HostSockoptForm/HostFinalMaskForm) are
    bound as value/onChange black boxes through a Controller (their own
    internal forms are unchanged). remark/inboundId keep their validation
    via rhfZodValidate; submit runs through handleSubmit and builds the
    same payload (isDisabled = !enable) and save call.
    
    * refactor(frontend): migrate OutboundFormModal + fragments to React Hook Form
    
    Move the outbound form cluster off Ant Design's Form store onto RHF.
    The parent uses useForm + FormProvider with a watch() subscription for
    the protocol reseed cascade and setValue-based network/security/xmux
    cascades; the JSON<->Basic bridge and the formValuesToWirePayload
    submit are preserved exactly. Every outbound transport/protocol/security
    fragment now binds through FormField/useWatch via context.
    
    The shared config editors stay untouched and are bound through small
    value/onChange adapters (src/lib/xray/forms/fields: FinalMaskField,
    SniffingField, SockoptCustomField) via Controller; HeaderMapEditor binds
    directly. The host json-form wrappers that reuse the outbound MuxForm/
    SockoptForm (HostMuxForm, HostSockoptForm, OutboundSubtreeJsonForm) move
    to a local RHF provider to match. Outbound render/link tests pass
    unchanged.
    
    * refactor(frontend): migrate InboundFormModal + fragments to React Hook Form
    
    Move the inbound add/edit form (the largest form in the panel) and its
    transport/protocol/security fragments off Ant Design's Form store onto
    RHF, mirroring the outbound migration. The parent uses useForm +
    FormProvider with a watch() subscription for the protocol reseed
    cascade (type==='change' guard so programmatic resets don't reseed) and
    setValue-based network/security cascades; useSecurityActions drives the
    TLS/Reality keypair + scan through setValue. Hidden pass-through
    Form.Items are dropped (their values ride in the reset object and
    survive via shouldUnregister:false), so getValues() still returns the
    settings.clients subtree untouched. accounts / certificates / tun lists
    use useFieldArray; the shared FinalMask/Sniffing/Sockopt editors bind
    through the value/onChange adapters.
    
    Submit keeps the manual InboundFormSchema.safeParse + formatInboundValidation
    toast + formValuesToWirePayload exactly. The golden link/full fixtures
    pass byte-for-byte, confirming identical wire output. inbound-form-blocks
    test harness rewritten from a Form.useForm harness to an RHF provider.
    
    * refactor(frontend): retire antdRule; document the RHF form pattern
    
    All forms now build on React Hook Form, so the AntD-Form Zod adapter
    antdRule (src/utils/zodForm.ts) has no remaining callers — remove it.
    Update frontend/CLAUDE.md: forms use useZodForm + FormField from
    components/form/rhf with zodResolver/rhfZodValidate validation; AntD
    <Form> is layout-only; the shared FinalMask/Sniffing/Sockopt editors
    stay AntD islands wrapped as value/onChange adapters bound via a
    Controller.
    
    * chore(frontend): cover esbuild in the allowScripts allowlist
    
    esbuild (pulled in transitively by Vite/Vitest/Storybook) ships a
    postinstall that npm's allow-scripts flags as uncovered on every
    install. Its platform binary is delivered through the @esbuild/<platform>
    optionalDependencies, so the postinstall isn't needed here; deny it like
    the other entries to silence the warning.
    
    * fix(frontend): restore label layout in Sniffing/FinalMask field adapters
    
    The value/onChange adapters that wrap the shared SniffingFields and
    FinalMaskForm editors put them in their own isolated AntD Form, but that
    Form was missing the label layout the fields used to inherit from the
    inbound/outbound parent form. Their labels rendered full-width instead
    of the compact right-aligned column, so the Sniffing tab and the TCP
    Masks / QUIC Params sections looked broken. Give both adapter forms the
    same colon=false, labelCol/wrapperCol span 8/14, labelWrap layout.
    
    * ci: add least-privilege permissions to Docs CI workflow
    
    The docs-ci workflow had no explicit permissions block, so it inherited
    the repository default for GITHUB_TOKEN. The build job only checks out
    and builds the docs, so restrict it to contents: read, resolving the
    CodeQL actions/missing-workflow-permissions alert.
  • refactor(frontend): replace recharts with uPlot for charts
    Swap the Sparkline chart component (the only chart in the panel) from recharts to uPlot, keeping its public prop API identical so the three consumers (SystemHistoryModal, XrayMetricsModal, NodeHistoryPanel) are untouched. This drops recharts and 32 transitive deps (es-toolkit, victory-vendor, d3, redux, immer), shrinking the chart vendor chunk to ~51KB (22KB gzip).
    
    The uPlot port reimplements every recharts feature on canvas: gradient area fill, spline curves, up to three series, dashed horizontal grid, formatted axes, hover tooltip and marker, reference lines, and min/max extrema dots. Because canvas cannot read CSS variables, axis and ring colors are resolved via getComputedStyle and repainted on theme changes through a MutationObserver on the body class and documentElement data-theme.
    
    Also removes the es-toolkit/compat resolver shim from vite.config.js, which existed only for recharts, and swaps the manualChunks entry to vendor-uplot.
    
    Note: repaint with redraw(false); a bare uPlot redraw() re-runs _setScale and nulls the index-based x-scale, which collapsed the series to a flat, partial line.
  • refactor(frontend): replace axios with the native Fetch API
    Drop the axios (and qs) dependencies in favor of a native fetch wrapper.
    axios only ever handled same-origin JSON/form calls, a CSRF header, a 401
    redirect, and a 403-retry, all of which the platform now provides directly.
    
    - New src/api/http-init.ts (replaces axios-init.ts) reimplements the
      request/response interceptors on fetch: base-path prefixing,
      X-Requested-With, same-origin credentials, the CSRF token on unsafe
      methods, a single 403 retry with token refresh, and the 401
      redirect-and-latch. A small encodeForm() reproduces qs's
      arrayFormat:'repeat' encoding, so the request wire format is unchanged.
    - HttpUtil (src/utils/index.ts) keeps its public signatures and the Msg
      envelope, so the ~49 API call sites are untouched. HttpOptions is now
      hand-rolled instead of extending AxiosRequestConfig.
    - PanelUpdateModal drops its lone direct axios.get in favor of HttpUtil.get
      with { silent, timeout }.
    - Add tests for the fetch core (CSRF header, form/JSON/FormData bodies,
      base-path prefix, 403 retry, 401 redirect, tolerant body parse) and for
      HttpUtil's envelope unwrap / toast / error mapping; this logic was
      previously untested.
    - Remove the vendor-axios manualChunks branch and the qs type shim, and
      reword stale "axios" mentions in docs and route comments.
  • fix(logs): limit Xray log growth (#5840)
    * Limit Xray log growth
    
    * Apply suggestion from @github-actions[bot]
    
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
    
    * Apply suggestion from @github-actions[bot]
    
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
    
    ---------
    
    Co-authored-by: Mahyar Dana <dana.mahyar76@gmail.com>
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • docs: vendor the documentation site into the monorepo
    Fold the standalone 3x-ui-docs project (Next.js 16 + Fumadocs, deployed to
    docs.sanaei.dev) into docs/ so the panel and its documentation share a single
    source of truth, the way sing-box keeps its docs in-tree. The old repo becomes
    redundant and can be retired.
    
    - Import the full site under docs/ (app, components, content, lib, public,
      scripts, config). The self-contained pnpm project sits alongside the existing
      engineering notes with no filename collisions.
    - Re-point "Edit on GitHub" links from MHSanaei/3x-ui-docs to this repo's
      docs/content/docs path (docs/lib/shared.ts, docs/app/.../page.tsx).
    - Add docs-ci.yml and docs-deploy.yml under .github/workflows/, scoped to
      docs/** and run with working-directory: docs, since GitHub only runs
      workflows from the repo-root .github/. deploy-static.yml's GitHub Pages
      publish (CNAME docs.sanaei.dev) carries over unchanged.
    
    Follow-up (outside this commit): attach the docs.sanaei.dev custom domain to
    this repository's Pages (or set the Vercel project's root directory to docs),
    confirm the site is live from the monorepo, then delete MHSanaei/3x-ui-docs.
  • fix(node): start a fresh quota window when a node auto-renews a client
    When a node-hosted client auto-renews, the node extends the deadline
    and zeroes its own counters, but the master treated the counter drop
    like any reset dip (#5456): the delta clamped to zero, the renewed
    expiry was adopted, and the old period's up/down stayed on the master
    row. A "100 GB every 30 days" package never got a fresh quota on the
    master for node inbounds.
    
    Detect the renewal in setRemoteTrafficLocked - reset days configured,
    an absolute deadline that moved forward, and the node counter falling
    below the stored baseline - and on that path adopt the node's
    post-renewal counters and enable state absolutely instead of adding
    the clamped delta, plus clear the email's stale cross-panel
    global-traffic rows, mirroring what the local autoRenewClients path
    already does. A plain counter dip without a deadline move keeps the
    existing clamp behavior, and a deadline extension with rising counters
    keeps accumulating.
    
    Closes #5843
  • fix(sub): carry a host's Final Mask into raw share links
    A Host's Final Mask was merged into the JSON and Clash subscription
    outputs via applyHostStreamOverrides, but the raw link builders compute
    the fm param once from the inbound's own streamSettings.finalmask
    before the per-host fan-out, and the endpoint override path never read
    the host's mask. A Final Mask configured only on a host was silently
    dropped from vless/trojan/ss/vmess share links while an inbound-level
    mask worked everywhere.
    
    Merge the host mask into the fm param per endpoint with the same
    additive semantics as the JSON path (host tcp/udp masks appended to the
    inbound's, quicParams only when the inbound has none), for both the
    URL-param and the VMess object link forms.
    
    Closes #5831
  • fix(ldap): attach auto-created clients to every configured inbound tag
    The sync job built an independent client per configured tag and called
    CreateOne once per tag. Each call generated a fresh random subId, and
    the email-uniqueness check in ClientService.Create only re-admits a
    taken email when the incoming subId matches the stored one - so the
    first tag succeeded and every other tag failed with "email already in
    use", leaving new LDAP users on a single inbound.
    
    Build the client once per email and hand ClientService.Create the full
    list of resolved inbound ids, the same path the panel's own client
    create endpoint uses: one identity (email, subId) attached to all
    configured tags, with per-protocol credentials filled per inbound.
    Unknown tags are now skipped with a warning instead of building
    clients against a nil inbound.
    
    Closes #5846
  • fix(client): clean node_client_traffics rows when deleting a client
    Delete and DeleteByEmail removed client_traffics, global-traffic, and
    inbound_client_ips rows but never the per-node baseline rows in
    node_client_traffics, so every deleted client left orphaned baselines
    behind for each registered node. The shared DelClientStat and
    delClientStatsByEmails helpers already clean that table; mirror the
    same cleanup in both row-cleanup paths so the record-only and
    record-less delete flows stop leaking baselines.
    
    Closes #5841
  • [Feature]: Add a tooltip/hint to the "Password" field in the client form clarifying which protocols use it (#5809)
    * feat(clients): clarify which protocols use the Password and Hysteria Auth fields
    
    Add tooltips to the Password and Hysteria Auth Form.Items in the client
    form, explaining that Password is only consumed by Trojan and Shadowsocks
    (ignored for VLESS, VMess, Hysteria, WireGuard) and that Hysteria Auth is
    the credential Hysteria actually uses. Adds passwordDesc/hysteriaAuthDesc
    keys to all 13 locale files, following the existing limitIpDesc/totalGBDesc
    tooltip convention.
    
    Closes #5803
    
    * test(clients): assert Password/Hysteria Auth tooltip hints render
  • refactor(mtproto): manage ad-tags per client only
    The inbound-level ad-tag duplicated the per-client override for no
    gain: the fork's global tag applied to every secret anyway, so one
    value had two homes and they could drift. The inbound form field, the
    settings key, and the global ad-tag in the generated config and in the
    PUT /secrets body are gone; the tag is set on each client instead.
    Existing inbound-level values are intentionally not migrated; a
    leftover settings key is stripped on the next save.
  • chore(mtproto): bump the mtg-multi binary pin to v1.14.0
    Same asset layout and platform coverage as v1.13.3; picks up the
    sidecar's Docker-style environment variable support.
  • feat(mtproto): per-client ad-tags, management-API auth, and record secret sync
    Catch the panel up to the mtg-multi README (v1.14.0):
    
    - Each client can now carry its own 32-hex advertising tag overriding the
      inbound-level one. The tag lives on the client (settings JSON is the
      source of truth, clients.ad_tag is the UI projection), is rendered into
      the fork's [secret-ad-tags] section for active secrets only (mtg rejects
      a config whose override names an unknown secret), is pushed per entry
      through PUT /secrets, and is part of the reload fingerprint so a tag
      edit hot-applies without dropping connections.
    - The loopback management API can replace the whole secret set, so every
      mtg process now gets a random per-process api-token; the manager sends
      it as a bearer token on PUT /secrets and GET /stats and reuses it across
      config rewrites, because mtg reads the token only at startup.
    - Malformed tags are rejected at every save path and additionally dropped
      in InstanceFromInbound: one bad tag would otherwise fail the whole
      generated config and take every client of the inbound down with it.
    - SyncInbound never copied a re-keyed mtproto secret into the canonical
      clients table, so the clients page and subscription links kept serving
      the old secret, which mtg then rejects. It is now guarded-copied like
      the other credentials.
  • fix(ci): stop executing tag-checkout code in the release smoke test
    CodeQL alert 99 (actions/cache-poisoning/poisonable-step): the workflow_run
    job runs in the default branch's cache scope, so checking out
    workflow_run.head_sha and executing a script from it is a cache-poisoning
    surface. The if-guard (event == 'push') already kept fork PRs out, but the
    checkout pin was never the load-bearing part of the release verification —
    the version argument is, since install.sh downloads that exact release
    binary. Run the smoke script from the default branch instead, which also
    matches what real users execute.
  • fix(mtproto): stop dropping connections on client/inbound edits; add live updates + ad-tag (#5838)
    * fix(mtproto): split the mtg fingerprint into structural and secrets parts
    
    A reordered clients array in the stored settings used to read as a config
    change because the fingerprint concatenated secrets in array order, and one
    opaque fingerprint could not tell a restart-worthy change (bind address,
    fronting, throttle) from a secret-set change a reload-capable mtg can absorb
    in place. Sort the secret pairs so order stops mattering, and split the value
    so the upcoming hot-reload path can decide between keeping, reloading, and
    restarting the process.
    
    * fix(mtproto): stop restarting mtg on every inbound edit
    
    Saving an mtproto inbound tore down and respawned its mtg sidecar even when
    nothing material changed, dropping every live Telegram connection: the update
    path pushed DelInbound+AddInbound, and Remove deletes the manager's map entry,
    so Ensure's fingerprint no-op gate could never fire. Route mtproto updates
    through a single Ensure call so an edit that leaves the generated TOML alone
    keeps the process, and only real config changes restart it.
    
    Capturing the pre-edit protocol also fixes a latent leak: changing an
    inbound's protocol away from mtproto never stopped the sidecar, because the
    snapshot handed to the runtime already carried the new protocol and the
    removal took the xray branch, leaving an orphaned mtg holding the port.
    
    An mtproto push failure no longer requests an xray restart - xray cannot fix
    the sidecar, and the 10s reconcile job self-heals it.
    
    The regression test fakes mtg by re-executing the test binary, counting
    spawns through a pid file: an unchanged save and a remark-only edit must keep
    the process, a re-keyed secret must restart it.
    
    * fix(mtproto): exclude depleted clients from the reconcile job to match the sync push
    
    The 10s reconcile job derived mtg secret sets from raw inbound settings while
    the interactive push filtered clients through buildRuntimeInboundForAPI, which
    drops client_traffics-disabled (depleted or expired) clients. The two paths
    therefore disagreed on the fingerprint - each disagreement one needless mtg
    restart dropping live connections - and worse, the job kept serving depleted
    clients' secrets indefinitely, so running out of traffic never actually cut an
    mtproto client's access.
    
    DesiredMtprotoInstances now builds the job's desired state with the same
    depletion overlay the push uses (one bulk client_traffics query), drops
    inbounds whose every secret is filtered away so their sidecar stops, and
    AddInbound pushes the filtered payload too so an imported inbound carrying
    disabled stats does not seed a fingerprint the next reconcile disagrees with.
    
    * feat(mtproto): hot-reload mtg secrets in place instead of restarting
    
    A client add, removal, re-key, or enable-toggle changes only the [secrets]
    section of the generated config, yet the panel could apply it only by killing
    and respawning the mtg sidecar, dropping every Telegram connection on that
    inbound. Split the ensure decision three ways: an identical config is a no-op,
    a secrets-only change rewrites the TOML on the same api port and asks mtg to
    hot-swap it via POST /reload, and a structural change (or a failed reload)
    falls back to the full stop-and-start.
    
    The reload endpoint is served by the mhsanaei/mtg-multi fork; against an older
    binary the POST 404s and the manager restarts exactly as before, so panel and
    binary upgrades stay order-independent.
    
    * feat(mtproto): apply single-client edits to the sidecar immediately
    
    Client CRUD on an mtproto inbound was a runtime no-op, so an add, delete,
    re-key, or enable-toggle only reached mtg on the next 10s reconcile. With the
    sidecar now able to hot-reload, push the change straight after the edit commits:
    applyLocalMtproto rebuilds the inbound's filtered client set and re-applies it,
    so a new client works within a moment (and, on a reload-capable binary, without
    disturbing the others) and deleting the last client stops the process.
    
    The three interactive single-client paths (add, update, delete) call it; bulk
    operations still ride the reconcile job, which converges to the same state.
    
    * chore(mtproto): pin mtg-multi to the mhsanaei fork v1.13.3
    
    The reload endpoint the panel now uses lives in the mhsanaei/mtg-multi fork, so
    point the source-build pin (DockerInit.sh + both release.yml matrices) at it and
    bump to v1.13.3. The install still produces the same mtg-multi binary name, so
    the mtg-<os>-<arch> rename and everything downstream are unchanged. Docs and the
    package comment note the hot-reload path and its restart fallback.
    
    * feat(mtproto): apply live secret updates via the management API and add ad-tag
    
    Two capabilities the mhsanaei/mtg-multi v1.13.3 fork exposes are now surfaced by
    the sidecar manager.
    
    Live updates go through PUT /secrets on the fork's management API instead of
    POST /reload: the panel already holds the whole desired set per inbound, so it
    sends secrets and the advertising tag as one JSON call that mtg applies
    atomically, keeping every unchanged connection and closing only removed or
    re-keyed ones. The config file is still written first so a restart or crash
    recovery reproduces the state, and any non-200 (an older binary, a refused
    connection) still falls back to a full restart.
    
    Per-inbound ad-tag adds an optional 32-hex Telegram advertising tag plus
    public-ipv4/public-ipv6 overrides. The ad-tag rides the reloadable secrets
    fingerprint, so changing it hot-applies without dropping connections; the public
    IPs are proxy-construction parameters and sit in the structural fingerprint, so a
    change there restarts the process. Empty public IPs are omitted so mtg
    auto-detects the reachable address.
    
    * feat(inbounds): expose the mtproto ad-tag and public IP in the inbound form
    
    Adds an Ad-tag field (validated as 32 hex characters) plus optional Public IPv4
    and Public IPv6 overrides to the MTProto inbound form, backed by the same-named
    settings the sidecar writes into the mtg config. The public IPs are optional —
    left blank, mtg auto-detects the reachable address the ad-tag middle proxy needs.
    English strings are added to every locale; the non-English ones carry the
    English text until translated and fall back to it meanwhile.
    
    * ci(mtproto): install mtg-multi from prebuilt release binaries
    
    The fork now publishes release archives for every platform we package, so
    download and unpack the matching mtg-multi-<ver>-<os>-<arch> binary instead of
    compiling it from source with go install. Faster builds and no toolchain step,
    and the archive's platform labels line up with our matrix; the produced
    mtg-<os>-<arch> filenames are unchanged.
    
    * i18n(mtproto): localize the ad-tag and public IP strings
    
    The six mtgAdTag*/mtgPublicIp* keys shipped with English text in every locale as
    a placeholder. Translate them into the twelve non-English locales (Arabic,
    Spanish, Persian, Indonesian, Japanese, Portuguese-BR, Russian, Turkish,
    Ukrainian, Vietnamese, and Simplified/Traditional Chinese); en-US is unchanged.
    
    * retired goreportcard.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.
  • fix(mtproto): drop the remark fragment from tg proxy deep links
    genMtprotoLink appended the panel remark as a URL fragment (tg://proxy?...&secret=...#remark). Because secret/server is the last query value, lenient Telegram parsers fold the "#remark" into it and the imported proxy breaks with "incorrect client random". Telegram proxy deep links have no name field, so emit a clean link on both the backend (internal/sub) and frontend (inbound-link.ts). The remark still shows as a separate tag in the inbound info modal, which reads it from genAllLinks, not the URL.
    
    Guards: Go TestGenMtprotoLinkFields asserts no fragment; the frontend mtproto link test asserts no '#'.
  • chore(gen): refresh generated schemas after Client.Secret comment drop
    Commit d8b9f535 dropped the trailing comment on model.Client.Secret but did not regenerate the openapigen output, leaving a stale "MTProto FakeTLS secret" description in schemas.ts and openapi.json. Rerun make gen to bring the generated files back in sync with the source.
  • fix(ci): install mtg-multi without GOBIN for cross-compiled release builds
    go install refuses to run with GOBIN set when GOOS/GOARCH differ from the host, which failed the linux release build for every non-amd64 platform (386, arm64, armv7, armv6). Let it install into GOPATH/bin instead, where cross-compiled binaries land in a GOOS_GOARCH subdirectory, and locate the binary there. DockerInit.sh keeps GOBIN because buildx runs it under emulation for the target platform, making the install native.
  • style(model): drop trailing comment on Client.Secret to satisfy gofumpt
    The long example tag on Secret pulled the struct's trailing-comment block into a new alignment section, so gofumpt demanded every following comment be re-aligned to that tag's column. Removing the comment restores the previously accepted layout and follows the repo rule against line comments.
  • 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(script): stop logging an error when Enter accepts the default ACME port
    Pressing Enter at the 'Please choose which port to use (default is 80)' prompt left WebPort empty, and bash arithmetic treats an empty string as 0, so the out-of-range branch fired and printed 'Your input is invalid' even though the default was correctly applied. Handle empty input as accepting the default silently, and validate real input with a digits-only regex so non-numeric entries like '8x' get the invalid-input message instead of a bash arithmetic error. Applied to the identical prompt in x-ui.sh, install.sh, and update.sh.
    
    Fixes #5829
  • feat(db): add pgclient command to install or upgrade PostgreSQL client tools
    Restoring a panel backup made by a newer pg_dump fails when the host's
    pg_restore is older, and the existing pg_ensure_client only installs the
    distribution package when the tools are missing - it can never upgrade,
    and distribution repositories often cap below the required major.
    
    Add pg_upgrade_client to x-ui.sh, exposed as 'x-ui pgclient [major]' and
    as a PostgreSQL menu entry: it checks the installed pg_restore major,
    tries the distribution package for the exact requested major first, and
    falls back to the official PostgreSQL repository (apt on Debian/Ubuntu,
    yum/dnf on Enterprise Linux, with a /usr/pgsql PATH symlink fallback);
    Arch, Alpine and openSUSE install their current package. The panel's
    dump-version mismatch error now names the ready-to-copy command with
    the exact major parsed from the dump header.
  • fix(db): probe dump readability before PostgreSQL import
    pg_restore cannot read archives newer than itself, so importing a dump
    made by pg_dump from PostgreSQL 17+ into a panel with an older
    postgresql-client failed with a raw 'unsupported version (1.16) in file
    header' - and only after Xray had already been stopped for the restore.
    
    Probe the uploaded file with pg_restore --list first, which reads only
    the archive TOC without touching the database, so an unreadable dump is
    rejected before Xray is interrupted. When the failure is a dump-format
    version mismatch, translate it into a message naming the PostgreSQL
    version that produced the dump and the client version to install.
  • feat(outbound): add real-delay connection test mode
    The HTTP probe reports the warm per-request round-trip, which reads
    lower than the delay figure client apps show for the same server. Add a
    third "real" test mode that reuses the temp-instance HTTP probe but
    reports the cold request's full elapsed time - tunnel establishment
    included - and skips the warm request. UDP-transport outbounds forced
    out of the TCP lane still report "http"; in real mode they report
    "real". The mode joins the TCP/HTTP toggle on the outbounds tab, with
    the label translated in all 13 locales.
  • 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(ui): keep an explicit zero happy-eyeballs delay across the round trip
    Follow-up found in review: the wire normalizer still stripped
    tryDelayMs when it equaled 0, but with the schema default now 250 a
    reload rehydrates the missing field as 250 - a user who explicitly set
    0 ("disabled", per the field's own placeholder) would see 250 and any
    subsequent save would silently enable a delay they turned off. Keep
    tryDelayMs on the wire unconditionally; it is the one happy-eyeballs
    field whose presence changes xray's behavior.
    
    Refs #5780
  • fix(link): reject non-finite and clamp out-of-range quicParams from fm=
    Follow-up hardening of the fm= sanitizer found in review. ParseFloat
    accepts "inf"/"NaN", and a non-finite float64 makes json.Marshal fail
    later - the subscription refresh discards that error and blanks the
    stored outbound set, so one poisoned link could wipe a subscription's
    outbounds. Values that coerce fine but sit outside xray-core's accepted
    ranges (keepAlivePeriod 0 or 2-60, maxIdleTimeout 0 or 4-120,
    maxIncomingStreams 0 or >= 8) still killed the config load, and huge
    magnitudes serialize in exponent notation that xray's integer fields
    reject. Coerced values are now stored as integers, clamped into the
    accepted ranges, and dropped when negative, non-finite, or absurdly
    large; the TS import parser mirrors the same rules.
    
    Refs #5783
  • 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): fully delete clients on nodes instead of only detaching them
    Deleting a client on the master propagated to nodes via the detach
    endpoint, which removes the client from that one inbound's settings but
    deliberately keeps the client record. The node ended up with an
    orphaned record that kept showing in its Clients view; the master and
    node could never converge on a delete.
    
    Full-delete and detach intent now travel separately: the Runtime
    interface gains DeleteClient, which on Remote hits the node's
    panel/api/clients/del endpoint (record, attachments, traffic; repeat
    calls for a client on several inbounds of the same node are swallowed
    as idempotent "not found"). Delete/DeleteByEmail/BulkDelete use it for
    node inbounds, while Detach/BulkDetach keep the inbound-scoped detach
    RPC so removing a client from one inbound never wipes it node-wide
    (the #5543 guarantee is preserved and covered by tests). Bulk deletes
    above the fold threshold still converge membership via reconcile; their
    leftover node records can be cleaned with the node's delete-orphans
    action.
    
    Closes #5797
  • fix(outbound): measure HTTP test delay on a warm connection
    Since the batched prober replaced the single tester, the reported delay
    came from one cold request with keep-alives disabled, so it stacked the
    SOCKS handshake, proxy dial, proxy TLS, target TCP and target TLS on top
    of the round-trip. Users upgrading from v2.9.4 - whose tester warmed the
    connection first and timed a second request - saw several times the real
    connection time.
    
    The cold request still proves reachability and supplies the HTTP status
    plus the connect/TLS/TTFB breakdown; the delay is now re-measured on a
    second request over the kept-alive connection, falling back to the cold
    total when the warm request fails. Bodies are drained (bounded) so the
    connection returns to the pool, and the batch test asserts both requests
    of a probe share one connection.
  • fix(tgbot): find clients by tgId regardless of settings JSON formatting
    The Telegram-bot usage lookup prefiltered inbounds with
    settings LIKE '%"tgId": N%', which requires the exact space the panel's
    MarshalIndent happens to emit. Inbounds whose settings were serialized
    compactly (node sync, imports, external edits) never matched, so the
    bot reported no configuration even though the client and traffic rows
    exist. Replace the string match with the driver-portable JSON helpers
    already used by GetAllEmails, which read the actual clients array on
    SQLite and Postgres alike.
    
    Closes #5805
  • fix(link): sanitize numeric quicParams taken from a share link's fm= param
    The fm= finalmask blob was JSON-decoded and attached to streamSettings
    verbatim, both by the Go parser (outbound subscriptions) and the
    frontend import. Some providers emit duration strings for the strictly
    integer quicParams fields (e.g. keepAlivePeriod "10s"), and xray-core
    then refuses to load the whole config at startup - one bad subscription
    entry took the panel's Xray down on the next refresh. Coerce numeric
    strings, convert duration strings to whole seconds, and drop values
    that cannot be represented as integers; genuinely string-typed fields
    (congestion, bbrProfile, brutalUp/Down, udpHop) pass through untouched.
    
    Closes #5783