Commit Graph
3026 Commits
  • fix(balancers): keep mixed strategies on one observer (#5674)
    * fix(balancers): keep mixed strategies on one observer
    
    Xray resolves Observatory and Burst Observatory through the same global observer feature. When any burst-required strategy is present, keep all observer-backed balancer selectors on burstObservatory and remove the regular observatory so mixed leastPing configs cannot generate two competing observer blocks.
    
    * test(balancers): cover observer strategy combinations
    
    Exercise the observer sync matrix for random, round-robin, leastPing, and leastLoad balancers. Include mixed and stale-observer cases so the panel keeps only the observer type that Xray should consume.
    
    * fix(balancers): clarify observer empty state
    
    Update the Observatory tab empty hint to describe the actual auto-managed cases. Least Ping, Least Load, and fallback Random or Round-robin balancers now explain why an observer is added before the balancer can choose a target.
    
    * fix(balancers): remove mixed observer switch
    
    Show only the observer settings panel that matches the current balancer requirements. Legacy configs that still contain both observatory blocks now display a warning instead of a tab switch, since saving balancers normalizes the config back to one global observer.
    
    * test(balancers): cover observer cleanup on deletion
    
    Add direct balancer deletion and outbound cascade cases for leastLoad, fallback, and mixed leastPing scenarios. These tests pin that the final unneeded observer is removed, burst switches back to regular observatory when only leastPing remains, and burst remains when a burst-required balancer survives.
  • fix(web): sync the VLESS generate-key dropdown with the encryption field
    The auth-kind dropdown in the VLESS "Generate Key" block was hardcoded to
    x25519 on mount, while the "Already selected" text next to it was derived
    independently from settings.encryption. Editing an inbound whose encryption
    uses another kind (e.g. ML-KEM-768) showed a mismatched dropdown, and
    clicking Generate without noticing would produce a keypair of the wrong
    kind for the inbound.
    
    Extract the encryption-string parsing into a shared pure helper
    (lib/xray/vless-encryption), use it both for the selected-auth label and to
    initialize/sync the dropdown, so the two can no longer diverge. When the
    encryption is none or unparseable the dropdown keeps its x25519 default.
    
    Closes #5744
  • fix(settings): include savePayload in the category body memo deps
    react-hooks/exhaustive-deps flagged the omission; a stale closure could
    hand SecurityTab an outdated save callback after a mutation state change.
  • fix(sub): resolve subscription clients and stats from normalized tables
    A subscription fetch inside a large inbound cost seconds because every
    layer re-parsed the inbound's full settings JSON: getInboundsBySubId
    preloaded the whole client_traffics table of each matched inbound,
    matchingClients parsed all clients to filter by subId, and then every
    per-protocol generator (raw links, JSON outbounds, Clash proxies) parsed
    the blob again per link — once to find the client by email and once for
    inbound-level fields like encryption or method. At 500k clients in one
    inbound that was 13s per raw fetch and 8.5s per JSON fetch; at 100k,
    2.6s/1.7s. After this change both cost ~70ms at 100k.
    
    matchingClients now resolves through the indexed clients/client_inbounds
    tables (ListForInboundBySubId, ordered by clients.id like ListForInbound
    — the same source the running Xray users are built from), and the
    per-request SubService carries two caches: clientsByInbound, primed by
    matchingClients/inboundLinks so clientForLink resolves a client without
    parsing settings (with the old full-parse as fallback, which also fixes
    the export-all-links path that re-parsed the blob once per client), and
    settingsByInbound, a once-per-request shallow decode that skips
    materializing the clients array entirely. The ClientStats preload is
    replaced by loading only the subscriber's traffic rows (indexed
    clients.sub_id); statsForClient's per-email DB fallback (#5567) covers
    any miss, and the case-insensitive email dedupe keeps the #5134
    guarantee for case-differing duplicate rows.
  • fix(job): batch ip-limit per-email lookups and persistence
    processObserved paid four round-trips per observed email every 10s scan:
    an inbound-resolving join, a tracking-row read, an autocommit Save (one
    fsync each under synchronous=FULL), and — worst of all — a full JSON
    parse of the owning inbound's settings blob just to read that one
    client's limitIp. On a big single inbound that parse alone made a scan
    cost ~1.5s per online client.
    
    The scan now front-loads three chunked batch queries (clients.limit_ip,
    email->inbound through the client_inbounds relation keeping the lowest
    inbound id like the old First(), and the tracking rows) and writes every
    inbound_client_ips change inside one transaction, so M observed emails
    cost a handful of queries and a single fsync. The per-email LIKE fallback
    remains for emails missing from the relation, preserving the #4963
    stale-email cleanup. limitIp now comes from the clients table (same
    source B3 gates on) instead of the settings blob, and xray disconnects
    for banned clients run after the commit so their network round-trips
    never extend the write transaction node syncs contend with.
  • feat(web): broadcast delta client stats above a snapshot threshold
    Both 5s broadcasters (the local traffic poll and the node traffic sync)
    shipped the complete client_traffics table on every cycle while a browser
    was connected. At 500k clients that is a 1.7s full-table read plus an
    86MB marshal per job per poll — and the hub drops any payload over 10MB
    and sends an invalidate the frontend ignores for these message types, so
    past ~55k clients all of it was pure waste and the UI got nothing.
    
    Installs at or below 5000 clients (clientStatsSnapshotMaxClients) keep
    the exact full-snapshot behavior — it exists because a pure delta feed
    left UI rows stale when nothing moved in a cycle (see GetAllClientTraffics)
    — and the payload now carries snapshot=true. Above the threshold the jobs
    send only this cycle's active rows (the xray poll's active emails, or the
    emails online on the synced nodes) with snapshot=false, and scope the
    last-online map to those rows; the initial full map still arrives over
    REST and the clients page refetches every 5s.
    
    GetActiveClientTraffics gains the overlayGlobalTraffic pass so delta rows
    carry the same cross-panel usage as snapshot rows. The node job also
    stops reading the full last-online map before the has-clients gate, which
    was a wasted full-table read on every tick with no dashboard open.
    
    Frontend: useClients keeps its live summary strictly snapshot-driven
    (snapshot=false payloads skip the allClientStats replace and the summary
    falls back to the server-computed one); the per-row page merge and the
    inbounds-page merges already handle deltas.
  • fix(job): gate ip-limit scan on clients.limit_ip instead of parsing all settings
    hasLimitIp ran settings LIKE '%limitIp%' and JSON-parsed every matching
    inbound's settings blob — and since clients marshal limitIp without
    omitempty, every inbound matched, so each 10s scan loaded and parsed
    every settings blob in the database (~75MB of JSON at 500k clients) just
    to decide whether any limit exists.
    
    It now probes the normalized clients table (limit_ip > 0, Limit(1) count
    like depletedCond does), which SyncInbound and the legacy seeder keep in
    sync with the settings JSON. Semantics note: a limitIp that exists only
    in settings JSON with no clients row no longer enables enforcement — the
    enforcement path itself already resolves clients through the same
    normalized tables.
  • fix(traffic): disable depleted clients by id instead of a second full scan
    disableInvalidClients evaluated the depleted predicate twice per poll:
    once to SELECT the rows (for xray removal and settings sync) and again in
    the UPDATE that flips enable off — each a full client_traffics scan, the
    second also re-running the cross-panel EXISTS subquery when global rows
    exist.
    
    The UPDATE now flips the already-collected rows by primary key in
    sqlInChunk batches, sorted for stable lock order. Same rows, same
    RowsAffected, half the scan cost; id-based matching also stays correct
    for rows with empty emails.
  • fix(traffic): persist delayed-start expiry only for converted clients
    addClientTraffic's second pass wrote expiry_time for every polled row via
    UPDATE ... WHERE expiry_time < 0 — a no-op statement per active client on
    every 5s poll, since almost all rows carry a positive expiry. At 10k
    active clients that was 10k pointless indexed UPDATEs per poll.
    
    adjustTraffics now returns the emails it actually converted this tick and
    the persistence pass writes exactly those, in sorted order to keep
    concurrent writers lock-compatible on Postgres. Behavior is unchanged:
    unconverted rows never matched the WHERE clause anyway.
  • test(scale): cover traffic poll, ws payloads, ip-limit job, sub and xray config at 500k
    The paths that run continuously in production had no scale coverage: the
    5s traffic poll (AddTraffic with its auto-renew and depleted scans), the
    websocket snapshot the job broadcasts while a browser is connected, the
    10s ip-limit job (hasLimitIp LIKE scan + per-email settings parse), a
    subscription fetch inside a huge inbound, and the full Xray config build.
    
    New benchmarks reuse the XUI_SCALE_TEST / XUI_DB_TYPE gating and stay
    log-only. Sizes default to 10k/100k; XUI_SCALE_SIZES=500000 raises the
    ladder without editing code. seedScaleDataset writes inbounds, clients,
    client_inbounds and client_traffics directly in one transaction instead
    of SyncInbound, so a 500k seed takes seconds. XUI_SCALE_DB_PATH persists
    the seeded SQLite file for manual smoke runs against a live panel.
  • docs: move architecture map into docs/ and refresh it against the live tree
    The architecture/code map previously lived in .claude/CLAUDE.md, which was
    gitignored (local-only) and auto-loaded into every agent session alongside
    the root CLAUDE.md. Track it in docs/architecture.md instead and reference
    it from CLAUDE.md so it is read on demand.
    
    While moving it, fact-check the whole map against the current tree:
    - add the missing internal/eventbus and internal/tunnelmonitor packages,
      the service/email subpackage, and util/wirecodec
    - document node mTLS (tls_client.go, node_mtls.go, setting_mtls.go) and the
      fourth TLS verify mode
    - add the Host, ClientExternalLink, NodeClientIp and ClientGlobalTraffic
      models plus their symptom-index rows
    - correct the cron table (check_cpu_usage is 1m not 10s; add
      check_memory_usage and free_os_memory), the middleware chain
      (MaxBodyBytes, ConfigEnvelope, CSRF) and the controller route prefixes
    - refresh the sub/ and service/ file listings, frontend pages (hosts/,
      index/), CI workflow list, and replace stale exact line counts with
      rounded sizes
  • feat(settings): let users clear stored secrets from the UI
    Redacted secrets (SMTP password, Telegram bot token, LDAP password) are
    always served blank to the browser, so the update path treats a blank
    submission as "unchanged" and silently restores the stored value. That
    made a once-set secret impossible to remove without editing the database
    — e.g. switching to a passwordless localhost SMTP relay kept sending the
    old credentials forever.
    
    Blank stays "unchanged"; clearing is now its own signal. The update
    request carries explicit clear flags (request-scoped fields on the
    controller form, so they are never persisted as settings rows), and
    preserveRedactedSecrets skips the restore for a flagged secret. Each
    secret field gets a Clear/Undo button that arms the flag; typing a new
    value disarms it. The 2FA token keeps its existing behavior: it is
    already clearable by disabling 2FA.
    
    Closes #5724
  • fix(sub): default https:// for scheme-less support and profile URLs
    A support URL saved without a scheme (e.g. "t.me/handle") is served
    verbatim in the subscription Support-Url header and page data, and client
    apps resolve it relative to the subscription domain — clicking it lands
    on "https://panel.example/t.me/handle". Same hazard for the profile URL.
    
    Default the scheme to https:// when none is present, both when saving the
    settings and when reading already-stored values, so existing databases are
    covered without a migration. Deliberate non-http schemes (tg://, mailto:,
    tel:) pass through untouched, which is why these two fields don't go
    through SanitizeHTTPURL's http(s)-only validation.
    
    Closes #5738
  • 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(node): stop Postgres deadlocks and deleted-client resurrection in node sync
    Two defects in the node traffic sync, both hit hard on busy
    master+multi-node Postgres deployments:
    
    Client-IP merges deadlocked. Each node syncs on its own goroutine and
    shared clients appear in several nodes' reports, but MergeInboundClientIps
    and upsertNodeClientIps locked rows in whatever order each node's report
    arrived. Two concurrent merges taking the same rows in opposite order is
    exactly what Postgres aborts with SQLSTATE 40P01 ("merge client ips from
    <node> failed: deadlock detected"). Both merges now process emails in
    sorted order so every transaction acquires row locks in one global order.
    
    Deleted clients resurrected with zeroed traffic. A snapshot fetched just
    before a deletion still names the deleted email; applying it after the
    delete committed re-added the client. The delete tombstone existed for
    precisely this race but only zeroed the seed counters: the sync still
    recreated the client_traffics row, and worse, adopted the node's stale
    settings JSON wholesale, putting the client back in the central inbound
    as if it were brand new with 0 traffic. Snapshot application now skips
    row creation for tombstoned emails on known inbounds and strips
    tombstoned clients from adopted settings; fresh node-adoption semantics
    (rows seeded at zero) are unchanged.
    
    The mass-disconnect part of the report is the forced node restart on
    auto-disable, removed separately in 4d6f2ddd.
    
    Closes #5739
  • fix(node): stop force-restarting a node's Xray when its clients auto-disable
    When a depleted or expired client lived on a node, the master pushed the
    updated inbound (client flipped off) to the node and then also told the
    node to fully restart Xray. The push alone already applies the disable:
    the node updates that one inbound on its running core. The extra restart
    dropped every live connection on the node each time any of its clients
    crossed a quota or expiry, and a restart that failed to come back left
    the node forwarding nothing until someone restarted Xray by hand.
    
    This mirrors e5b56c94, which removed the same forced restart from the
    local auto-disable path; remote nodes now get the same graceful
    reconcile-by-push treatment.
    
    Closes #5740
  • fix(scripts): pass --force to acme.sh --installcert so it survives sudo
    acme.sh guards every non-install command behind _checkSudo: when a
    non-root user runs the panel scripts via sudo, it prints the sudo wiki
    warning and exits before doing anything, unless FORCE is set. All our
    --issue calls already pass --force and were unaffected, but none of the
    --installcert calls did, so issuance succeeded and installation then
    aborted silently, ending in "Certificate files not found after
    installation". FORCE has no other effect on the installcert path, so
    mirror the --issue calls and pass --force everywhere we install certs.
    
    Closes #5741
  • feat(reality): derive a stable per-client spiderX for shared links
    The inbound's spiderX now acts as a per-client seed: exports emit
    sha256(seed|subKey) truncated to a 15-hex "/path", so a client's spx no
    longer changes on every subscription fetch (#5718) while different
    clients stop sharing one fingerprintable value. The form gains a
    regenerate button that rotates every client's path at once.
    
    The frontend link builders derive through the same function
    (lib/xray/spider-x.ts, @noble/hashes) keyed on subId-then-email like
    the Go subKey, so panel QR/copy links and subscription output agree —
    cross-language vector tests lock both sides byte-for-byte. streamData
    now tolerates malformed stored stream settings (unparseable JSON, null
    tls/reality settings) instead of panicking the subscription request.
  • feat(wireguard): make client allowedIPs editable with validation
    The WireGuard peer address was allocated server-side and shown read-only
    in the client editor, so changing it required hand-editing the inbound's
    raw settings JSON (#5715). The backend add/update paths already honored a
    submitted allowedIPs; only the form withheld it.
    
    Make the field editable (comma-separated, empty still auto-assigns) and
    validate submissions server-side: entries must parse as an IP or CIDR,
    bare addresses normalize to single-host prefixes, and an address already
    used by another peer on the inbound is rejected.
    
    Closes #5715
  • fix(node): show the activated first-use deadline on the Clients page
    With "start after first use" on a node inbound, the node activates the
    absolute deadline and the master adopts it into client_traffics via the
    sync CASE merge — but the client record (what the Clients page reads) was
    only refreshed by SyncInbound from the snapshot's settings JSON. A node
    whose JSON still carried the negative duration (stale conversion, older
    node build, or a mixed local+node attachment) kept rewriting the record
    back to "not started" even though the DB held the real deadline (#5714).
    
    Lift the activated deadline from client_traffics onto still-negative
    client records at the end of every node sync, after SyncInbound has run.
    Intentional resets back to delayed start are unaffected: editing a client
    also resets client_traffics to the negative duration, so the lift's
    expiry_time > 0 guard never matches.
    
    Closes #5714
  • fix(xray): reconcile client auto-disable through the API instead of a forced restart
    When a client expired or hit its traffic limit, XrayTrafficJob called
    RestartXray(true), stopping the whole process and dropping every live
    connection on every inbound (#5712 reported this as XHTTP on 443 dying) —
    even though disableInvalidClients had already removed the user from the
    running core over gRPC. The force restart existed only to re-sync the
    process's config snapshot.
    
    Switch the job to a non-forced restart and teach ComputeHotDiff to express
    a client-only inbound change as per-user AlterInbound operations for
    vless/vmess/trojan, so the reconcile is a no-op RemoveUser plus a snapshot
    update rather than a handler swap that would still blip that inbound's
    listener. Anything beyond the clients list still falls back to handler
    replacement or a full restart as before.
    
    Closes #5712
  • fix(groups): keep group traffic totals stable across client resets and deletes
    ListGroups displays live_sum(client_traffics) minus the group's stored
    reset baseline, but only ResetGroupTraffic ever moved the baseline. Any
    client-level operation that zeroed or deleted traffic rows (single/bulk
    reset, client delete, removing a client's last inbound) shrank the live
    sum and silently subtracted that client's history from the group total.
    
    Shift the baseline down by the removed counters inside the same
    transaction, so group totals only change through group reset. Derived
    groups without a stored row get one with a negative baseline, which the
    existing clamp handles.
    
    Closes #5675
  • fix(inbounds): apply the legacy xhttp session-key migration when editing
    rawInboundToFormValues injected the stored xhttpSettings blob into the form
    store without running it through XHttpStreamSettingsSchema, so the
    sessionPlacement/sessionKey -> sessionIDPlacement/sessionIDKey rename from
    xray-core v26.6.22 (and the v3.4.0 field defaults) never applied on the
    edit path. Inbounds saved before the rename opened with blank session
    fields, and the stale keys could ride back on save even though the core no
    longer reads them. Parse the sub-object through the schema on load, and
    lift any stale legacy keys in normalizeXhttpForWire as a backstop.
    
    Closes #5621
  • 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
  • fix(sub): use configured spiderX instead of always randomizing
    applyShareRealityParams and SubJsonService.realityData generated a fresh
    random spx on every export, so share links, "export all links", and JSON
    subscriptions never matched a spiderX configured on the inbound and two
    exports of the same client disagreed with each other. Read the value from
    realitySettings.settings like pbk/fp/pqv and keep the random value only as
    a fallback when none is configured.
    
    Closes #5718
  • fix(xray): force full restart for inbounds with a VLESS reverse client
    Hot-applying an inbound change swaps it via DelInbound+AddInbound on
    the running core. That unregisters any client's reverse.tag handler
    on the xray-core side without closing the bridge's already-established
    connection, so the reverse tunnel is silently orphaned until someone
    manually restarts xray. diffInbounds now bails out of the hot-apply
    path whenever the old or new inbound carries a reverse-tagged client,
    falling back to a full restart, which actually drops the socket and
    lets the bridge redial on its own.
    
    Also scope the .claude ignore rule to its contents (.claude/*) instead
    of the whole directory, so individual files under .claude/ can be
    tracked selectively.
  • chore(ci): upgrade claude-bot to Sonnet 5 and set explicit effort levels
    Sonnet 5 reaches near-Opus quality on coding/agentic work at lower cost;
    pin effort explicitly (xhigh/max) instead of relying on model defaults.
  • fix(node): stop the offline-sync toast firing on saves to online nodes
    IsNodePending fed the user-facing "saved locally, node offline, will
    sync on reconnect" toast off three conditions, one of which was the
    node's config_dirty flag. But every node-backed client/inbound edit
    marks the node dirty unconditionally inside its write transaction — it
    is the reconcile self-heal marker, set even for edits pushed live to a
    healthy online node. The controller reads that freshly-set flag right
    after the save, so the warning fired on every save to a node-backed
    inbound regardless of the node actually being online.
    
    Drop the dirty term so the predicate reflects only what the message
    claims: the node being unreachable (offline or disabled). Offline and
    disabled nodes still mark dirty and still surface the toast.
    
    Add regression tests: online+dirty must not be pending; offline and
    disabled must be.
  • chore(deps): bump antd to 6.5 and migrate deprecated component props
    Upgrade frontend deps (antd 6.4.5 -> 6.5.0, Ant Design icons, TanStack
    Query, i18next, eslint) and fasthttp 1.71 -> 1.72.
    
    AntD 6.5 deprecated several Input/Card/Space props, so adapt the panel UI:
    - Input/InputNumber addonBefore/addonAfter -> prefix/suffix
    - Card bordered -> variant="outlined"
    - Space direction -> orientation
    - swap the hand-rolled Telegram SVG for the new TelegramFilled icon
    - guard SettingListItem against cloning aria-labelledby onto a Fragment,
      which only accepts key/children
  • fix(sub): bake Host VLESS Route into subscription UUIDs
    The Host VLESS Route field was stored and shown in the panel but never applied to any generated subscription (raw, JSON, Clash), so the UUID was emitted unmodified (#5655).
    
    Xray reads the route from the UUID's 3rd group (bytes 6-7, net.PortFromBytes) and masks those bytes to zero before authenticating, so a value can be baked into the share/JSON/Clash UUIDs without breaking the user match. A shared applyVlessRoute helper encodes a single 0-65535 value as the 3rd group; empty/invalid/non-UUID input is left unchanged, so legacy data never yields a broken link and no DB migration is needed.
    
    The field was wrongly validated as a multi-segment port spec (that form belongs to the separate server-side routing rule). It is now a single value 0-65535, with frontend validation, link-preview parity (genVlessLink/hostToExternalProxyEntry), hint + error translations across all 13 locales, and tests on every path.
    
    Closes #5655
  • fix(clients): re-enable depleted clients on API renewal (#5619)
    Renewing a subscription via POST /panel/api/clients/bulkAdjust extended a client's expiry/quota but left it disabled. The enforcement loop disables a depleted client across client_traffics, client_records and the inbound settings JSON (and pushes that to the node), while BulkAdjust only updated expiry/total and never cleared enable. On a node its UpdateUser push was built from the stale ClientRecord (Enable=false), which the next traffic poll merged back onto the master, so the client never recovered.
    
    BulkAdjust now re-enables a client only when it was disabled because it was depleted and the adjustment lifts it back within limits, computed as a set-difference of the production depletedCond predicate and applied through the canonical BulkSetEnable (run after the per-inbound loop, since lockInbound is non-reentrant). Manually-disabled or still-depleted clients stay disabled.
    
    Update now writes the clients.enable column explicitly so re-enabling sticks for inbound-less clients and stops feeding a stale record into node pushes.
  • fix(xray): clean stale routing references when a balancer or outbound is deleted (#5648)
    * feat(xray): reference-cleanup helpers for entity deletion
    
    When an outbound or balancer is deleted on the Xray page, routing rules and
    balancers that reference it must be repaired in the same edit, or the saved
    config breaks the core: a dangling balancerTag stops Router.Init (whole core
    down), a dangling outboundTag black-holes matched traffic at the dispatcher.
    
    Add pure plan*/apply* helpers that compute and apply the cleanup. A rule is
    kept when a destination (outboundTag or balancerTag) remains and dropped when
    none does. Deleting an outbound cascades: emptying a balancer selector removes
    that balancer too, then repairs its rules in one pass against the full removed
    set; fallbackTag and dialerProxy references are cleared and observatories
    re-synced.
    
    * fix(balancers): clean routing rules referencing a deleted balancer
    
    Deleting a balancer left routing rules pointing at its balancerTag. xray-core's
    Router.Init then fails ("balancer <tag> not found"), the core won't restart and
    every inbound drops — the saved config passes CheckXrayConfig (JSON shape only),
    so it breaks only on the next restart.
    
    The delete confirm now lists the affected rules (modified vs removed) next to
    the existing observatory warning and applies planBalancerDeletion's cleanup: a
    rule keeps its outboundTag when present, otherwise the whole rule is dropped.
    Adds the shared DeletionImpactList and refCleanup strings across all 13 locales.
    
    * fix(outbounds): clean rules, balancer selectors and dialerProxy on outbound delete
    
    Deleting an outbound left routing rules pointing at its outboundTag (matched
    traffic black-holed at the dispatcher), plus stale references in balancer
    selectors / fallbackTag and other outbounds' dialerProxy.
    
    The delete confirm now shows planOutboundDeletion's impact and applies the
    cascade: rules keep a remaining balancerTag (else are dropped), the tag is
    pulled from balancer selectors and fallbacks, dialerProxy references are
    cleared, and a balancer whose selector is emptied is removed along with its
    own now-targetless rules.
    
    * refactor(xray): share one rule classifier across preview and apply
    
    Code review flagged that the keep/drop predicate was transcribed twice — in
    ruleImpacts (the delete-modal preview) and in applyCleanup (the mutation) — kept
    in sync only by a parity test. Extract a single classifyRule() that both call,
    so the preview can never disagree with what apply actually does.
    
    Also harden balancersEmptiedBy to skip tagless balancers: an empty/missing tag
    would otherwise enter the removed set as "" and silently drop every other
    tagless balancer (only reachable via a hand-edited config, but a silent data
    loss). And remove observersRemovedByDeletingBalancer, orphaned once BalancersTab
    switched to planBalancerDeletion.
    
    * fix(xray): null-guard reference cleanup against unvalidated configs
    
    The PR review noted that classifyRule and applyCleanup dereferenced rule /
    balancer entries directly, while the sibling propagateOutboundTagRename uses
    optional chaining — because fetchXrayConfig falls back to the unvalidated parsed
    object when Zod validation fails, a stray null in rules / balancers can survive
    into the editor and would throw during the delete preview/apply.
    
    Match that defensive style: classifyRule and balancersEmptiedBy read through
    optional chaining, the balancer loop skips nullish entries, and the dialerProxy
    walk guards the outbound. A delete on a hand-edited config with null entries now
    degrades gracefully instead of throwing.
  • feat(a11y): screen-reader & keyboard accessibility across the panel (#5486) (#5652)
    * feat(a11y): label list, toolbar & dashboard actions for screen readers
    
    Phase 1 of #5486 (Android TalkBack support). Icon-only controls across
    the management surfaces previously announced only their untranslated
    icon name (e.g. "edit", "ellipsis") or nothing at all.
    
    - Add aria-label to icon-only row-action and toolbar buttons across
      inbounds, clients, groups, hosts, nodes and xray
      (outbounds/routing/dns/balancers) lists, plus the dashboard cards.
    - Make clickable bare icons and AntD Card actions keyboard-operable via
      role/tabIndex + Enter/Space (new activateOnKey helper); convert mobile
      dropdown triggers to buttons so they open from the keyboard.
    - Fix the sidebar hamburger's mislabeled aria-label (was the dashboard
      label) and translate previously-hardcoded outbound menu labels.
    
    New i18n keys in all 13 locales: sort, menu.openMenu,
    pages.xray.outbound.moveToTop.
    
    * feat(a11y): label modal, QR and copy/download controls for screen readers
    
    Phase 2 of #5486. Modal and overlay controls relied on tooltips (not a
    reliable accessible name) or were bare clickable icons with no keyboard
    or screen-reader support.
    
    - Add aria-label to copy/QR/download/info icon buttons in the inbound and
      client info modals, sub-links modal, QR panel, backup/log modals, and
      to the bare search/select inputs of the attach/detach client modals.
    - Make click-to-copy QR codes and the IP-log refresh/clear, geofile
      reload and log refresh icons keyboard-operable (role/tabIndex +
      Enter/Space) with translated labels.
    - Label the 2FA code input; drop the QrPanel download-image string
      fallback now that the key exists.
    
    New i18n key in all 13 locales: downloadImage.
    
    * feat(a11y): label form fields and shared form components for screen readers
    
    Phase 3 of #5486. Form controls and shared form widgets were largely
    unlabelled, and several remove controls were not keyboard-operable.
    
    - SettingListItem now ties its title to the control via aria-labelledby,
      giving accessible names to the ~90 settings-tab inputs at once.
    - InputAddon gains button semantics (role/tabIndex/Enter+Space) and an
      ariaLabel prop when used as an interactive remove control.
    - Sparkline charts expose a role="img" summary of their latest values.
    - Add aria-label to add/remove/regenerate icon buttons and bare
      inputs/selects across inbound, client and xray (dns/routing/balancer/
      outbound) forms; make clickable remove icons keyboard-operable; mark
      decorative help/target icons aria-hidden; label the JSON editor,
      date-time clear button, header-map remove, notification select-all and
      remark token chips.
    
    New i18n keys in all 13 locales: regenerate, jsonEditor,
    pages.xray.balancer.{costMatch,costValue,costRegexp}.
    
    * chore(a11y): add eslint-plugin-jsx-a11y harness and fix flagged interactions
    
    Phase 4 of #5486. Adds eslint-plugin-jsx-a11y (recommended ruleset,
    scoped to .tsx) so screen-reader/keyboard regressions fail lint.
    
    - Make the mobile node-card header a proper keyboard disclosure
      (role=button, aria-expanded, Enter/Space activation that ignores
      clicks on the nested action buttons) and drop the now-redundant
      stop-propagation click handlers the linter flagged on card-action
      wrappers in the node, client and inbound mobile cards.
    - Disable jsx-a11y/no-autofocus: the autofocus on the login field and
      modal primary inputs is intentional focus management that helps
      screen-reader and keyboard users land on the right control.
    
    make lint passes with the a11y ruleset enforced.
    
    * feat(a11y): cover remaining deferred spots (settings tabs, sockopt, API docs)
    
    Completes the panel sweep for #5486 by labelling the spots previously
    left out of phases 1-4:
    
    - NotifyTimeField (Telegram notifications): the mode, interval, unit and
      custom-cron inputs now carry aria-labels.
    - The Sockopt toggle in transport options.
    - Settings category tabs in icons-only (mobile) mode now expose the tab
      name as the icon's aria-label instead of the raw icon name.
    - The Swagger API-docs view is wrapped in a labelled region landmark.
    
    New i18n keys in all 13 locales: pages.settings.notifyTime.{interval,unit}.
    
    * feat(a11y): label shared xray form components and remark field
    
    Code review surfaced frontend/src/lib/xray/forms/ — shared form components
    used by the host and inbound JSON forms — which the initial audit missed.
    
    - FinalMaskForm (TCP/UDP final-mask editor): label the icon-only add and
      regenerate buttons and make all six remove icons keyboard-operable
      (role/tabIndex/Enter+Space); adds useTranslation to its sub-components.
    - CustomSockoptList: the remove icon is now keyboard-operable.
    - SniffingFields: aria-label on the otherwise label-less destOverride select.
    - RemarkTemplateField: aria-label on the remark-variable picker button.
    
    New i18n key in all 13 locales: pages.inbounds.sniffingDestOverride.
    
    * feat(a11y): label client info modal and WireGuard config block
    
    After rebasing onto the WireGuard client-config feature, re-apply the
    ClientInfoModal copy/QR/IP-log aria-labels (the modal was restructured
    upstream, so the original labels did not carry over) and label the new
    ConfigBlock component's copy/download/QR actions. ConfigBlock's action
    wrapper keeps its stop-propagation handler (a non-interactive guard for
    the Collapse header) under a scoped jsx-a11y exception.
    
    * fix(frontend): let npm install jsx-a11y under ESLint 10
    
    eslint-plugin-jsx-a11y@6.10.2 declares a peer range that stops at ESLint 9,
    but the panel is on ESLint 10, so `npm ci` aborts with ERESOLVE even though
    the plugin runs fine on ESLint 10 with flat config. Add an npm override so
    jsx-a11y accepts the project's ESLint version. This keeps normal peer
    resolution (recharts' react-is peer still auto-installs) — no global
    legacy-peer-deps and no manual react-is pin needed.
    
    * fix(a11y): size mobile row triggers and move node expand role to chevron
    
    Address automated review on #5652:
    - add size="small" to the inbound/client/node mobile-card "more" dropdown
      triggers so they match the adjacent small Switch and the established
      desktop RowActions pattern.
    - move the node card-head disclosure semantics (role/tabIndex/aria-expanded/
      keyboard) onto the chevron affordance so the expand control is no longer a
      role="button" wrapping the Switch, info button and dropdown. Mouse
      click-anywhere-to-expand is preserved on the header div.
  • fix(clients): hide WireGuard config after detaching the WG inbound
    The client info and QR modals rendered a WireGuard config whenever the
    client still carried leftover WG key material (privateKey / publicKey /
    allowedIPs / preSharedKey / keepAlive), regardless of whether a WireGuard
    inbound was actually attached. After detaching the WG inbound the config
    kept showing, built with an empty endpoint port and public key.
    
    Gate wgConfigText on an attached WireGuard inbound (wgInbound) being
    present, not just isWireguardClient(client), in both ClientInfoModal and
    ClientQrModal.
    
    Also rename the i18n key pages.clients.conf -> config and add the missing
    pages.clients keys (wireguardConfig, config, bulkFlow, bulkFlowNoChange,
    bulkFlowDisable) to all 12 non-English locales so each one matches en-US.
  • feat(wireguard): client config UX, collapsible config card, configurable DNS
    Land the WireGuard client-config UX work on main (the upstream PR #5642
    branch could not be pushed to).
    
    - Reusable collapsible ConfigBlock (copy/download/QR, actions aligned right)
      for the client .conf, used by client info and the public sub page.
    - Correct .conf: canonical PresharedKey casing and DNS sourced from the inbound
      (configurable per-inbound, default 1.1.1.1, 1.0.0.1).
    - Configurable per-inbound DNS for WireGuard (schema + form + backend hint via
      InboundOption.WgDns); inert at the Xray layer.
    - Public sub page now shows the WireGuard config, rebuilt from the share link;
      the Go wireguard:// link carries dns/presharedkey/keepalive for completeness.
    - QR enabled for the wireguard:// link; link rows are compact like other protocols.
    - Client information order is subscription, copy URL, WireGuard config; the
      redundant config tab is removed from the add/edit client modal.
    - Drop the Inbound Information and QR Code row actions for WireGuard inbounds.
  • feat: ldap skip tls verify (#5637)
    * feat(ldap): add InsecureSkipVerify field and tlsConfig helper
    
    Extract the inline TLS config at both LDAPS dial sites (FetchVlessFlags,
    AuthenticateUser) into a tlsConfig(cfg) helper, and add a new
    Config.InsecureSkipVerify bool that flows through to
    tls.Config.InsecureSkipVerify. This unblocks enterprise environments
    (e.g. Microsoft AD CS with internal CAs) where the server certificate
    chain cannot be imported into the system trust store.
    
    Behavior is identical when InsecureSkipVerify is false (the default) -
    pure refactor + plumbing. The helper is unit-testable without a live
    server, which is why it is extracted.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * feat(settings): add LdapInsecureSkipVerify setting
    
    Plumb the new LDAP skip-TLS-verify toggle through the settings stack:
    - AllSetting struct field (json/form tag: ldapInsecureSkipVerify)
    - defaultValueMap default ("false")
    - GetLdapInsecureSkipVerify() getter
    - ldap_sync_job wiring into ldaputil.Config (FetchVlessFlags path)
    - panel/user.go wiring into ldaputil.Config (AuthenticateUser path;
      the original issue's file list missed this)
    
    Persistence is handled by UpdateAllSetting's reflect loop, matching
    the existing pattern used by ldapUseTLS (no explicit setter).
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * feat(ui): add Skip TLS verification switch in LDAP settings
    
    Wire the new ldapInsecureSkipVerify setting into the hand-written
    frontend model and Zod schema, and render it as a new Switch in
    GeneralTab right under "Use TLS (LDAPS)". The switch is disabled
    when TLS is off (the setting is meaningless without LDAPS) and shows
    an insecure-warning description to make the security implication
    visible to operators.
    
    Also adds a Vitest round-trip test pinning schema acceptance and
    model default-to-false behavior.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * chore(i18n): add Skip TLS verification strings to all locales
    
    Add pages.settings.ldap.skipTlsVerify and skipTlsVerifyDesc to all 13
    backend-served translation files, matching the existing repo
    convention of keeping LDAP keys present in every locale (en-US, fa-IR,
    ru-RU, zh-CN, zh-TW, pt-BR, ar-EG, uk-UA, id-ID, tr-TR, vi-VN, ja-JP,
    es-ES). No translation-parity test exists in CI, but every other
    LDAP key is replicated across all files, so this keeps the
    invariant intact.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
    
    * chore(codegen): regenerate frontend artifacts
    
    Regenerate frontend/src/generated/{zod,types,schemas,examples}.ts
    and frontend/public/openapi.json via `npm run gen` to reflect the
    new ldapInsecureSkipVerify field. The codegen CI job runs
    `git diff --exit-code` on these files; failing to commit them would
    break the build.
    
    Closes https://github.com/MHSanaei/3x-ui/issues/5538
  • fix(sync): mark node dirty inside the mutation transaction (atomic ConfigDirty) (#5611)
    * fix(sync): mark node dirty inside the mutation transaction
    
    ConfigDirty is currently set by MarkNodeDirty AFTER the mutation, on a
    separate DB handle outside the mutation's transaction. A crash or error
    between the committed change and the mark leaves a committed config
    change that never reconciles to the node (silent drift). Add
    MarkNodeDirtyTx(tx, id) and call it inside each mutation's transaction so
    the dirty mark commits atomically with the change.
    
    * fix(test): initialize DB in TestResolveInboundAddress and group gorm import
    
    Two CI failures on this branch:
    
    - race (-shuffle=on): TestResolveInboundAddress reaches resolveInboundAddress -> configuredPublicHost -> GetSubDomain, which reads the global DB. The test never initialized one, relying on another sub-package test to do so first; under shuffle it ran first and nil-dereferenced gorm. Call initSubDB(t) so it is self-sufficient (empty DB yields an empty subDomain, so the subscriber-host fallback still holds).
    
    - golangci goimports: gorm.io/gorm was grouped with the github.com/mhsanaei/3x-ui local imports in node_dirty_test.go. Move it into the third-party group.
  • fix(settings): require re-2FA confirmation for sensitive setting changes (#5610)
    * fix(settings): require server-side 2fa for sensitive changes
    
    * fix(lint): group third-party imports separately from local (goimports)
    
    golangci-lint goimports flagged setting.go and setting_security_test.go because xlzd/gotp and gorm.io/gorm were mixed into the github.com/mhsanaei/3x-ui local-prefix group. Move them into the third-party group so the local imports stand alone.
  • feat(balancers): tabbed Observatory/Burst Observatory form (#5627)
    * feat(balancers): tabbed Observatory/Burst form replacing raw JSON
    
    Replace the raw JSON editor for the Observatory / Burst Observatory sections
    with a proper Ant Design form, and split the Balancers page into two sub-tabs:
    "Balancer Settings" (the existing table) and "Observatory".
    
    Observers stay fully auto-managed by balancer strategy through the existing
    syncObservatories logic: users edit only the tunable probe fields, the
    subjectSelector is shown read-only since it is derived from the balancers, and
    deleting the last balancer that needs an observer now warns in the confirm
    dialog that the observer will be removed too. Overlapping selectors keep an
    observer alive while any balancer still references it.
    
    Also add the previously missing pingConfig.httpMethod field (HEAD/GET) and
    translations for the new strings across all 13 locales.
    
    * refactor(balancers): tighten httpMethod typing and align connectivity default
    
    Address automated review feedback on the Observatory form:
    - Use the ObservatoryHttpMethodSchema enum for pingConfig.httpMethod instead of
      a free-form z.string(), and drive the HTTP method Select from its options.
      Removes the previously dead enum export and the duplicate local list, and
      types the field as 'HEAD' | 'GET'.
    - Align the schema's connectivity default with DEFAULT_BURST_OBSERVATORY (the
      hicloud URL) so it matches what burst observers are actually created with.
    
    No behavior change.
  • fix(balancers): defer validation errors until touched or save (#5626)
    The Add Balancer modal parsed its empty initial state through
    BalancerFormSchema on mount and bound Form.Item validateStatus/help
    directly to the result, so "Tag is required" and "Pick at least one
    outbound" rendered the moment the modal opened, before any user input.
    
    Gate the inline errors behind per-field touched tracking plus a
    submit-attempted flag, and drop the disabled Create button so a save
    attempt surfaces the errors (matching RuleFormModal). The existing
    key-based remount in BalancersTab resets the flags on each open.
    
    Add a regression test asserting no errors on open and errors only
    after a save attempt.
  • Bump minimum eligible Xray version
    Update Xray release filtering to only include versions at or above v26.6.27 (previously v26.4.25). Also mark `google.golang.org/protobuf` as a direct dependency in `go.mod` by removing the `// indirect` annotation.
  • fix(wireguard): allocate client IPs in the existing peer subnet
    defaultWireguardClients always allocated new tunnel addresses from the
    hardcoded 10.0.0.0/24 base, so a legacy or migrated inbound whose peers
    live in a different subnet (e.g. 172.16.0.0/24) got new clients in an
    unrelated, unroutable range. Derive the allocation base from the existing
    peers' /24 and fall back to 10.0.0.0/24 only when there are none.
  • 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.
  • feat(xhttp): default xmux maxConnections to 6
    xray-core v26.6.27 changed the XHTTP client xmux default to maxConnections=6 (anti-RKN). The panel previously sent maxConnections=0, which overrode that default; default XHttpXmuxSchema to 6 so new outbounds adopt it and the wire-exclusivity rule drops maxConcurrency accordingly.
  • chore(deps): bump xray-core to v26.6.27
    Update the xray-core Go module (infra/conf builders + gRPC command clients) and the bundled binary pin in DockerInit.sh and the release workflow from v26.6.22 to v26.6.27. No gRPC command-API breaking changes. The release's other inbound work rides along with the bump: TUN autoSystemRoutingTable/autoOutboundsInterface are already modeled in the frontend tun schema, while Hysteria vlessRoute (UUID-derived) and the TUN traffic counters are internal to xray-core and need no panel changes.
  • fix(lint): use errors.Is for io.EOF comparison in sys_linux
    The errorlint linter rejects direct error comparison with != because it
    fails on wrapped errors. Compare via errors.Is(err, io.EOF) instead.
  • feat(groups): reset group traffic without touching client counters
    The group page shows traffic counting per group, but the only reset
    available zeroed every member client's up/down counters (and their
    quotas) via bulkResetTraffic. Group traffic is a derived sum of client
    traffic, so zeroing the group display previously required mutating the
    clients themselves.
    
    Add a display-only baseline: ClientGroup gains reset_up/reset_down
    columns (additive, handled by AutoMigrate). ResetGroupTraffic snapshots
    the group's current up/down sum into the baseline, and ListGroups now
    reports max(0, sum - baseline). Client counters are left untouched and
    no Xray restart is triggered. A new POST /panel/api/clients/groups/
    resetTraffic endpoint drives it, creating the client_groups row when the
    group exists only as a derived label.
    
    The groups page action now calls the new endpoint; confirm/success
    strings updated across all 13 locales to reflect group-only semantics.