Commit Graph
109 Commits
  • fix(clients): clarify renewal preview times and estimates (#6662)
    * fix(clients): clarify renewal preview times and estimates
    
    The preview rendered RFC3339 strings directly and labeled the server's Local
    zone without explaining which clock it represented. Its renewal count also
    looked like a record of renewals already performed.
    
    Display readable dates with an explicit UTC offset while preserving the
    server's wall time, per-date DST offset and fractional cutoff precision.
    Explain the panel/server timezone and read-only preview, and label the
    renewal count as estimated allowance consumption in all 13 locales.
    Let the first-cutoff button wrap on narrow screens and update the English
    and Chinese client documentation plus display/form regression coverage.
    
    This changes presentation only: renewal calculations, stored expiry values,
    API payloads and first-use behavior remain unchanged.
    
    * test(clients): remove redundant renewal preview copy checks
    
    The locale-only preview case repeated the Local timezone branch without
    covering a distinct behavior. Exact textContent comparisons after matching
    the same text with getByText also only pinned constant wording, contrary
    to the repository's testing guidance.
    
    Remove that duplicate case, its locale setup and the redundant copy
    assertions. Keep the UTC, per-boundary DST offset, fractional precision
    and original datetime checks, together with the existing real form-save
    tests. Production rendering, translations and renewal behavior are unchanged.
    
    ---------
    
    Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
  • chore(deps): bump frontend and docs deps, clear npm audit findings
    Bump vite, oxlint/oxfmt, msw, jsdom and plugin-react in the frontend, and
    fumadocs, lucide-react, oxlint/oxfmt, postcss and pnpm in docs.
    
    npm audit reported seroval <=1.6.2 (critical) via solid-js, which the
    react-query devtools pull in pinned to ~1.5.4, and sprintf-js (no patched
    release) via remarkable's argparse@1. `npm audit fix --force` "fixed" both
    by downgrading swagger-ui-react to 3.23.3, which brings in far worse
    advisories. Instead override seroval/seroval-plugins to ^1.6.8 and give
    remarkable argparse@2; remarkable only requires argparse from its unused
    CLI entry, so the bundled library is unaffected.
    
    pnpm appends an exact-version minimumReleaseAgeExclude entry on every
    update of a too-fresh release and never prunes them. Drop the stale ones;
    keep only fumadocs 16.16.2 and oxlint/oxfmt, still inside the 1-day cutoff.
  • fix(tuic): client speed display and certificate button layout (#6723)
    * fix(tuic): restore client speed and certificate layout
    
    * docs(tuic): clarify native runtime and protocol behavior
    
    * fix(websocket): preserve traffic updates from independent sources
    
    * fix(docs): sync websocket traffic schema and drop restating TUIC tests
    
    docs/public/openapi.json still described the old traffic event, without
    clientTrafficSource/clientTrafficIntervalMs or the TUIC oneOf branch, so
    the docs site showed a payload the panel no longer sends. No check
    covers that copy.
    
    The TUIC certificate layout test and the TUIC speed payload test only
    read back the literals the code writes, so neither could fail on a real
    regression. Both are removed, along with the className that existed only
    for the layout test.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • fix(server): apply the outbound address policy to remote cert pinning
    The remote certificate fetch now dials through the same netsafe guard
    as the REALITY target scan. A private or loopback endpoint is refused
    unless the request carries allowPrivate; the inbound form asks the
    operator to confirm and retries with the opt-in.
  • feat(tuic): implement native in-process Go TUIC v5 server (#6577)
    * feat(tuic): implement native in-process Go TUIC v5 server
    
    - Implement native TUIC v5 protocol server on pure Go using quic-go
    - Bridge decrypted TCP/UDP traffic into Xray-core via loopback SOCKS5 inbound
    - Support full Xray routing rules (geosite/geoip) and cascading outbounds
    - Implement atomic per-client traffic accounting with TotalGB and ExpiryTime
    - Add automatic legacy cleanup for older Rust tuic-server binaries, configs, and orphaned processes
    - Eliminate external Rust tuic-server downloads from install/CI scripts
    
    * fix(tuic): address traffic accounting, client reload, and socket lifecycle issues
    
    * fix(service): update checkTuicSocksReverseConflict to use bindAddr for listenOverlaps
    
    * fix(tuic): resolve traffic double-accounting, UDP fragmentation, and socket lifecycle issues
    
    * feat(tuic): complete native Go integration and address audit findings
    
    - Integrate an isolated QUIC fork pinned to a specific commit
    - Preserve original QUIC dependencies for Xray, Hysteria and Gin
    - Apply BBR, CUBIC and Reno to server connections and exported client profiles
    - Bridge Xray BBR with correct monotonic time and congestion type conversions
    - Handle congestion sender recreation after PMTU changes
    - Update congestion control for new connections without restarting the listener
    - Preserve existing connections and their selected congestion controller
    - Apply per-inbound log levels through the shared panel logger
    - Add lifecycle, authentication and TCP/UDP relay events without exposing secrets
    - Rate-limit repeated authentication and relay warnings
    - Support native and QUIC UDP relay modes on the same listener
    - Recover UDP associations after relay worker failures
    - Fix TCP relay cancellation, idle shutdown and half-close handling
    - Close active sessions when client credentials are revoked or disabled
    - Track traffic by immutable client statistics IDs across email and UUID changes
    - Prevent ambiguous accounting and duplicate UUIDs within TUIC inbounds
    - Persist pending traffic in a durable shutdown journal
    - Replay journal batches transactionally without duplicate accounting
    - Report server shutdown failures through the shared logger
    - Preserve legacy flat and nested TUIC settings compatibility
    - Normalize congestion controller values consistently across backend and frontend
    - Preserve controller, UDP mode and SNI in client links and subscriptions
    - Separate client profile options from server settings in the TUIC form
    - Keep certificate path autofill explicit when changing client SNI
    - Align UDP packet size validation with protocol limits
    - Simplify and localize TUIC field hints and certificate autofill messages
    - Add controller, TCP/UDP, logging and live settings update tests
    - Add accounting identity, journal replay and shutdown regression tests
    - Add relay recovery, session revocation and legacy frontend form tests
    
    * fix(service): alias the TUIC duplicate-UUID subquery for PostgreSQL < 16
    
    syncInboundClients runs a COUNT(*) FROM (subquery) for every client sync,
    whatever the protocol. PostgreSQL before 16 rejects a FROM subquery with
    no alias, so on the distro PostgreSQL install.sh provisions (14 on Ubuntu
    22.04, 15 on Debian 12) every client add or edit failed with SQLSTATE
    42601. Reproduced against postgres:15 with the new env-gated test.
    
    * fix(database): create tuic_traffic_receipts through the model migration
    
    AddTuicTrafficBatch issued CREATE TABLE IF NOT EXISTS at runtime, a schema
    change outside db.go. The table was invisible to allModels and
    migrationModels, so x-ui migrate-db dropped the receipts and a retained
    journal could be counted twice after a SQLite to PostgreSQL move. It is
    now a GORM model in both lists, and the insert uses OnConflict DoNothing.
    
    * chore(tuic): skip the ICMP-dependent relay test on Windows, drop dead collectors
    
    Go disables SIO_UDP_CONNRESET on Windows, so a dead UDP bridge never fails
    a read there and TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure
    was red on every Windows run. Server.CollectTotalTraffic and
    Manager.CollectTraffic had no caller.
    
    * refactor(tuic): serve TUIC on apernet/quic-go instead of a personal fork
    
    The native server depended on github.com/poise52/quic-go, a personal fork
    of apernet/quic-go patched only to pick the congestion controller before
    the handshake. That put a second QUIC/TLS stack in the binary that no
    upstream security fix reaches. apernet/quic-go is already in the graph
    through xray-core and exposes SetCongestionControl, so BBR is now installed
    on each accepted connection with Xray's own congestion.UseBBR; the
    cross-module BBR adapter is gone.
    
    apernet ships New Reno as its only built-in sender, so a cubic setting is
    served as new_reno server-side (clients still get cubic in their profile).
    The test inspectors now read the sender under congestionMutex, which the
    post-handshake install writes under.
    
    Linux loopback, single stream through Xray: 2428 -> 3383 Mbit/s (bbr).
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(inbounds): deploy AmneziaWG, TUIC and MTProto inbounds to nodes
    The node gate assumed a node-assigned sidecar row would never converge,
    because the master's reconcile loops only read node_id IS NULL rows. But
    a pushed row is local on the node's own panel, whose AmneziaWG, TUIC and
    mtg loops run it like any other; node-adopted rows of these protocols
    already worked. Only creating or cloning them from the master was blocked.
    
    Open the three protocols on both lists and fix what assumed the master's
    host for a node row:
    - A node older than the release that introduced the protocol (MTProto
      v3.5.0, AmneziaWG v3.7.0, TUIC v3.8.0) would hand it to Xray as-is, so
      add and protocol-changing update refuse it, and a node that has not
      reported its version yet. Dev builds ("dev+<sha>") track main and pass.
    - MTProto's routeXrayPort is a loopback port on the host running mtg.
      The master no longer allocates one, nor forwards a cloned source's, for
      a node row; the node allocates its own and node sync adopts it back.
    - AmneziaWG forwardedPorts were checked against the master's inbounds,
      web port and id-derived relay ports. A node row is now checked against
      its own node's inbounds; the node re-checks what only it knows.
      UpdateInbound restores the stored nodeId before that check.
    
    Verified on a docker master+node pair: AWG, routed MTProto and TUIC
    created and cloned from the master start on the node (interface, mtg,
    tuic-server); an AWG client added and an MTProto client edited on the
    master apply on the node; the node-chosen egress port survives edits.
    
    Closes #6306
  • fix(sub): carry REALITY ML-KEM hint in VLESS links (#6712)
    * fix(sub): carry REALITY ML-KEM hint in VLESS links
    
    Keep raw share links in parity with Clash subscriptions for Xray 26.9.8+. Preserve the URI hint through Go and frontend imports, expose it in the outbound editor, and update the documentation tooling.
    
    * fix(link): accept REALITY ML-KEM boolean aliases
    
    * test(frontend): isolate Happ preset notifications
    
    * fix(link): keep the ML-KEM hint out of Xray REALITY settings
    
    support-x25519mlkem768 is a Mihomo reality-opts option; xray-core's
    REALITYConfig (infra/conf/transport_security.go) has no such field and its
    JSON loader drops unknown keys silently. The PR also stored it as
    realitySettings.supportX25519Mlkem768 in Xray outbounds (form switch, Go and
    TS link import, docs outbound builders) and as an inbound settings default
    that is stripped before Xray and read by no link generator. The outbound
    switch therefore did nothing, and imported links carried a dead key into the
    JSON subscription.
    
    The share-link hint itself stays: Go, frontend and docs still emit
    support-x25519mlkem768=true on VLESS REALITY links and drop it on a TLS host
    override.
    
    ---------
    
    Co-authored-by: libmur-dev <333915961+libmur-dev@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • chore(deps): update project dependencies
    Refresh Go, frontend, and documentation dependencies, including MSW 3 and pnpm 12.8.1. Update the MSW test setup to use the renamed `onUnhandledFrame` option.
  • docs(architecture): fix table padding flagged by oxfmt
    The NodePendingReset row added in 4210a50c had one extra space of padding,
    failing the Docs CI format check.
  • fix(inbounds): keep the stored client list and enable on inbound save
    Invariant: saving an inbound's configuration never changes which clients it
    holds nor whether it is enabled; both have their own endpoints. The edit
    modal posts back the clients and the enable flag it loaded when it opened.
    A client added meanwhile (another admin, the bot, the API, LDAP) was
    detached and its stats deleted; a client deleted meanwhile came back with
    its credentials, restoring access that had been revoked; an inbound
    switched off meanwhile was switched back on.
    
    For every save but a master's node-sync push, UpdateInbound now takes the
    client list and enable from the row it re-reads inside the writer; this
    replaces the lifecycle-only carry from the previous commit. Client
    validation (renewal schedule, Hysteria auth, TUIC credentials) moves after
    that swap so it judges the clients actually saved: a protocol switch keeps
    the stored clients, and #6268's refusal must apply to them.
    
    The edit form no longer loads or sends clients, so neither the JSON editor
    nor validation sees a copy the server ignores, and the enable switch shows
    only when adding; the list toggle (/setEnable) covers existing inbounds.
    
    Tests that added or re-keyed clients through a panel inbound save pinned
    the old rule; they now drive the master-push path, where payload clients
    still apply.
  • fix(traffic): make a client reset reach every counter enforcing its quota
    Invariant: a client traffic reset zeroes every counter that enforces the
    client's quota - the master's, each hosting node's, and the local MTProto
    sidecar's. A node cuts a client on its own local counters, and the master
    adopts that verdict when both judged the same limits (#4917).
    
    Node counters: ResetClientTraffic tried the node once and dropped a
    failure ("nothing replays a reset"); BulkResetTraffic,
    ResetAllClientTraffics and ClientService.ResetAllTraffics never told the
    node at all. The node kept its pre-reset usage, switched the client off
    again on its next tick, and the master latched that - a client shown at
    zero usage stayed disabled.
    
    Every reset path now queues a node_pending_resets row per hosting node in
    its own transaction. It is delivered right after commit (per-client
    endpoint up to the push threshold, bulkResetTraffic above) and replayed by
    the node sync ahead of its snapshot, and dropped only once the node
    accepted it. While one is owed, the merge takes only that client's usage
    from the node, not its enable or limits. Deliveries to a node are
    serialized so a reset is not sent twice.
    
    Sidecar quota: BulkResetTraffic, ClientService.ResetAllTraffics and
    auto-renew zeroed the panel counters but not mtg's own quota counter, so
    the sidecar kept refusing a renewed or reset MTProto client. They now
    reset it too, scoped to the affected clients.
  • fix(inbounds): keep stored client lifecycle and counters on inbound save
    Invariant: saving an inbound's configuration never changes a client's
    enable, expiry, quota or renewal state, nor the inbound's own traffic
    counters. The inbound modal posts back the whole settings.clients list it
    loaded when it opened, and UpdateInbound stored it, synced it into the
    client records and wrote it into client_traffics. Any client renewed,
    depleted or reset while the modal was open was reverted - a renewed client
    came back disabled with its old expiry. The row itself was read before the
    serialized tx and saved whole, so traffic the poll added in between was
    rolled back and a depleted inbound could be re-enabled.
    
    UpdateInbound now re-reads the row inside the writer and, for clients the
    inbound already holds, keeps enable, expiryTime, totalGB, reset, resetDay,
    resetWeekday and resetMax from it; those change through the client
    endpoints. A master's node-sync push stays authoritative. Existing clients'
    lifecycle fields are no longer editable through the inbound JSON editor or
    /inbounds/update, which the API docs now state.
  • fix(wireguard): reject allowedIPs that overlap another client's range
    xray's WireGuard inbound credits a packet to the first peer whose allowedIPs
    contain its source address, and routes replies by the same table. The panel
    only rejected an allowedIPs entry that was string-equal to another client's,
    so a pre-assigned address typed in interface notation (10.10.2.9/24, as other
    WireGuard tools export it) was accepted and claimed the whole /24: other
    clients' traffic and online IPs were credited to that one email, and replies
    went to a peer with no endpoint ("no known endpoint for peer").
    
    The collision check now compares masked ranges on every path that uses it:
    add, edit, the cross-inbound recheck inside the write transaction, and
    AmneziaWG. Auto-allocation skips any address inside a prefix another client
    holds. A /0 default route still claims nothing, as before, because legacy
    migrated peers carry one. Clients already saved with overlapping ranges keep
    working as they do today until edited. The API docs describing the error are
    updated, including the stale claim that cross-inbound duplicates are accepted.
    
    Closes #6623
  • feat(panel): let a sponsor slot start at a scheduled time
    sponsors.json only had an end date, so a booked placement had to be
    added to the file on the day it started. An optional `from` now hides
    a sponsor (and its logo) until that instant; entries without it show
    immediately as before.
  • fix(nodetoken): stop refusing every node-token key file on Windows
    FileKeySource rejected any key file whose mode had group or other bits,
    but Windows has no such bits: Stat reports every writable file as 0666.
    On the Windows builds release.yml ships, the key file therefore never
    loaded, not even one written 0600, and only XUI_NODE_TOKEN_KEY could
    supply a key. The mode check now applies off Windows only, the stance
    the DB permission tests already take; there the file's NTFS ACL guards
    it, and env-vars.mdx says so in all four locales.
    
    The load test is split so the half that must hold everywhere, an
    owner-only file loading, also runs on Windows, and the rejection half
    asserts the exact error instead of any error.
  • feat(tgbot): access levels and /start account binding (#6518)
    * feat(tgbot): gate the bot behind three user levels
    
    Every Telegram account that found the bot could run /help, /status and
    /usage, and tap any client button it could forge: nothing separated an
    account no admin had bound from a customer.
    
    Each update now resolves to stranger, client or admin, and commands are
    allowlisted per level so a command added later stays admin-only until it
    is listed. A stranger may run /start and /id only, and /start answers with
    the ChatID an admin needs to bind it; a stranger's callbacks are answered
    and dropped. Client detection reads the same tgId lookup as
    clientOwnedByTgUser, so the level gate and the ownership check agree.
    
    The bot also ignores everything outside private chats: authorization keys
    on the sender while wizard state keys on the chat, and the two are the
    same identity only in a private chat.
    
    * feat(tgbot): bind Telegram accounts through /start deep links
    
    Linking a customer meant the customer sending /id and an admin copying
    the ChatID into the client by hand, which does not scale past a few
    customers and is easy to get wrong.
    
    The admin client card now offers an invite link, t.me/<bot>?start=<subId>,
    and the first account to open it is bound through the existing
    SetClientTelegramUserID. A subId already grants the subscription, so
    binding gives the holder nothing the token did not. A subscription that
    spans several clients binds all of them, and is refused if any part
    belongs to another account; re-opening your own link is idempotent.
    Unknown and already-claimed tokens share one reply, so the link cannot
    be used to probe for valid subIds.
    
    * fix(tgbot): harden invite claims after review
    
    Review of the access-level and binding change found five problems:
    
    - Concurrent claims of one link all read the client as unbound, all bound
      and all were told so, while only the last write held. Resolving and
      binding now share one lock, and a bind that fails part-way through a
      multi-client subscription undoes the bindings it already made.
    - A subId has no minimum strength and the bot needs only its public
      username, so /start was an unthrottled guessing oracle. Non-admin claim
      attempts are capped at five per account per hour, the first refused one
      notifies the admins, and the Subscription ID field now says it doubles
      as the bot invite code.
    - levelOf expanded every inbound's client JSON on every non-admin update.
      It now reads the indexed tg_id column of the clients table.
    - A button tapped in a group chat was dropped unanswered and kept
      spinning, with nothing logged. It is answered now, and each ignored chat
      is logged once.
    - The subId was pasted raw into the t.me link, so '#' or '&' truncated it
      and Telegram rejects anything outside A-Za-z0-9_-. The payload is now
      base64url, and a subId too long for the 64-character limit is refused.
    
    * fix(tgbot): answer group chats again and make the claim race test bite
    
    ignoredChat dropped every non-private chat because wizard state was
    keyed by chat while authorization keyed on the sender. #6604 on main
    re-keyed that state by (chat, user) so admins can drive the bot from a
    group, so after the merge the drop only took the whole bot away from
    those admins, report keyboards sent to a group included. The level gate
    already keys on the sender, so group chats need no special case.
    
    TestConcurrentClaimsBindOnlyOneAccount passed with inviteClaimMu
    removed: the first claimant took the pool's idle connection and bound
    before the rest had opened theirs, so no two ever raced. It now holds
    the inbound write the binds need until every claimant has resolved,
    and fails without the lock ("6 accounts told they bound").
    
    TestCommandAllowed restated the commandsByLevel map; TestGateCommand
    drives the same allowlist through gateCommand. TestIgnoredChat goes
    with the code it pinned.
    
    * docs(tgbot): document access levels and invite links
    
    The command table still said /help and /status answer anyone. An
    account no admin has linked now reaches only /start and /id, and a
    customer is linked through the client card's Invite Link, whose token
    is the Subscription ID. Updated in en, fa, ru and zh.
    
    ---------
    
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(inbound): excludeFromSub hides links without disabling (#6463)
    * feat(inbound): excludeFromSub hides links without disabling
    
    Add a per-inbound flag that omits subscription output while keeping the
    inbound enabled for Xray, auth, and traffic accounting. Fixes #6435.
    
    * fix(inbound): excludeFromSub review follow-ups
    
    gofumpt model.go, sync docs OpenAPI, keep excludeFromSub master-authored
    on node mirror, and exercise the legacy add-column migration path in tests.
    
    * fix(sub): keep excluded inbounds' clients in the usage header
    
    The excludeFromSub filter sat in getInboundsBySubId's SQL, so an excluded
    inbound's clients never reached seenEmails in the raw, Clash or JSON
    renderer. A client that lives only on a hidden inbound (one client per
    inbound sharing a subId) dropped out of the Subscription-Userinfo usage,
    quota and expiry and out of the info-node state, while the inbound kept
    serving it and counting its traffic.
    
    The query returns every enabled inbound again; each renderer skips an
    excluded inbound's links but still counts its clients, the same rule the
    Clash renderer already applies to external links it cannot express.
    
    ---------
    
    Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(clients): preserve traffic counters in portable export/import (#6469)
    * feat(clients): preserve traffic counters in portable export/import
    
    ExportAll now attaches client_traffics up/down (plus resetCount and
    last-seen fields) on each portable payload, and ImportClients restores
    them only for newly created emails so skipped/existing clients keep
    their live counters. Fixes #5858.
    
    * fix(clients): restore imported traffic only onto rows the import created
    
    Review of the portable-traffic export/import (#5858) found four defects:
    
    - An orphan's restored row was hand-built, dropping reset_weekday and
      forcing enable=true; a row kept by a keepTraffic delete kept the old
      client's limits. depletedClientsClause then matched a weekly-renewing
      over-quota orphan and DelDepleted deleted it. Orphan rows now go
      through AddClientStat, whose upsert refreshes config and keeps counters,
      so the unused traffic.total field is dropped from the export.
    - Created clients were inferred from Skipped emails, so a duplicate email
      in the file left the created copy with zero counters. bulkCreate now
      reports which payloads inserted a record, and only those are restored.
    - Each client took its own serialized-writer commit: 2000 clients spent
      3.66s instead of 0.52s. Counters now apply in batched transactions
      (0.51s).
    - importClients discarded needRestart when the late restore step failed
      after clients were committed; it now flags and notifies first, as
      create already does.
    
    The /clients/export and /clients/import API docs now describe traffic.
    
    * fix(groups): keep imported traffic out of group totals
    
    Group totals keep a deleted client's usage (#5675), and the portable
    import restores that same usage onto the re-created client. Export,
    delete, re-import therefore counted it twice in ListGroups, and a fresh
    panel showed the migrated usage as consumption of its groups.
    
    Restored counters are usage from before the import, so the import now
    shifts each group's baseline up by what it restored, in the same
    transaction. A group total no longer moves at import time; only traffic
    consumed afterwards counts. The baseline shift reuses the #5675 helper,
    now signed.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • chore(ci): stop release and CodeQL runs on PRs, drop deploy smoke tests
    The release matrix (7 Linux cross-builds + a CGO Windows build) ran on every
    PR and on every branch push, so a PR from a repo branch built everything
    twice. Release binaries now build only on main (dev channel) and version
    tags; any other branch can still be built via workflow_dispatch.
    
    CodeQL keeps its push-to-main and weekly scans but no longer runs per PR.
    
    The deploy smoke workflow fired on every Release completion only to skip
    its jobs; deploy/test/smoke-noninteractive.sh stays for manual runs.
  • feat(sub): add Incy app-management parameters (#6650)
    * feat(sub): add Incy app-management parameters
    
    The panel already pushes a set of Happ headers, but INCY documents its own
    lowercase header names and its own value domains, so a Happ-shaped payload gets
    ignored by the client (per-app mode is bypass|proxy, not on|bypass, and
    per-app-proxy-enable has no Happ counterpart at all). Add a sibling Incy path
    that emits exactly the documented headers.
    
    Covered, per https://docs.incy.cc/en/app-management/:
    - profile-description, sort-order, support-email, announce-url, premium-url
    - banner text/button/URL and the two hex colours
    - hide-url, hide-check, no-limit-enabled
    - per-app split tunnelling (enable/mode/list)
    - TCP fragmentation (enable/length/interval/packets)
    - UDP noise packets (enable/type/packet/delay)
    - DoH pre-resolution (enable/domain/IP)
    
    Each string setting is tri-state: an empty value omits the header, so an
    untouched panel never overrides the subscriber's own choice in the app. Values
    are validated against the documented domains and dropped when they do not
    match, and non-ASCII text is base64-wrapped the way the docs require for
    Cyrillic. INCY identifies itself as INCY/<version>/<platform>, which gates the
    headers behind the same auto-detect switch the Happ path uses.
    
    Headers the panel already emits for every client (Profile-Title, Support-Url,
    Profile-Web-Page-Url, Announce, Profile-Update-Interval, Subscription-Userinfo)
    and Incy's routing line are left as they are.
    
    The Premium API (theme, defaultPingProtocol, fallbackHosts, ...) is a separate
    encrypted endpoint and stays out of scope here.
    
    * fix(sub): keep Incy per-app list entries separate on the wire
    
    The Incy settings textarea takes one package per line, as Incy documents for
    per-app-proxy-list, but the header path ran the value through
    sanitizeHeaderValue, which deletes CR/LF. "com.google.chrome\norg.telegram.messenger"
    reached the client as the single bogus package
    "com.google.chromeorg.telegram.messenger", so per-app split tunnelling silently
    matched no app. Join comma- or line-separated entries as CSV instead.
    
    Also drop three tests that could not fail: TestIncyExcludesHappOnlyHeaders
    (ApplyIncyHeaders has no path that emits Happ headers, and the non-Happ UA
    gate is already pinned by TestApplyHappHeaders_Gating) and two UI tests that
    only asserted updateSetting received the key the JSX passes it.
    
    ---------
    
    Co-authored-by: DIMFLIX <dimflix@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): make external subscription fetch User-Agent configurable (#6613)
    * feat(sub): make external subscription fetch User-Agent configurable
    
    Some providers reject fetches that do not send a known client User-Agent.
    Expose externalSubUserAgent as a panel setting (default v2rayNG/1.8.5)
    and use it when fetching client external subscription URLs.
    
    Fixes #6383
    
    * ci: retrigger frontend after npm registry maintenance
    
    The frontend job failed solely on `npm audit` while registry.npmjs.org
    returned 503 (Service Under Maintenance). Lint, typecheck, vitest, vite
    build, and storybook all passed. Local `npm audit --omit=dev
    --audit-level=high` now reports 0 vulnerabilities.
    
    * fix(sub): fall back to the default UA when the DB is not initialised
    
    externalSubUserAgent read the setting through SettingService.getSetting,
    which calls Model() on database.GetDB() and panics on a nil *gorm.DB.
    The fetch path's other DB read, service.ExternalSubscriptionHwid, already
    treats a nil DB as unreachable and sends no header; the new UA lookup
    did not, so any fetch before InitDB panicked instead of sending the
    historical v2rayNG/1.8.5.
    
    Production initialises the DB before the sub server starts, but the
    internal/sub fetch tests run without one: under make test-go's
    -shuffle=on, whenever one of them ran before the first InitDB test the
    panic aborted the whole package. Reproduced deterministically with
    go test -run '^TestDoFetchSubscriptionLinks_RejectsOversizedBody$'.
    
    ---------
    
    Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
    Co-authored-by: MHSanaei <ho3ein.sanaei@gmail.com>
  • feat(clients): add calendar weekly renewal and schedule previews (#6524)
    * feat(clients): add calendar weekly renewal and schedule previews
    
    Expose fixed-day, calendar-weekly, calendar-monthly, and disabled renewal
    through one shared selector in individual and bulk client forms. Store the
    weekly weekday separately (Monday 1 through Sunday 7) and use panel-local
    calendar dates rather than a fixed 168-hour duration. Resolve skipped or
    repeated midnights to the first valid instant of the selected date, and skip
    an entirely nonexistent calendar date rather than changing the weekday.
    
    Reuse the existing renewal writer and share its boundary alignment and
    per-period catch-up calculation with an authenticated, read-only preview.
    Keep monthly precedence for legacy records, fixed-day interval semantics,
    maximum renewal allowances, first-use durations, and operator-disabled
    settings unchanged. Selecting a mode does not rewrite an existing cutoff;
    an unset calendar cutoff requires an explicit action to choose the first.
    The last-valid-second preview uses the stored exclusive expiry, even when
    the billing calculation aligns a legacy last-second cutoff up to midnight.
    
    Carry weekly schedules through client persistence, paging, enable toggles,
    inbound settings, and node traffic reconciliation. Migrate missing or nullable
    weekday columns to disabled by default without altering existing limits, and
    include the new isolated-schema PostgreSQL regression in the live CI gate.
    
    Regenerate API contracts and reference documentation, add lifecycle and form
    regressions, and document timezone, quota-reset, and upgrade considerations.
    All participating nodes must be upgraded before weekly mode is enabled;
    older binaries ignore the new field. Independent periodic traffic resets and
    the optional month-end subscription-header display are not changed.
    
    * fix(clients): validate renewal schedules across inbound write paths
    
    Reject conflicting weekly/interval/monthly schedules and out-of-range
    weekdays on inbound creation and edits, legacy one-client apply paths,
    record/link synchronization, and traffic metadata writes. Validate imported
    traffic snapshots as well, before any inbound or client is persisted, so
    an inbound API cannot create a client that the clients page cannot toggle.
    
    Merge a weekly-related schedule as one timestamp-selected tuple rather
    than filling its zero fields from another renewal mode. Preserve empty
    migration snapshots and the existing non-weekly monthly/interval merge
    semantics. Renewal caps, counters, credentials, and deadlines are unchanged.
    
    Add regressions for nine write paths, unchanged records and runtime calls
    after rejection, valid inbound clients remaining editable, and duplicate
    record merges between individually valid renewal modes.
    
    * docs(clients): clarify depleted-client deletion risks on downgrade
    
    Explain in English and Chinese that older versions not only stop weekly
    renewal: their depleted-client cleanup can delete a weekly-only client once
    its expiry or quota is exhausted. This is conditional on cleanup, not an
    automatic deletion caused by downgrade itself.
    
    Recommend backing up and converting weekly schedules to a mode supported
    by every participating version before rollback, and avoiding cleanup while
    mixed versions or unconverted clients remain. Merely disabling weekly
    renewal does not restore the old binary's missing purge protection.
    
    * fix(clients): bound weekly renewal date searches
    
    Limit the search for a valid weekly calendar date to eight candidates so
    an unusual timezone cannot monopolize the single traffic writer. Exhaustion
    returns the original instant, allowing the existing catch-up forward-progress
    guard to stop without advancing expiry, consuming an allowance, resetting
    traffic, or falling back to a fixed-duration schedule that can drift.
    
    Reject a non-future calendar suggestion in the read-only preview instead of
    offering an immediately expired initial cutoff. Also report failed weekly
    catch-up as a search error when allowances remain, not as cap exhaustion.
    Existing preview errors use the form's current warning; no API schema or
    locale changes are needed.
    
    Exercise exhaustion with a synthetic valid TZif containing twelve skipped
    Sundays. This fault-injection case was red without the bound; it is not a
    claim that a production IANA timezone was observed hanging. Keep the Havana
    and Apia regressions for real skipped/repeated midnights and absent dates.
    
    * fix(tests): isolate weekly renewal preview timezone
    
    Stop the weekly search regression from replacing process-global time.Local.
    CI caught that assignment and its cleanup racing with background timer reads
    through time.Now, even though the top-level tests do not use t.Parallel.
    
    Pass the timezone and current instant into the unchanged preview calculation.
    The public service still validates the request and resolves the panel timezone;
    API responses, renewal accounting, and persisted client data are unchanged.
    
    Use fixed dates for both suggestion and catch-up exhaustion, removing the
    test's dependency on today's date and its unnecessary database setup. Keep a
    bounded-lifetime background clock reader to expose future global-timezone
    mutations under the existing race gate rather than disabling that check.
    
    * ci: retrigger PR checks
    
    Create an empty commit to request a fresh pull-request CI run after release dependency downloads failed with network errors.
    
    No source, dependency, or workflow changes are included. Retry the existing checks without bypassing them.
    
    * ci: retry PR checks and record deferred download hardening
    
    Request another CI run after the amd64 release job compiled successfully but failed during dependency fetching with exit code 4 (network failure).
    
    Record possible follow-up improvements for the Linux release fetch helper:
    - Print each download URL and destination, and preserve error details.
    - Reuse the existing curl configuration with up to five retries; add connection and per-attempt timeouts and a bounded retry window.
    - Download to a temporary file and promote it to the final filename only after a successful, non-empty transfer. Keep the job failing if downloads ultimately fail.
    - Validate successful downloads, recovery after a temporary failure, and correct failure after persistent errors before shipping such a change.
    
    These improvements are intentionally deferred, not implemented or tested by this commit. This commit is empty: renewal logic, dependencies, workflow configuration, check requirements, and TLS verification remain unchanged.
    
    ---------
    
    Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
  • fix(sub): make Happ require auth on its local SOCKS/HTTP proxy (#6628)
    Happ ships its local SOCKS5 (127.0.0.1:10808) and HTTP inbounds with
    authorization disabled by default. Any app on the same device can then
    connect to that proxy, bypassing Android's per-app VPN routing, and learn
    the VPN server address - the leak publicly described in March-April 2026
    for Happ, v2rayNG and other VLESS clients. Happ fixed its Xray API
    exposure, but the unauthenticated local proxy remained.
    
    Happ exposes a standard subscription header for this (no Provider ID
    required): socks-auth-mode / http-auth-mode = auto|manual|from-json|
    disable. A new subscription setting, subHappLocalProxyAuth (default
    "auto"), sends both headers to Happ clients. Like every other Happ header
    it is emitted only when Happ auto-detect is enabled and the User-Agent is
    Happ, so panels that never opted into the Happ integration see no change.
    An empty value sends nothing and keeps the client's own setting.
    
    Verified on Happ Android 4.4.1 (Xray 26.7.28): a subscription carrying
    socks-auth-mode manual + a test user/password switched the client's
    Inbounds screen to Manual with those credentials on "refresh subscription",
    and "auto" switched it to Auto with generated credentials.
    
    Co-authored-by: Kirill Rudenko <rudenko@npp-energy.ru>
    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • fix(amneziawg): bound S1-S3 by the receive buffer, reject overlapping H (#6642)
    * fix(amneziawg): bound S1-S3 by the receive buffer, reject overlapping H
    
    The native AmneziaWG validator, both Zod schemas, both forms and the docs now
    follow the rules amneziawg-go actually enforces.
    
    S1-S3. A padded handshake message is 148+S1, 92+S2 or 64+S3 bytes
    (device/send.go). The peer reads each datagram into a [MaxMessageSize]byte
    buffer, where MaxMessageSize = MaxSegmentSize (device/pools.go,
    constants.go). MaxSegmentSize is 65535 on Linux/Android, 2016 on Windows and
    1700 on iOS (device/queueconstants_*.go). The limits are therefore
    S1 <= 1552, S2 <= 1608 and S3 <= 1636. Before, S1/S2 allowed 65535, which
    iOS peers silently drop, and S3 was capped at 64, a number inherited from the
    coinman-dev/3ax-ui port in #6105 with no stated reason. That cap blocked real
    configs such as Amnezia Premium's S3=1045. RandomTrailers only tops a packet
    up to 500 bytes (DefaultUdpWindow), so it never pushes a message past these
    limits.
    
    H1-H4. amneziawg-go refuses the whole device when the header ranges overlap
    ("headers must not overlap", device/uapi.go mergeWithDevice), and so does the
    kernel module (src/netlink.c). The panel did not check this, so an inbound
    with overlapping ranges saved and then failed to apply. A blank H is never
    sent, so the engine keeps its default, WireGuard's own type 1-4; the check
    treats blank fields that way. The docs said 1-4 "must not be used". They are
    valid and are the engine default, only unobfuscated without a
    HeaderProtectionKey. The docs also said amneziawg-go rejects S1+56 == S2. It
    does not (IpcSet accepts it). The panel keeps that rule as a fingerprint
    guard, and the docs now say so.
    
    Tests: the new params_test cases and the Zod bounds fail on the old code.
    TestValidatedObfuscationAlwaysApplies runs every accepted set through a real
    amneziawg-go IpcSet and now covers overlap, blank-H defaults, H=1-4, the
    exact S bounds and the full Amnezia Premium set. Before this fix it failed
    with "headers must not overlap".
    
    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
    
    * fix(amneziawg): bound only inbound padding by the iOS receive buffer
    
    The 1700-byte iOS buffer limits what an inbound's clients can receive,
    but ValidateObfuscation also runs for outbounds, and the Xray template
    save re-validates every AmneziaWG outbound. An outbound whose remote
    server uses S1 above 1552 would have blocked every Xray settings save,
    though its values come from that server and are received on Linux.
    
    ValidateObfuscation keeps amneziawg-go's uint16 UAPI width for S1-S3;
    ValidateServerObfuscation adds the receive-buffer bounds and is what
    inbounds call. The outbound schema and form follow the same split.
    
    ---------
    
    Co-authored-by: Kirill Rudenko <rudenko@npp-energy.ru>
    Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(panel): add sponsor slots fed from sponsors.sanaei.dev
    Monthly sponsor placements need to change without cutting a panel
    release. Panels now read 3X/sponsors.json from the MHSanaei/sponsors
    repo (GitHub Pages on sponsors.sanaei.dev) and show active sponsors in
    four slots: an overview banner, a rotating sidebar card (max three), the
    login page and a new Sponsors page that also lists open placements.
    
    An entry shows only while enable is not false and until is in the
    future; links must be https and logos are png/webp/jpg by name only.
    The list is cached for an hour and the last good copy survives upstream
    failures; logos are proxied through /sponsors/logo/:name with failures
    cached, so CSP stays 'self' and admin browsers never reach a third
    party. Admins can hide a slot for 24h. Under XUI_DEBUG the panel reads
    a sibling ../sponsors/3X checkout so edits can be previewed before push.
  • chore(deps): update toolchains and dependencies
    Raise the frontend baseline to Node 26/npm 11 and refresh contributor documentation. Update frontend, documentation-site, and Go dependencies with regenerated lockfiles and module checksums.
  • feat(hosts): add a cipher suites override and accept custom suites
    The inbound TLS form offered cipherSuites as a closed single-choice list,
    but xray reads the value as a colon-separated list and accepts any name Go
    knows, so several suites or one missing from the list could not be set.
    Both the inbound and the new host field now use a tag picker that keeps
    the stored value as the colon-joined string xray expects; old single
    values open unchanged.
    
    A host's cipher suites replace the inbound's in the JSON subscription
    stream, and a blank field inherits them. Share links and Clash carry no
    cipher suite parameter, so their output is unchanged.
  • fix(sub): prevent default profile page URL disclosure (#6538)
    * fix(sub): prevent default profile page URL disclosure
    
    Add explicit none, builtin, and custom profile page modes.
    Preserve existing custom URLs and warn before exposing the built-in page.
    Cover mode selection, legacy settings, and subscription response headers.
    
    * fix(subscription): add profile page link options and upgrade notes
  • chore(docs): bump dependencies and adapt to fumadocs-core 16.15.11
    Updates the docs site's dependencies, including the Fumadocs packages,
    Next 16.3.5, React 19.3 and three majors: mermaid 12, vitest 5 and
    pnpm 12. Two code changes follow from the bump:
    
    - fumadocs-core 16.15.11 makes `llms().index()` return a Promise, so
      the llms.txt route now awaits it; tsc rejected the old synchronous
      call
    - lucide-react 1.46 renamed the BookMarked icon to BookBookmark. The
      old name is still exported, but lucideIconsPlugin looks names up in
      lucide's `icons` map, which only has the new one, so the Reference
      section lost its sidebar icon in all four locales. The build only
      printed a warning.
    
    minimumReleaseAgeExclude gains entries for the newly installed
    versions.
    
    Checked with typecheck, lint, vitest (106 tests) and a full build: no
    plugin warnings, and each locale's rendered /docs page contains the
    book-bookmark icon.
  • fix(xray): restart when a diff strands a client's live session (#6550)
    * fix(xray): restart when a diff strands a client's live session
    
    Disabling or deleting a client took it out of the generated config and the
    hot path applied that with AlterInbound/RemoveUser, which only drops the
    credential (vless, vmess, trojan and shadowsocks all keep the established
    session running) -- so the panel showed a disabled client whose connection
    kept passing traffic, and the core offers no API to close one session.
    
    A diff that removes a user without re-adding the same email under the same
    tag is that case: honour the operator's restart-on-client-disable setting and
    let the caller replace the process, which is already how an auto-disabled
    client loses its session. An edit re-adds the email and keeps the hot path.
    
    * chore(i18n): cover manual disable and delete in the restart-setting description
    
    The setting now also decides what happens when a client is disabled or deleted
    by hand, so the description cannot keep naming only the automatic path. All 13
    locales updated in the same commit to keep the wording consistent.
    
    * fix(xray): reach the guard from the manual switch and from every protocol
    
    Round-1 findings on this PR. The guard sat in tryHotApply, but a manual disable
    or delete applies through runtime.Runtime and finishes with needRestart false,
    so none of the three RestartXray schedulers fired and the predicate was never
    reached: the session in #6533 kept flowing. The apply layer now asks for the
    restart the setting promises when the client actually leaves the config, on the
    single-client update and delete paths and on bulk disable, and only for local
    inbounds so a node row cannot make the master restart its own core.
    
    The predicate itself could not fire for shadowsocks or hysteria either, because
    RemovedUsers is only produced for the protocols diffInboundUsers will diff. The
    diff now also compares settings.clients of an inbound present in both configs,
    which is the one shape every account list shares, so those protocols reach the
    guard through the inbound instead of through nothing.
    
    TestManualClientDisableHonoursRestartSetting fails without the apply-layer fix
    ("needRestart = false, want true" with the setting on) and
    TestHotDiffDropsUsersOnProtocolsItCannotDiff fails without the diff fix -- both
    watched red. The two three-line comments this PR added are back inside the cap.
    
    * docs(i18n): stop scoping restartXrayOnClientDisable to auto-disable
    
    The setting now covers a client disabled or deleted by hand as well, so its
    title no longer says "Auto" in all 13 locales, and the docs callouts in en, ru,
    zh and fa describe the same behaviour instead of the auto-only one.
  • feat(sub): add opt-in month-end expiry presentation (#6517)
    Offer monthly calendar subscriptions an explicit last-valid-second display
    without moving their real billing boundary or spending renewal allowances.
    
    Keep the option off by default and limit conversion to a shared fixed
    day-1 midnight cutoff at an actual month transition in the panel timezone.
    Use the authoritative client calendar mode when aggregating node traffic,
    and share the header formatter across raw, JSON, and Clash exports.
    
    Expose the setting in the existing settings API/UI, regenerate its schemas,
    and document that clients may report expiry one second early or format the
    date differently in another timezone. Add HTTP, settings, and DST coverage.
    Stored deadlines, access enforcement, info/remark expiry values, and renewal
    accounting remain unchanged.
    
    Refs: #6516
    
    Co-authored-by: JacktheRanger <219502738+JacktheRanger@users.noreply.github.com>
  • docs: add Discord bot to READMEs, architecture, operations guides, and locales (#6513)
    * docs: add Discord bot to READMEs, architecture, operations guides, and locales
    
    * docs: address review feedback on Discord bot formatting, backup commands, and architecture
    
    * docs(discord): fix Persian typo and literal arrows on fa/zh bot pages
    
    Senior review of #6513, two LOW findings in the two new pages:
    
    - fa/operations/discord-bot.mdx:30 spelled "developers" with Cyrillic
      "де" in place of Persian "ده", rendering a mixed-script word.
    - Both pages copied `$\rightarrow$` from the en page. The docs site has
      no math plugin (nothing in source.config.ts, no remark-math
      installed), so the built HTML shows the literal string
      "$\rightarrow$" in every menu path. Replaced with a Unicode arrow on
      fa and zh; en and ru have carried the same since #6486 and are left
      for a separate change.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • docs: add TUIC v5 to READMEs, guides, and protocol references (#6511)
    * docs: add TUIC v5 to READMEs, guides, and protocol references
    
    * docs: address review feedback on TUIC architecture, external links, and i18n parity
    
    * docs(tuic): drop the Xray-routing claim and qualify Limit IP for TUIC
    
    The README feature bullet in all seven locales credited the TUIC sidecar
    with "seamless Xray routing". A TUIC inbound never enters the Xray config
    (internal/web/service/xray.go skips model.TUIC) and the generated
    tuic-server config carries no forwarding target, so decrypted TUIC
    traffic egresses from the sidecar directly and Xray routing rules never
    see it; docs/architecture.md in this same branch already says so. An
    operator reading the bullet would expect geo blocking and outbound
    selection to cover TUIC clients.
    
    The client field table marks Total (GB) as inbound-level for TUIC but
    left Limit IP at "all". The IP-limit job's only data source is Xray's
    online-stats API (internal/web/job/check_client_ip_job.go), which TUIC
    clients never reach, so a Limit IP set on a TUIC client is silently
    unenforced. Qualify that row the same way in en, fa, ru and zh.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(settings): add setting for Reality scan candidates (#6471)
    * feat(settings): allow customizing Reality scan candidate list
    
    Persist a realityScanCandidates panel setting (defaulting to the previous
    hardcoded list), expose it in General Settings with i18n, and have the
    Find Targets scanner use it when the search box is empty.
    
    Fixes #5847
    
    * style(frontend): oxfmt realityScanCandidates in setting.ts
    
    * Fix locale JSON syntax
    
    This change removes the malformed duplicate key and missing comma in the Android per-app proxy translations across the bundled locale files. The JSON now parses correctly while preserving the translated labels for each language.
    
    * docs(i18n): update Happ translations
    
    Localize the remaining Happ subscription settings strings across the translation files and refine the English copy. This aligns the labels and descriptions with the current Happ behavior for notifications, TUN options, HWID enforcement, routing presets, and per-app proxy settings.
    
    * refactor(reality): drop test-only scaffolding from the candidate setting
    
    TestDefaultRealityScanCandidatesCSV compared the CSV against its own
    initializer and a defaultValueMap lookup, and
    TestRealityScanCandidateTokensFallsBackWithoutDB drove a no-database
    state no production caller reaches (the only caller is the
    scanRealityTargets handler, served after InitDB). The
    s != nil && GetDB() != nil guard existed only for that second test.
    None of them could fail except in lockstep with the code they restate.
    
    * docs(api): describe the setting-driven scanRealityTargets fallback
    
    An empty targets value now probes the realityScanCandidates setting,
    but the endpoint summary, parameter description and handler comment
    still promised the built-in seed list, so API consumers were told the
    wrong target set. Regenerated openapi.json and synced the docs copy,
    which also lacked the new AllSetting field in the settings reference.
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(discord): add Discord notification bot service (#6486)
    * feat(discord): add Discord notification bot service, settings UI, and event subscriber
    - internal/web/service/discord: implement lightweight Discord REST API v10 client and EventBus subscriber
    - internal/web/service/setting: add discordBotEnable, discordBotToken, discordChannelId, discordEnabledEvents, discordCpu, discordMemory settings and secret protection
    - internal/web/controller: register POST /panel/api/setting/testDiscord endpoint
    - frontend: add Discord settings tab, notifications configuration, sidebar navigation, and command palette integration
    - translation: add localization keys across all 13 locales
    - tests: add comprehensive unit tests with httptest server and verify route/i18n contracts
    
    * fix(discord): address PR review findings on concurrency, linting, i18n, and stories
    
    - subscriber: eliminate unbounded goroutines, sending inline per EventBus contract
    - discord: accept context.Context in SendMessage, SendEmbed, SendTest with http.NewRequestWithContext
    - format: apply gofumpt to controller and entity struct alignments
    - i18n: localize testDiscord controller responses across all 13 locales
    - storybook: add DiscordNotifications.stories.tsx component story
    
    * docs: add Discord bot setup and operations guide
    
    - add docs/content/docs/en/operations/discord-bot.mdx with setup steps, event indicators, settings, and troubleshooting
    - add docs/content/docs/ru/operations/discord-bot.mdx with localized instructions
    - update operations/meta.json across en, ru, zh, fa
    - link Discord bot from panel configuration overview
    
    * feat(discord): add discordLang, discordRunTime, discordBotBackup settings and update settings UI
    
    - internal/web/entity: add DiscordRunTime, DiscordBotBackup, DiscordLang fields to AllSetting
    - internal/web/service/setting: add defaultValueMap entries, getters, and setters
    - frontend: update AllSetting schema, model defaults, and generate OpenAPI / Zod contracts
    - frontend: extract shared NotifyTimeField component and update DiscordTab with General and Notifications tabs
    - translation: add localization keys across all 13 locales
    
    * feat(discord): implement scheduled status reports and database backup attachments
    
    - internal/web/service/discord: add SendMessageWithFiles supporting multipart uploads
    - internal/web/service/discord: implement BuildReport and SendReport generating rich status embeds
    - internal/web/service/discord: attach database backup (and config.json) when discordBotBackup is enabled
    - internal/web/job: implement DiscordNotifyJob scheduled via robfig/cron
    - internal/web/locale: add LocalizerFor and I18nForLang helpers
    - internal/web/controller: trigger reloadDiscordFunc to dynamically reschedule cron upon setting changes
    - internal/web/web: register and reschedule DiscordNotifyJob
    - tests: comprehensive unit tests for multipart uploads, status reporting, and job execution
    
    * feat(discord): add interactive bot commands via Gateway WebSocket and update documentation
    
    - internal/web/service/discord/gateway: connect to Discord Gateway v10 via WebSocket (gorilla/websocket)
    - internal/web/service/discord/gateway: handle heartbeat loop, reconnection, and command dispatch
    - commands: implement !status, !report, !backup, !usage <email>, !inbounds, !restart, !help (with ! and / prefixes)
    - internal/web/web: start/stop Gateway client with server and reload dynamically on setting updates
    - docs: update operations guide (en, ru) with scheduled reports, backups, commands, and privileged intents
    - tests: add end-to-end WebSocket Gateway test verifying command handling
    
    * style(discord): fix goimports formatting and add 3x-ui to gitignore
    
    * fix(discord): stop gateway panics, reconnect storms and proxy bypass
    
    The Gateway client wrote to its websocket from both the heartbeat ticker
    and the read loop answering server-requested op 1 heartbeats. gorilla
    panics on concurrent writes and neither goroutine recovers, so a colliding
    heartbeat took the whole panel process down; writes now share writeMu.
    
    It also reconnected every 5s forever after close codes Discord marks
    non-reconnectable (4004 bad token, 4010-4014, including 4014 when Message
    Content Intent is off), re-identifying and logging a warning each time.
    The loop now stops on those codes; the docs say to restart the panel.
    
    The gateway dialed with websocket.DefaultDialer, bypassing the panel
    egress proxy the REST client already uses, so where Discord is filtered
    notifications arrived but commands never connected.
    
    * fix(discord): deliver the scheduled report when the backup upload fails
    
    SendReport posted the report embed and the x-ui.db/config.json attachments
    in one multipart request. Once the database outgrows Discord's upload cap
    (20 MiB by default) the request is rejected and the report embed is lost
    with it on every run, leaving only a log warning. Send the embed first and
    the attachments as a second message.
    
    * chore(discord): delete tests that pass whether or not the code works
    
    TestDiscordNotifyJob_NilServiceNoPanic and TestHandleEvent_NilDiscordService
    feed a nil DiscordService that web.go never passes, and
    TestDiscordNotifyJob_DisabledNoPanic passes with or without the enable
    guard because Xray is not running under test.
    
    * fix(discord): require admin user IDs for bot commands and honor discordLang
    
    Any member who could post in the configured channel could run !backup
    (the whole x-ui.db and config.json, even with discordBotBackup off),
    !restart and !usage. Commands now run only for the Discord user IDs in
    the new discordAdminIds setting; an empty list turns commands off.
    
    discordLang was saved and offered in the UI, but nothing read it, so
    every embed stayed English. The test message, alerts, the scheduled
    report and command replies now render through I18nForLang in the chosen
    language, with a discord section in all 13 locales. InitLocalizer takes
    an fs.FS so tests load the real translation files.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(happ): generate Crypt5 subscription links locally (#6494)
    * feat(clients): add stateless Happ link generator
    
    Generate Happ provider links from the current effective subscription source without caching results. Reject unsafe provider responses and redact failure diagnostics.
    
    * fix(clients): reject duplicate Happ provider fields
    
    Parse Happ provider objects token by token so duplicate supported keys cannot be silently overwritten by encoding/json.
    
    * feat(clients): expose on-demand Happ link API
    
    Expose a no-store client endpoint backed by the Happ link generator and keep its generated OpenAPI contract synchronized.
    
    * fix(openapi): exclude service interfaces from generated types
    
    Keep dependency-injection interfaces out of the frontend API surface while preserving allowed response schemas.
    
    * feat(clients): add stateless Happ QR presentation
    
    Generate Happ links only for the active modal scope and retire late responses so Standard remains immediately available. Add focused component coverage and localized retry guidance across every locale.
    
    * fix(clients): cover overlapping Happ generations
    
    Prove the cancellation cleanup is required by resolving a retired request while its replacement remains pending. Also wait for Regenerate to leave loading state before exercising the existing action.
    
    * fix(clients): harden Happ link handling
    
    Validate generated responses before rendering and hide actions during unresolved requests. Strengthen route, redirect, timeout, and lint regression coverage with mutation-sensitive tests.
    
    * fix(clients): gate Happ link generation behind operator opt-in
    
    - add a fail-closed happLinkEnable setting
    - enforce the gate before and after provider requests
    - add locked Happ QR state with privacy disclosure and settings link
    - cover backend, frontend, settings, and i18n regressions
    
    * fix(frontend): guard oversized Happ QR codes
    
    Keep valid long crypt5 links copyable while suppressing QR rendering and image actions above the encoder's UTF-8 byte limit. Add localized guidance and boundary coverage.
    
    * fix(clients): log the sanitized transport error for Happ link failures
    
    Every fail() call in HappService.Generate passed a string literal as the
    detail, so the sanitizer written for provider errors only ever saw
    constants, and an operator following the QR modal's "check Logs" hint
    found nothing beyond reason=transport. Transport and body-read errors now
    flow through sanitizeHappDetail, which also redacts cookie/session pairs.
    
    Drop TestHappLinkEnableDefaultsOffWithoutPersistingRow: it pinned a getter
    and its constant default, which the Generate gate test already drives.
    
    * fix(frontend): size the Happ QR cap to level L and keep the QR modal mounted on close
    
    HAPP_QR_MAX_BYTES was the level-M capacity (2331) while QrPanel encodes at
    errorLevel "L", whose version-40 byte-mode capacity is 2953, so valid links
    between 2332 and 2953 bytes lost their QR. The cap now matches the encoder
    and a test renders the real QrPanel at the boundary.
    
    Keying the modal content on `open` remounted it on every close, which cut
    the Modal's exit transition and made the openSubId sync unreachable, so
    `loading` never turned on for the subLinks fetch and a client without a
    subscription link flashed noLinks on reopen. `open` leaves the key and the
    sync block now also resets the Happ state.
    
    * chore(clients): request Happ crypt5 links from api-v3
    
    crypto.happ.su serves api-v2.php and api-v3.php side by side. Probed with
    the same payloads, both take {"url"} over a JSON POST, answer
    {"encrypted_link":"happ://crypt5/..."} of identical length with the same
    crypt5 key marker, and fail the same way: 400 "No url provided.",
    500 "Invalid URL format.", 405 on GET. Happ's own generator page is
    branded "URL Encryption v3", so the panel follows it. The parser and the
    link validator are unchanged.
    
    * feat: add local generation of encrypted Happ links
    
    - Implemented functionality to generate encrypted Happ links locally without network dependency.
    - Added validation for URL length and format to ensure compliance with processing limits.
    - Introduced new error handling for invalid URLs and control characters.
    - Updated translations for various languages to reflect changes in Happ link generation.
    - Created unit tests to validate the encryption process and ensure session keys and nonces are unique.
    
    * fix(frontend): match the tuic memo deps to the non-optional subSettings
    
    The Happ branch reads subSettings non-optionally in ClientQrModalContent
    (happLinkEnable and the WireGuard/AmneziaWG publicHost memos), so React
    Compiler infers subSettings.publicHost. The TUIC memo merged in from main
    still listed subSettings?.publicHost, which fails oxlint's
    preserve-manual-memoization rule and makes the compiler skip optimizing
    the component. make verify stopped at lint-fe on the branch head.
    
    * chore(happ): trim the pinned-key provenance comment to two lines
    
    CLAUDE.md caps a comment block at two lines. The bare URL line repeated
    the repository and file the next line already names, so it is folded
    into that line (review LOW on happ_crypto.go).
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): let the panel set the JSON subscription DNS servers (#6485)
    * feat(sub): let the panel set the JSON subscription DNS servers
    
    A baked routing profile (#6402) carries only the DNS its preset defines, so an
    operator who wants their own resolvers has to override the whole profile or
    patch the subscription behind a proxy.
    
    Add the subJsonDns setting: either a full xray dns block or a bare array of
    servers. It wins over the profile's DNS while leaving the profile's routing
    rules intact, and reaches per-inbound, balancer and info-node documents alike.
    
    The value is validated with xray's own schema (internal/xray/dnsconf): a block
    the client could not load is rejected when the settings are saved and ignored
    with a warning at request time, instead of being baked into every document.
    Both the sub server and the settings API share that validator, so a stored
    value can never be silently dropped.
    
    xray's Build() is deliberately not used for validation: it resolves geosite
    tokens from the geodata files and would reject valid configs whenever those
    are absent from the panel's working directory.
    
    * style(dnsconf): drop the ineffectual initial map assignment
    
    golangci's ineffassign flagged the zero-value map whose value both paths
    overwrite: the object branch now assigns the decoded map directly.
    
    * docs(sub): scope the DNS setting to the documents it rewrites
    
    The Routing header mirrored to Happ/INCY keeps the routing profile's own
    resolvers, so the setting description and the header-source comment now say
    so instead of claiming the profile's DNS is replaced everywhere.
    
    Also trims two comments in the new dnsconf package to the repo's two-line cap.
  • fix(inbounds): allow negative subSortIndex for subscription order (#6465)
    * fix(inbounds): allow negative subSortIndex for subscription order
    
    Preserve explicitly set negative indices so primary inbounds can sort
    ahead of the default without renumbering peers; keep 0/omitted → 1.
    
    * fix(inbounds): gofumpt model.go and trim subSortIndex comments
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • feat(reality): warn when target cert chain is too small for ML-DSA-65 (#6470)
    * feat(reality): warn when target cert chain is too small for ML-DSA-65
    
    Expose peer cert-chain DER size from the REALITY scanner and surface a UI
    warning when ML-DSA-65 is enabled but the chain is under xray-core's 3500-byte
    minimum, so silent fallback failures are easier to catch.
    
    Fixes #5973
    
    * fix(reality): gate scanner ML-DSA tag and sync docs OpenAPI
    
    Only warn on short cert chains in the target scanner when ML-DSA-65 is
    enabled. Copy frontend/public/openapi.json to docs/public/openapi.json
    and fix oxfmt wrapping in the new test.
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • feat(clients): show short HWID fingerprint in admin device list (#6464)
    * feat(clients): show short HWID fingerprint in admin device list
    
    Expose a 12-char prefix of the stored hwid_hash in the admin HWID list API and UI so admins can distinguish devices without querying the database. Full hashes and raw HWIDs remain unexposed.
    
    Fixes #6359
    
    * ci: retrigger release matrix after 386 dependency download flake
    
    ---------
    
    Co-authored-by: mrchatam <mrchatam@users.noreply.github.com>
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • Feature/tuic v5 (#6337)
    * Feat(tuic): Implement native TUIC v5 protocol support via Rust sidecar daemon
    
    - Add internal/tuic package for official tuic-server sidecar lifecycle management, configuration generation, and graceful process control
    - Bridge decrypted TUIC QUIC traffic into loopback Xray SOCKS5 inbounds (63200+id) for traffic accounting, statistics, and routing rules
    - Implement periodic reconciliation job (cadence @every 10s) and immediate runtime synchronization on inbound/client mutations
    - Add TUIC inbound & multi-user client settings (UUID + Password authentication) in Web UI with SNI auto-fill and panel certificate loader
    - Integrate tuic:// subscription links and Clash.Meta (Mihomo) proxy generation for TUIC
    - Update install.sh to automatically download and install official tuic-server release for x86_64, aarch64, and armv7
    - Add full localization for TUIC protocol across all 13 supported languages
    
    * Feat(install): Support custom repository and branch in install and update scripts
    
    * Ci(release): Enable publish-dev for feature branch and workflow dispatch
    
    * Feat(sub): Add TUIC to subscription resolution and client QR config generator
    
    - Add 'tuic' to getInboundsBySubId SQL allowlist to resolve TUIC inbounds in subscriptions and sub links
    - Enhance buildTuicProxy in Clash subscription generator with robust host and credentials resolution
    - Add tuicConfig.ts to generate standalone Clash/Mihomo YAML configuration
    - Add dedicated TUIC Config tab in ClientQrModal with QR code and .yaml download button
    - Add localization keys for TUIC config across all 13 supported languages
    
    * Fix(tuic): Exclude TUIC from native Xray inbounds and strip udp_relay_mode from server config
    
    - Exclude model.TUIC from native Xray inbounds in GetXrayConfig to prevent Xray startup failure
    - Remove udp_relay_mode from tuic-server JSON configuration builder
    - Update install.sh to install tuic-server binary to both xui_folder/bin and /usr/local/bin
    
    * Fix(install): Fallback to dev-latest when releases/latest is not present on fork
    
    * Feat(tuic): Add real-time online status and LastOnline tracking for TUIC clients
    
    - Track client activity by mapping client UUID in tuic-server logs to email
    - Integrate TUIC active clients into XrayTrafficJob to refresh local online clients
    - Bump LastOnline timestamp in database and broadcast live online status over WebSocket
    
    * Feat(tuic): Implement real-time traffic statistics and live speed reporting for TUIC
    
    - Collect precise I/O traffic deltas for tuic-server child processes via /proc/<pid>/io
    - Aggregate and attribute TUIC traffic deltas per client in tuic Manager
    - Integrate TUIC traffic deltas into XrayTrafficJob to update database and broadcast live speed
    
    * Feat(tuic): Finalize TUIC v5 integration with 1:1 traffic counting and orphan process cleanup
    - Use exact 1:1 byte delta accounting from /proc/<pid>/io
    - Add killStrayTuicProcesses to terminate orphan sidecars on panel startup
    - Fully integrate TUIC with subscriptions, live speed meter, and all 13 locales
    
    * Feat(frontend): Polish TUIC UI, support bulk operations, and update translations
    
    - Align TUIC inbound certificate form with standard 3X-UI layout (Set Default Cert, Clear)
    - Remove extra subtitle hint text from TUIC inbound form fields
    - Support TUIC in client bulk attach/detach and bulk add modals
    - Add TUIC badge color to client info modal, clients table, and host list
    - Update password tooltip across all 13 locales to include TUIC
    - Remove obsolete dead translation keys across all 13 locales
    
    * Chore(ci): Finalize TUIC v5 bundling across release workflow, Docker, and scripts
    
    * Feat(openapi): Update OpenAPI generator and schemas for TUIC types
    
    * Fix(backend): Address core review findings for TUIC types, port checks, and xray bridge
    
    * Refactor(traffic): Isolate proc reading with build tags and decouple TUIC metering into TuicJob
    
    * Feat(client): Add TuicServer to InboundOption, fix config export and clean share links
    
    * Fix(frontend): Register TUIC in multi-user helpers, tracked protocols, and tag derivation
    
    * Chore(openapi): Re-generate OpenAPI specification and sync Zod schemas
    
    * Chore(scripts): Add Alpine musl binaries, 386 and Windows packaging, and anchor pkill
    
    * Fix(review): Remove stale import, correct binary names, switch to musl, and drop unreachable relay gate
    
    * Feat(frontend): Show share link in Inbound Info and display UDP tag for TUIC
    
    * Docs: Add TUIC v5 configuration guide and link specifications
    
    * Docs(tuic): Correct Clash Meta configuration parameter to reduce-rtt
    
    * Fix(tuic): Generate client credentials on copy, enforce ID/password validation, and add i386 to DockerInit
    
    * Fix(tuic): drop unused relay, fix traffic accounting, and honor host endpoints
    
    - Drop unused loopback SOCKS relay and eliminate port collision with AmneziaWG
    - Correct inbound traffic calculation without double-counting
    - Drop heuristic client traffic division while retaining online tracking
    - Support externalProxy host fan-out and conditional parameters in share links
    - Scope orphan process termination to managed config directory
    
    * Fix(tuic): enforce client quotas, decouple Xray restart, and sync openapi schemas
    
    - Regenerate OpenAPI, Zod schemas, and TypeScript types without route_through_xray
    - Populate clientTraffics in TuicJob to enforce client quotas and first-use expiry
    - Split process I/O delta into up and down in Process.CollectTraffic
    - Remove SetNeedRestart from updateTuicInbound to prevent Xray session drops
    - Use InstanceFromInbound for default ALPN and UDP relay mode in tuic:// share links
    - Support allow_insecure on externalProxy host endpoints without parameter collision
    
    * Fix(tuic): attribute client traffic only on single-user inbounds and sync link defaults
    
    - Attribute I/O deltas to the client only when the inbound has exactly one configured client, avoiding false billing and disablings on multi-user inbounds
    - Aggregate client traffic by email in TuicJob so clients on multiple inbounds don't lose deltas
    - Match frontend genTuicLink defaults for alpn and udp_relay_mode with backend subscription links
    
    * Fix(tuic): gate client traffic by total sidecar clients and require client email
    
    * Fix(tuic): enforce inbound-only traffic limits and disable client totalGB
    
    * fix(tuic): restore delayed start, remove client totalGB rejection, and document linux-only limits
    
    * fix(tuic): anchor pkill, fix io baseline/split, escape yaml, and deduplicate start errors
    
    * fix(tuic): prevent traffic double-counting, ensure info log level for delayed start, and broaden pkill matching
    
    * fix(tuic): address review round 11 findings
    
    - internal/sub/json_service: skip tuic protocol in json subscription to prevent direct routing leak
    - internal/sub/clash_service: honor externalProxy/host row allowInsecure, sni, and alpn in buildTuicProxy
    - internal/web/runtime: decouple tuic inbound add/delete from xray restart
    - internal/tuic/config: restore user log-level options (warn, error) without forced info clamp
    - frontend/src/lib/xray/inbound-link: fix duplicate remark suffix and apply externalProxy TLS overrides
    - frontend/src/schemas/protocols/stream/external-proxy: propagate allowInsecure through host mapping
    - tests: add coverage for json sub skip, clash proxy overrides, and link generation
    
    * fix(tuic): meter inbound traffic through a UDP relay and bracket IPv6 binds
    
    Review repairs on the TUIC v5 sidecar integration:
    
    - Inbound traffic was read from the sidecar's /proc/<pid>/io rchar, but
      the kernel only counts read()/write() there and tuic-server moves its
      sockets with recvfrom/recvmmsg/sendmmsg/sendto, so an inbound's up/down
      stayed at 0 forever and inbound total limits never tripped (measured:
      12 MiB relayed, rchar delta 0). The panel now owns the inbound's public
      UDP port with a small relay and runs tuic-server behind it on a loopback
      port, counting up/down exactly on every OS. tuic-server therefore logs
      127.0.0.1 as every client's address; per-client attribution stays
      unsupported since QUIC is opaque.
    - Instance.BindTo formatted an IPv6 listen address as ":::8443", which
      tuic-server rejects with "invalid socket address syntax", so an inbound
      listening on "::" or any IPv6 literal never started. It now uses
      net.JoinHostPort; IPv4 output is unchanged.
    - The log level is passed to the sidecar as chosen. Online status,
      last-online and delayed start are read from its Info lines, so the Log
      Level field now says that Warn and Error switch them off for the
      inbound, and the docs say the same.
    - Drop two frontend tests that only exercised a getter and a set lookup,
      and strip the trailing blank line that made gofumpt fail on two of the
      new Go test files.
    
    * fix(tuic): harden tag updates, runtime routing, and relay stability
    
    ---------
    
    Co-authored-by: poise52 <equipoise52@gmail.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(outbounds): support custom subscription user agents (#6398)
    Some subscription providers require a client-specific User-Agent before returning outbound links. Persist an optional value per subscription and use it for refreshes and previews while preserving the existing default for blank values.
  • feat(sub): add read-only HWID device-slot status endpoint (#6380)
    * feat(sub): add read-only HWID device-slot status endpoint
    
    Closes #6357
    
    A client with an HWID limit had no way to tell a subscriber how many device
    slots were left: /{subPath}/{subId} only exposes the gate as a boolean through
    X-Hwid-* headers on a 404, and ?format=info carries no limitHwid or registered
    count. Every "why can't I connect on my new phone" case therefore had to be
    answered by the operator by hand.
    
    GET /{subPath}/{subId}/hwid-status now returns the aggregate counters:
    
      {"active":true,"limit":2,"registered":1,"remaining":1,"full":false}
    
    - SELECT-only. It never registers an hwid, never touches last_seen and never
      calls the enforcement path, so asking about a slot cannot spend one.
    - Counters only: no hwid value or hash, no email, no device metadata, no IP,
      no User-Agent, and none of the X-Hwid-* gate headers.
    - The subscription id is already the bearer secret for /{subPath}/{subId}, so
      no admin token and no new auth mechanism.
    - Unknown and disabled subscriptions both answer a bare 404, with identical
      status, headers and body, so the route cannot be used to probe which
      subscription ids exist.
    - No HWID limit configured returns {"active":false,"limit":0,...}.
    - No schema change and no migration.
    
    Scoped to enabled clients exactly like effectiveHwidLimitForSubID, so the
    reported limit is always the limit the gate enforces on a shared sub_id, and
    remaining clamps at zero when the effective limit drops below the number of
    registered devices. A separate route leaves /{subPath}/{subId}, ?format=info
    and the JSON/Clash routes byte-for-byte unchanged.
    
    Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
    
    * fix(sub): document hwid-status as the bare object it returns
    
    The OpenAPI operation for GET /{subPath}/{subId}/hwid-status inherited the
    {success,msg,obj} panel envelope from build-openapi.mjs's default 200
    response, while the handler writes the HwidSlotStatus struct bare. A client
    generated from the spec would read `obj` and never find the counters, and
    the description prose contradicted the schema with a hand-written example.
    
    HwidSlotStatus now sits in openapigen's StructAllow with example: tags, the
    entry references the generated schema through a `responses` block, and
    build-openapi.mjs attaches the generated example to any `responses` entry
    that $refs a generated schema, so no example is hand-written. The HEAD
    variant the controller registers is documented like its siblings, and the
    summary follows the "path prefix is configured by subPath" wording now that
    fresh panels randomise the prefix.
    
    Regenerated frontend/public/openapi.json, docs/public/openapi.json and the
    subscription-server MDX. openapi-runtime-contracts.test.ts pins the bare
    schema, the generated example and the HEAD operation.
    
    ---------
    
    Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(clients): let admins set PersistentKeepalive on tunnel clients (#6377)
    * feat(clients): let admins set PersistentKeepalive on tunnel clients
    
    model.Client already carries KeepAlive, and every AmneziaWG/WireGuard client
    config emitter already writes PersistentKeepalive when it is above zero -- but
    nothing in the UI could set it, so it stayed 0 and the line was never emitted.
    
    Without it a peer that goes quiet has nothing to trigger a handshake: WireGuard
    only initiates when it has data to send. An idle client stays disconnected
    after any interruption -- a NAT mapping timing out, a device sleeping, the
    panel restarting -- until the user generates traffic themselves.
    
    New clients default to 25, the conventional value, which also keeps the NAT
    mapping open. Existing clients keep whatever they have, and 0 remains valid and
    means "do not send keepalives".
    
    * fix(clients): let an explicit 0 actually disable PersistentKeepalive
    
    Addresses review feedback on the previous commit.
    
    UpdateInboundClient carries a stored keepalive forward whenever the incoming
    one is zero, so the settings JSON and the running peer survive a metadata-only
    edit that omits the field. That was a 0 -> 0 no-op while no UI could set a
    nonzero value. Now that the client form can, the carry-forward became reachable
    in the other direction: a client created at the form's default of 25 could
    never be returned to 0, and the hint text shipped to all 13 locales -- "0
    disables it" -- described something the backend silently refused. The save even
    reported success, because a settings blob that came back byte-identical skips
    the transaction entirely.
    
    The zero value cannot carry that distinction, so model.Client.KeepAlive becomes
    *int: nil means the field was never sent, &0 means "send no keepalives". The
    pointer survives the internal marshal in ClientService.Update, which is where an
    explicit 0 was being erased by omitempty before UpdateInboundClient ever saw it.
    ClientRecord.KeepAlive stays a plain int -- it is the stored column, where
    "unset" has no meaning -- and the conversions bridge the two.
    
    Two tests, both red before this change in the direction they cover: an explicit
    0 must reach wg_keep_alive, and an update that omits the field must still leave
    a stored 25 alone.
    
    Also adds the output transform every other numeric field in the client form
    already has, so a cleared box sends 0 rather than null.
    
    * fix(clients): repair the keepalive pointer conversion after the main merge
    
    Merging main brought buildAmneziaWGProxy (#6326) in beside the
    Client.KeepAlive int -> *int change without reconciling the new call site,
    so internal/sub stopped compiling and took every package importing it with
    it. The two sides touched different lines, so git merged them without a
    conflict -- the green `make verify` on 112b19a8 predates the break.
    
    ToClient also wrapped a stored 0 in a pointer, so omitempty stopped
    omitting: a VLESS client's settings JSON gained "keepAlive": 0 on the
    attach and bulk-attach paths, and that JSON reaches xray-core verbatim
    through GenXrayInboundConfig. wg_keep_alive cannot tell "off" from "never
    set", so a stored 0 now stays nil.
    
    Also copies the regenerated openapi.json over the docs mirror, which
    nothing in CI checks, and trims two comment blocks to the two-line cap.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(sub): add legacy Clash subscription endpoint (#6338)
    * feat(sub): add legacy Clash subscription endpoint
    
    * fix(deps): update js-yaml to patched release
    
    Raise the Swagger UI js-yaml override to 4.3.2 and refresh the lockfile to resolve GHSA-2883-xcg3-v3hh without changing Swagger UI.
    
    * fix(sub): preserve client detection and normalize legacy cipher
    
    Keep the original Clash/Mihomo auto-detection default so existing subscription URLs continue returning YAML. Normalize the panel-supported chacha20-poly1305 alias when generating legacy Clash profiles, and cover both regressions through HTTP endpoint tests.
    
    * refactor(sub): drop an unreachable guard and make the alias test assert
    
    Review of the legacy Clash subscription endpoint left three LOW findings, all
    introduced by the change:
    
    - The comment above the routing merge ran to three lines, over CLAUDE.md's
      two-line cap.
    - validateClashRouteGraph on the legacy path could never fail: the legacy
      branch skips the routing merge, so it validated the literal config built a
      few lines above against itself. Dead code that reads as a guard.
    - TestClashAliasesSkipConfiguredPathConflicts asserted nothing — it could only
      fail on an escaping gin panic, so a regression that registered the alias
      handler on the configured path went unnoticed. It now drives each collision
      through the router and asserts which format answers each path.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(ui): add global command palette (Ctrl+K) for fast navigation and search (#6352)
    * feat(ui): add global command palette (Ctrl+K) for fast navigation and search
    
    * fix(ui): address review feedback for shortcut listener, i18n parity, and search deep links
    
    * fix(ui): resolve search routing, translation keys, and palette state reset
    
    * fix(ui): improve command palette styling and sidebar transitions
    
    * fix(ui): address review feedback for typecheck, codegen, debouncing, and state reset
    
    * fix(ui): resolve effect state update warning and debounce reset in command palette
    
    * fix(ui): address review feedback for stale client search results and theme action
    
    * style(ui): apply oxfmt formatting to command palette and tests
    
    * fix(deps): update js-yaml override to resolve audit advisory
    
    * docs(api): sync the docs OpenAPI copy with the new InboundOption fields
    
    Adding Network/Security to InboundOption regenerated
    frontend/public/openapi.json, but docs/public/openapi.json is a
    hand-kept copy of that file and nothing checks it: make verify never
    reaches docs/, and docs-ci.yml fires only on docs/**. The two files were
    byte-identical on main and had diverged here, so the published API
    reference described a response shape the panel no longer returns.
    
    Regenerating the MDX under docs/content/docs/en/reference/api/ produced
    no change — the schema is read from the JSON at render time.
    
    * fix(ui): unnest the command palette row control and label its shortcut
    
    The palette row was a <button> wrapping the copy-subscription <button>.
    Nested interactive content is invalid HTML and React 19 logs two errors
    for it on every client result. The row is now a role="button" div using
    activateOnKey, the pattern the rest of the panel already uses, with
    line-height pinned so dropping the UA button style does not grow every
    row. Its keydown handler ignores events bubbling from the nested button:
    activateOnKey preventDefaults Enter, which would otherwise cancel the
    browser's Enter-to-click on the copy button and navigate instead.
    
    The sidebar chip hardcoded the Mac glyph while the handler accepts Ctrl
    as well, so Linux and Windows operators were shown a key they do not
    have; it now picks the modifier from the platform.
    
    Also restores the comment on ClientsPage's debouncedSearch that the
    deep-link change removed — the code it explains is unchanged.
  • feat(sub): bake Happ/INCY routing profiles into the JSON subscription (#6402)
    * feat(sub): parse generic Happ/INCY routing payloads for the JSON subscription
    
    Accepts the routing-rules format emitted for Happ and INCY (inline JSON,
    happ:// or incy:// deeplink, or a remote https:// URL resolved through the
    existing remote routing cache). The JSON subscription will bake these
    rules into its documents so header-ignoring clients still get routing.
    
    * feat(sub): bake Happ/INCY routing profiles into JSON subscription documents
    
    When subJsonRoutingRules is set, every emitted document (per-inbound and
    balancer alike) carries the profile's dns and routing rules baked in, so
    header-ignoring clients like Happ and INCY still get routing; the legacy
    simple-rules merge only applies when no profile is set. The balancer
    document builder keeps rewriting proxy-tag rules to the balancer.
    
    * feat(sub): add the subJsonRoutingRules setting
    
    Plumbed from the settings store through the subscription server into
    SubJsonService, so admins can set a routing profile once and every JSON
    subscription document carries it.
    
    * chore(api): regenerate OpenAPI artifacts for subJsonRoutingRules
    
    * feat(web): routing profile editor for the JSON subscription
    
    A textarea inside the JSON card accepts the routing profile (inline JSON,
    happ/incy deeplink, or https URL) with a remote-source badge; the badge
    helper moves to a shared module. Keys added to all 13 locales.
    
    * fix(sub): warm and lazily resolve the baked JSON routing source
    
    The routing profile was resolved once at service construction: a remote
    URL that was cold at that moment baked default routing forever, and the
    cron job never warmed it. The job now warms the subJsonRoutingRules URL,
    and the profile resolves per request with an in-memory memo (a failed
    resolve is not cached), so a warmed cache takes effect without a restart.
    
    * feat(sub): fall back to the JSON routing profile for the Routing header
    
    Happ and INCY download the geo files a routing profile references
    through the Routing response header. When the Happ header setting was
    blank the header stayed unset, and clients fetched no geo files even
    though a JSON routing profile was configured. A blank setting now falls
    back to the JSON profile: happ/incy deeplinks pass through, inline JSON
    and remote URLs are normalized to a happ:// deeplink; an unusable or
    oversized value leaves the header unset. Locale captions mention the
    fallback.
    
    * fix(sub): pass routingRules arg at call sites added by main
    
    Main gained four NewSubJsonService call sites after this branch forked;
    update them to the five-arg signature so internal/sub builds again.
    
    * fix(sub): address code review findings on the baked JSON routing
    
    The memoised baked template never invalidated, so an edited remote
    profile kept serving the superseded dns/routing subtrees until a panel
    restart; bakedTemplate now re-resolves the spec per request and rebuilds
    only when the payload actually changed (regression-tested).
    
    subJsonRoutingRules shared the happ persistence row with
    subRoutingRules, so only the last-written setting survived a restart;
    it now resolves under its own jsonhapp kind with the same validation
    and size caps. The setting also joins validateSettingsURLs, so remote
    values are canonicalised and bad URLs are rejected on save.
    
    Also: drop the unreachable half of the remote-source guard, cut the
    overlong comment blocks to the two-line convention, and deduplicate
    remoteSourceBadge in the General tab. Merges upstream/main (call sites
    for the widened NewSubJsonService signature).
    
    * style(sub): gofumpt the json_routing imports
    
    * fix(sub): accept happ add/ deeplinks and bound the routing warning
    
    The baked-JSON routing parser only recognised happ://routing/onadd/, but
    normalizeHappRouting treats happ://routing/add/ as an equally valid routing
    deeplink. An operator pasting the add/ form got the Routing header set, so
    the panel looked configured, while every JSON subscription document silently
    carried the default routing instead of their profile.
    
    resolveJsonRoutingSpec logged one warning per call and bakedTemplate calls it
    once per emitted document, so a single fetch of an unusable profile wrote one
    identical warning per document. On the public subscription server that floods
    the 10240-entry buffer the panel's log view reads, evicting real entries. Log
    only when the message changes, and reset on a successful resolve so a profile
    that recovers and fails again is still reported.
    
    Also resolve the template once in buildBalancerConfig: two resolves could
    straddle a profile refresh and pair one revision's dns with the other's
    routing.
  • feat(clients): support setting HWID limit and MTProto ad-tag in bulk adjust (#6399)
    * feat(clients): support setting HWID limit and MTProto ad-tag in bulk adjust
    
    Add HWID device limit and Telegram MTProto sponsor channel (ad-tag)
    support to the bulk client adjustment flow in both the panel API
    and frontend ClientBulkAdjustModal.
    
    Co-Authored-By: Claude Code <noreply@anthropic.com>
    
    * fix(clients): gate adTag to MTProto inbounds and avoid inbound rewrite for limitHwid
    
    Co-Authored-By: Claude Code <noreply@anthropic.com>
    
    * fix(clients): stamp updated_at only on the clients a bulk adjust changed
    
    The updated_at write was gated on hasInboundChanges, which accumulates
    over the whole inbound instead of describing the client in hand. Once any
    client in the settings array changed, every client after it was re-stamped
    as well, so whether an untouched client kept its own updated_at depended on
    its position in the array. That field feeds node-snapshot conflict
    resolution, where a spurious bump lets a stale snapshot value win over the
    stored record.
    
    Track the change per client and fold it into the inbound-level flag where
    the stamp is written, so the early return still skips a save whose settings
    JSON would be unchanged.
    
    Also condenses the BulkAdjust doc comment back to the two-line maximum.
    
    * docs(api): regenerate the bulkAdjust reference for limitHwid and adTag
    
    frontend/public/openapi.json was copied to docs/public/, but pnpm gen:api
    was never re-run, so the API reference page's heading, anchor id and search
    index still described bulkAdjust without limitHwid or adTag. docs-ci.yml
    fires only on docs/**, and that path had been touched, so nothing flagged
    the stale MDX.
    
    The externalLinks hunks are the generator rewrapping lines main had left
    stale, not a content change.
    
    * fix(i18n): stop enumerating fields in the bulk-adjust empty-form message
    
    bulkAdjustNothing listed the fields the form accepts, so it went stale
    every time one was added: only en-US ever gained "flow", leaving the other
    twelve locales describing days and traffic alone, and limitHwid and adTag
    would have repeated that. Say that one field is required instead of naming
    which, so the message cannot drift again.
  • feat(sub): add Happ client integration, routing presets, and app management (#6434)
    * feat(sub): add Happ client integration, routing presets, and app management
    
    Implement comprehensive Happ proxy client integration according to official developer specifications.
    
    - Fix header emission on disabled routing and hidden settings to send explicit '0' headers rather than omitting, allowing Happ clients to reset cached settings.
    - Add support for 'happ://routing/off' deeplink in routing validation.
    - Preserve '?serverDescription=' query parameters in link fragments without escaping to support Happ server subtitles across VMess, VLESS, Trojan and SS.
    - Add Happ application management headers: ProviderID, New-Url, Fallback-Url, Sub-Info banners, Sub-Expire notifications, No-Limit mode, hardware ID enforcement, TUN modes/types, route exclusions, APNS exclusions, and per-app proxy settings.
    - Add curated routing presets (Iran Bypass, China Direct, AdBlock, Global) and interactive visual rule generator in frontend settings.
    - Synchronize all 13 translation locales with native Persian, Russian, and Chinese translations.
    
    * fix(sub): keep Happ header overrides behind the auto-detect opt-in
    
    The Routing-Enable/Hide-Settings off values were emitted on the
    User-Agent alone, so every panel that upgraded would push
    "Routing-Enable: 0" — documented by happ.su as disabling routing
    globally — to every Happ client without the operator enabling anything.
    They now ride subHappAutoDetect like every other Happ header.
    
    Two further mismatches against the vendor spec:
    
    - serverDescription was written as a key of the VMess base64 JSON
      object. happ.su documents it as a "#Title?serverDescription=<base64>"
      link parameter or a JSON "meta" entry, so the caption never reached
      Happ while every other VMess consumer received an unknown key.
      Dropped rather than moved: emitting the documented form is unsafe
      here because our own parser base64-decodes the whole VMess body
      (internal/util/link/outbound.go).
    
    - The TUN Mode dropdown stored the literal "default", forwarded as
      "Tun-Mode: default", where happ.su documents system|gvisor only. It
      now stores the unset value so no header is sent. TUN Type "default"
      is a documented value and is unchanged.
    
    Each fix carries a test that fails without it.