Commit Graph
636 Commits
  • 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(sub): refine Happ routing presets, serverDescription escaping, and auto-detect placement (#6488)
    * feat(sub): refine Happ routing presets, serverDescription escaping, and auto-detect placement
    
    * fix(sub): address PR review findings on routing parity, agent regex, and i18n
  • 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(hosts): keep TLS override fields visible when Security is same (#6452)
    When Security is same, Fingerprint/SNI and TLS extras stayed live in form state but were hidden, so stale values could not be cleared (#6444).
  • fix(link): preserve Shadowsocks TLS query params on import (#6467)
    * fix(link): preserve Shadowsocks TLS query params on import
    
    Mirror trojan/vless stream parsing so Xray-native type/security/sni/alpn/fp
    query params on ss:// links survive into streamSettings on both Go and TS importers.
    
    Fixes #6094
    
    * fix(link): drop extra blank line so oxfmt passes
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • fix(frontend): fold sockopt v6only into V6Only on inbound load (#6453)
    Prevents duplicate keys and an unreachable switch when Advanced/API configs store lowercase v6only (#6421).
  • feat(settings): add Block tab for JSON subscription routing rules (#6466)
    * feat(settings): add Block tab for JSON subscription routing rules
    
    Expose the existing blackhole outbound in the subscription formats UI so
    operators can add block domain/IP rules without editing subJsonRules by
    hand. Scope Direct/Block helpers by outboundTag so the tabs keep separate
    rule objects, and keep block rules ahead of direct for Xray match order.
    
    * fix(settings): preserve rule order and clear foreign leftovers
    
    Stop sorting the whole subJsonRules array on every write. Prepend block
    defaults only when enabling Block. Clearing the last managed tag also
    drops foreign-tag leftovers so the panel can reach an empty setting.
    Fixes oxfmt on SubscriptionFormatsTab.
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • 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>
  • feat(clients): add Generate button for WireGuard/AmneziaWG PresharedKey (#6455)
    * feat(clients): add Generate button for WireGuard/AmneziaWG PresharedKey
    
    Matches existing key regenerate controls on the client form. Value is
    32 random bytes base64 via Wireguard.generatePresharedKey (same as
    wg genpsk). Field stays optional.
    
    Fixes #6343
    
    * fix(clients): keep FormField for WireGuard PresharedKey generate
    
    Restore RHF FormField (noStyle inside Space.Compact) so the regenerate
    control matches inbound reality patterns and satisfies oxfmt.
    
    ---------
    
    Co-authored-by: mrchatam <287639636+mrchatam@users.noreply.github.com>
  • Update deps and fix AntD Space API
    This change bumps the frontend and Go dependency set to newer patch/minor releases, including Vite, react-hook-form, zod, and the x/* Go modules. It also fixes a compatibility issue in the settings UI by switching Ant Design's Space usage from the deprecated `direction` prop to the current `orientation` prop.
  • 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>
  • fix(ui): keep the empty-group placeholder legible in dark mode
    The "no group" em dash in the clients table and in two client-picker
    modals was drawn with an inline color: rgba(0,0,0,0.45). The panel renders
    every page under antd's darkAlgorithm as well, so on a dark container that
    near-black placeholder is effectively invisible.
    
    All three now use Typography.Text type="secondary", the idiom the rest of
    the panel already uses for muted text — GroupAddClientsModal itself uses it
    58 lines further down.
    
    Mid-greys such as #888 elsewhere in the panel stay legible in both themes
    and are deliberately left alone.
  • 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.
  • feat(amneziawg): add AmneziaWG as an outbound protocol (#6320)
    * feat(amneziawg): add AmneziaWG as an outbound protocol
    
    - AmneziaWG outbound protocol end-to-end: config schema, socks bridge, netstack, panel UI
    - Route amneziawg outbounds to HTTP probe in TCP mode (backend + frontend classifiers) with pinning test
    - Add 2-minute idle read deadline to pumpUDPEgress to reap idle egress sessions
    - Require SOCKS5 username/password auth on the egress server (reject NO-AUTH with 0xFF) with test
    - Bound the egress TCP tunnel dial with portForwardDialTimeout (10s), matching portfwd.go
    - Resolve UDP domain targets off the association's reader loop via deliverUDPDatagram; race-safe getOrDial starts the reply pump at session creation; client passed by value into resolver goroutines (pinned by TestEgressUDPDatagramDomainInterleavedClients)
    - Reconcile early-returns on an empty desired set and closes the egress listener; EgressBasePort (64900) is reserved against local inbound port conflicts like the internal API port, with pinning tests for both the port reservation (TestCheckPortConflict_EgressPortBlockedLocal) and the Reconcile empty-desired Close/Listen lifecycle (TestOutboundManagerReconcileEmptyDesiredClosesEgress)
    - Eliminate acceptLoop shutdown race by validating listener != nil and registering to tracked under s.mu before wg.Add; bound pre-auth handshake with deadline (pinned by TestEgressServerCloseDuringConcurrentAccepts)
    - Support AAAA and dual-stack domain resolution in tunnel DNS resolver with v6 default fallback (DefaultTunnelDNSServerV6); add DNS field to frontend protocol form; avoid unneeded cache flushes on unchanged SetStack ticks
    
    * fix(amneziawg): resolve IPv6-only DNS default fallback and validate required keys
    
    - Default to IPv6 tunnel DNS on IPv6-only outbounds with blank dns
    - Require non-empty secretKey and peer publicKey in ValidateAmneziaWGOutbound
    - Add end-to-end IPv6 tunnel domain resolution test and test empty key rejection
    - Trim comment blocks exceeding 2 lines across modified files
    - Fix Storybook test execution on environments with POSIX locale
    
    Co-Authored-By: Claude Code <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: rqzbeh <rqzbeh@users.noreply.github.com>
    Co-authored-by: Claude Code <noreply@anthropic.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • chore(frontend): bump React and Zod deps
    Update frontend dependencies to React/ReactDOM 19.3.0, Zod 4.6.1, and matching React type packages. Also replace Storybook addon-vitest override placeholders with explicit Vitest/browser-playwright versions to keep dependency resolution stable.
  • feat(xray): update xray-core to v26.9.9 and follow the udpHop move
    Bump xtls/xray-core to 52a412d9e2f5 (v26.9.9) and the three binary pins in
    DockerInit.sh and release.yml in lockstep.
    
    Upstream moved UDP port hopping out of finalmask.quicParams.udpHop and into a
    standalone "udphop" UDP mask with a different shape (mode / interval /
    remotePorts / remoteIPs). The old key is gone from QuicParams, and since the
    config loader ignores unknown fields it is now silently dropped rather than
    rejected — port hopping just stops.
    
    The panel adapts where that key was live:
    
    - Both link importers rebuilt quicParams.udpHop from the standard mport param,
      so an imported hysteria2 link produced an outbound that no longer hops. They
      now emit a udphop mask in intervalremote mode, which is what the old key did.
      The mode is required: UDPHop.Build() rejects an empty or unknown one.
    - validFinalMaskUDPTypes and UdpMaskTypeSchema learn "udphop", otherwise the Go
      link generator strips the mask from every link and sub, and Zod strips it on
      the next form round trip.
    - mport generation (Go and frontend) reads the mask first and keeps reading the
      legacy key, so inbounds stored before the upgrade still advertise their range.
    
    On an inbound the old key was always inert — only hysteria's dialer consumed
    it — so nothing regresses server-side and no migration is needed. udphop stays
    out of the mask dropdown on purpose: it is client-only in core, which refuses
    to wrap a server socket, and that form is shared with the inbound editor.
  • fix(dns): stop offering a port field that DoH entries discard
    Xray ignores port for DoH/DoHL/DoQL, so valuesToWire deliberately stores none
    for an encrypted address and a non-standard port has to go inside the URL. The
    form kept offering the field anyway, pre-filled with the 53 from its own
    defaults: a port typed there was dropped on save and redrawn as 53 on reopen,
    which reads as the panel losing the value.
    
    Render the port field only where it is actually stored. DoT keeps it, since
    tls:// is not an encrypted-address scheme for this purpose.
    
    Closes #6403
  • fix(inbounds): reject missing TLS certificates before saving (#6429)
    An inbound could be saved with security "tls" and a certificate row carrying
    neither a file path nor inline content. Nothing rejected it, so the row reached
    xray-core, whose readFileOrString fails with "both file and bytes are empty"
    and takes the whole config build down with it — every other inbound included.
    
    Validate the credentials on both sides of the wire. validateInboundTLSCertificates
    follows xray's file-over-inline precedence, requires a private key for every
    non-verify certificate and insists on at least one server certificate, so a
    verify-only CA list no longer passes as a server config. The inbound form's Zod
    schema enforces the same rules per field and serializes only the editor mode the
    operator actually used, and a failed save jumps to the Security tab naming the
    certificate row that broke.
    
    On update the guard is scoped to a real TLS edit. A row already stored
    incomplete is grandfathered: it stays editable, and only a save that breaks a
    previously valid block is refused.
    
    A sub-node stores whatever the master pushes, and Remote.UpdateInbound falls
    back to AddInbound when the node does not yet hold the tag, so a grandfathered
    row could otherwise never be deployed or re-seeded — the rejection is swallowed
    to a logger.Debug line and the node stays on a stale config while the panel
    shows the client as cut off. The controller now marks a node-sync request (mTLS
    or a node-sync token) on a per-request copy of InboundService, and the guard
    steps aside for it on both add and update: the row was judged where the
    operator acted, and a node that refuses it only falls out of sync. Operator and
    admin-token saves are held to the guard as before.
    
    The security union is parameterised on its tlsSettings branch instead of copied,
    and tlsCertUsesFiles is the one file-vs-inline inference shared by the form
    schema and the adapter, so the mode the editor opens in and the pair of fields
    the save serializes cannot drift apart.
  • feat(sub): add dummy info node and status configs for subscriptions (#6412)
    * feat(settings): add subInfoNodeEnable and status template settings
    
    * feat(sub): add dummy info node and status configs for raw links
    
    * feat(sub): support dummy info node in clash and json subscriptions
    
    * feat(ui): add subscription info node switch and status templates to settings
    
    * style: apply gofumpt formatting
    
    * fix(sub): address review feedback on subscription info node
    
    - Restore GetSubs contract to avoid unintended remark expansions on non-subscription-body calls.
    - Exclude dummy info node from Clash PROXY select group when active server nodes exist.
    - Track hasEnabledClient and set traffic.Enable in JSON and Clash paths so status tokens evaluate correctly.
    - Deterministically sort client emails across subscriptions before selecting primaryEmail.
    - Consolidate duplicated info-node evaluation logic into resolveInfoNodeRemark helper.
    - Remove redundant pure-getter test from setting_sub_info_node_test.go.
    
    Co-Authored-By: Claude Code <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Code <noreply@anthropic.com>
  • docs(api): mark collection responses nullable (#6430)
    * docs(api): mark collection responses nullable
    
    Describe allLinks and panel log response objects as nullable string arrays so generated clients accept the existing nil-slice wire format. Pin both schemas with buildSpec regression assertions and regenerate the OpenAPI copies.
    
    * docs(api): include nullable Xray log responses
    
    Allow generated response arrays to opt into nullability while retaining their schema references and Go-derived examples. Apply this to Xray logs, whose nil slices already serialize as null, and pin the schema and example through buildSpec.
  • fix(amneziawg): account for S4 junk in the default tunnel MTU (#6376)
    * fix(amneziawg): account for S4 junk in the default tunnel MTU
    
    amneziawg prepends S4 random bytes to every transport packet
    (device.NewOutboundElement) and, unlike content padding and random trailers,
    never clamps them against the tunnel MTU. A full-size packet therefore lands on
    the wire at MTU + 60 + S4 bytes: 20 IPv4 + 8 UDP + S4 + 16 transport header +
    16 poly1305 tag.
    
    With the 1420 default that overflows a 1500-byte link once S4 exceeds 20, and
    GenerateObfuscation31 draws S4 from 12..27 inclusive -- so roughly 44% of newly
    created inbounds fragment every full-size packet they send.
    
    Measured on a live pair of interfaces, predicted against observed:
    
        MTU 1380  S4 12  ->  1452 on the wire   (fits)
        MTU 1420  S4 12  ->  1492               (fits)
        MTU 1420  S4 20  ->  1500               (exactly at the limit)
        MTU 1420  S4 21  ->  1501               (fragments)
        MTU 1420  S4 27  ->  1507               (fragments)
    
    EffectiveMTU now subtracts S4 from the default; an explicit MTU is untouched.
    
    Client configs carry the same number. They previously omitted the MTU line
    whenever the server had no explicit value, which left the client on its own
    1420 default and fragmented the client-to-server direction even after the
    server side was fixed -- silently, and only in one direction. All three
    emitters (the Go subscription text and the two TypeScript ones) now agree,
    which is what the existing parity test exists to protect.
    
    * fix(amneziawg): rebuild the device when S4 changes the derived MTU
    
    Addresses review feedback on the previous commit.
    
    Deriving the default MTU from S4 made a construction-time-only property depend
    on a hot-reloadable input, but addressFingerprint -- ensureLocked's only rebuild
    trigger -- still hashed the raw inst.MTU. S4 is a UAPI field, so an S4-only edit
    took the in-place IpcSet branch and the gVisor netstack kept the MTU derived
    from the old S4 while all three client emitters already advertised the new one.
    
    Every panel-created inbound leaves mtu unset, so that was the normal case, not
    an edge one: with S4 raised far enough the fragmentation this fix exists to
    remove came straight back, and stayed until a panel restart or an unrelated
    address edit.
    
    Folding EffectiveMTU into the fingerprint fixes it. An explicit MTU still takes
    the in-place branch on an S4 edit, since it does not move the interface MTU.
    
    Also trims four comment blocks to the 2-line cap in CLAUDE.md, and points
    NewDevice's doc comment at EffectiveMTU instead of the deleted defaultMTU.
  • fix(mtproto): use hosts for public share links (#6369)
    * fix(mtproto): use hosts for public share links
    
    Generate MTProto subscription, client, copy, QR, and export links from managed Hosts so reverse-proxied public ports are advertised correctly. Migrate the redundant legacy custom share address into a Host and keep old imports compatible.
    
    Closes #5126.
    
    * fix(mtproto): keep host share links lossless and consistent
    
    Address review on the MTProto hosts share-link change.
    
    The migration no longer drops a legacy custom share address: an unrelated
    (or disabled) Host stopped suppressing it, so only a Host already advertising
    the same address does. An imported address now clears the same validation the
    strict normalizer applies to every other protocol before it becomes a Host.
    
    Panel and subscription agree on the endpoint a Host advertises: a portless host
    string inherits the inbound port rather than the group's, and a port-only host
    inherits the inbound address instead of emitting server=%3A8443.
    
    LinksForClient prefers host endpoints for every protocol, the way getSubs and
    inboundLinks already do, so the client-links API no longer ignores managed
    hosts.
    
    * fix(mtproto): migrate legacy share address past unusable hosts
    
    The seeder skipped the conversion whenever any Host already carried the
    address, including one that is disabled or excludes the raw sub type.
    hostEndpoints drops those, so nothing advertised the address afterwards and
    the marker committed with no way back. The duplicate check now mirrors that
    same predicate.
    
    UpdateInbound cleared a legacy MTProto shareAddr without the Host conversion
    AddInbound runs, so re-applying an inbound definition through the API dropped
    the public address silently. Both paths share one capture helper now.
    
    Refresh the generated clients API reference for the summary reworded in the
    previous commit.
    
    * fix(inbounds): wait for the hosts list before building mtproto links
    
    The page destructured only `hosts` from useHostsQuery, and that list reads
    empty both while /panel/api/hosts/list is in flight and after it fails.
    withMtprotoHostEndpoints then returns the inbound untouched, so Copy, QR and
    Export advertise the internal listen port — the endpoint this branch exists to
    replace. It is worse than not fixing it: the seeder has already moved a legacy
    custom share address into a Host, so the fallback is the panel's own hostname
    instead of the operator's address, and the Go generators reading the same rows
    from the DB stay correct, so the two disagree for one inbound.
    
    Fold the query into the page's existing readiness gate, the same way
    useInbounds and HostsPage already consume that hook, so an empty list means
    "no hosts" rather than "not loaded yet". The error branch fires only when
    nothing is cached, so a refetch failing on window focus does not blank a page
    whose host rows are still perfectly usable.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • Update deps and simplify parsing
    Bump frontend and Go dependencies, then modernize a few hot paths with newer Go string/range helpers. Also widen the client form quota/limit fields to improve the layout.
  • feat(xray): update xray-core to v26.9.8 and adapt panel
    Bump xtls/xray-core to 37ceb8b4b6 (v26.9.8) and the three binary pins
    (DockerInit.sh, release.yml Linux + Windows) in lockstep. No deleted
    symbols; the impact is entirely on the JSON config surface.
    
    Outbound "proxySettings" is now refused by the config loader (moved to
    streamSettings.sockopt.dialerProxy) and a freedom outbound rejects
    sockopt.addressPortStrategy. Either key in a stored template would keep
    the core from starting after the upgrade, so a new OutboundRemovedKeysFix
    seeder rewrites xrayTemplateConfig once: proxySettings.tag becomes
    sockopt.dialerProxy (an existing dialerProxy wins) and addressPortStrategy
    is dropped from freedom outbounds. Template saves and outbound
    subscriptions already run through the vendored loader, so the new
    refusals surface there with the core's own message.
    
    REALITY no longer applies a built-in minClientVer (26.3.27) when the
    field is empty. The form placeholder and the min/max hints in all 13
    locales now say that empty means no minimum.
    
    New upstream keys the Zod schemas would otherwise strip, with form
    support where a sibling field already had it:
    - blackhole response type "custom" with base64 customResponseData
    - realm finalmask ipMode (dual/v4/v6) and portMapping (UPnP / NAT-PMP)
    - quicParams brutalDisableLossCompensation, disableChromeParrot,
      disableGSO, disableStatelessReset
    - hysteria masquerade proxy xForwarded
    - wireguard outbound remoteDNS
    - routing rule localOS
    
    freedom.domainStrategy is only deprecated upstream (auto-migrated to
    sockopt.domainStrategy with a warning) and is left untouched.
  • fix(clients): flag the restart a partly-applied edit or delete still needs
    63b46cd6 made a multi-inbound client op apply its inbounds concurrently and
    stop aborting at the first failure, so an error can now come back together
    with needRestart=true: the inbounds that succeeded committed real changes and
    their Xray still needs the restart. That commit taught the two callers it
    converted — create and attach — to read the flag before the error check.
    
    d34ec97f then routed Update, Delete, Detach and DeleteByEmail's record-less
    fallback through the same fanout but touched no caller, so on a master with
    several nodes a partly-applied edit or delete returned (true, err) into a
    handler that returned on err first. Xray was never flagged for the work that
    landed and notifyClientsChanged never fired, so the running config kept
    serving the pre-edit client set and every open panel showed stale rows until
    something else happened to trigger a restart.
    
    Read needRestart before the error check in update, delete and detach, and
    broadcast on needRestart || err == nil — the same shape create and attach have
    had since 63b46cd6. The predicate is a strict superset of the old err == nil,
    and needRestart is only ever assigned after a runSerializedTx commit, so it
    firing genuinely means something landed.
    
    The three handlers are pinned by a new controller test each: one client on two
    inbounds, the second one's settings JSON corrupted so the op commits on one and
    fails on the other, asserting both the success:false response and the restart
    flag. All three fail without the change.
    
    The API docs for update, del and detach now describe the partial-application
    contract, as add and attach already did. Detach ends at the fanout so every one
    of its errors carries the inbound prefix; update and delete write the client
    record afterwards, and a failure there is reported without one.
  • docs(api): align OpenAPI with runtime contracts (#6409)
    Document the cookie-authenticated WebSocket upgrade and its emitted envelopes without exporting pseudo-paths. Align REST response schemas, paged-client filters, and subscription HEAD operations with their runtime implementations, then regenerate frontend and docs artifacts.
  • fix(amneziawg): reject obfuscation values amneziawg-go's own UAPI rejects
    ValidateObfuscation exists, by its own doc comment, so that a bad manual
    entry cannot break the embedded device's IpcSet. It was not covering enough
    to do that. Auditing the panel against amneziawg-go v3.1.20260828's full
    UAPI surface turned up two holes, both confirmed by driving the values
    through a real IpcSet:
    
      S1 = 70000        upstream parses s1-s4 as uint16
      S2 = 70000        (device/uapi.go)
      Jc = -1           jc/jmin/jmax are uint32, so no negatives
      Jmin/Jmax = -5/-1
      Jc = 5000000000   and nothing wider than uint32
      I1 = <rand 100>   newObfChain hard-fails on an unknown tag
      I1 = <r 100       ... and on a missing '>'
      I1 = <>           ... and on an empty one
    
    All eight passed validation and were then rejected by the device. Only S3
    and S4 were bounded, which is why the asymmetry went unnoticed. The inbound
    saves, the reconcile fails on every tick, and the interface never comes up
    with a single log line to say so.
    
    Bound the five numeric fields to the widths upstream actually parses, and
    check the I1-I5 chain's <tag value> structure against a tag set mirroring
    upstream's own obfBuilders map. Each tag's value grammar stays amneziawg-go's
    to enforce -- that is eight builders across several files, and duplicating
    them here would drift. So <r abc> still reaches IpcSet, now as the only
    remaining class rather than one of four.
    
    Mirror the same bounds in the Zod schema, next to the max() that s3 and s4
    already carried, so the form rejects the value instead of the save doing it.
    
    TestValidatedObfuscationAlwaysApplies pins the contract itself: whatever
    ValidateObfuscation accepts, a real amneziawg-go device must accept too. It
    covers the specs the new grammar check deliberately allows, not just the ones
    it rejects, so the allowlist cannot quietly become stricter than upstream.
    
    The rest of the audit found no gaps: all 17 settable device keys reach
    buildUAPIConfig, ServerSettings, the Zod schema and all three .conf
    emitters. fwmark and persistent_keepalive_interval remain unemitted, both
    deliberately -- the panel models no fwmark anywhere, and keepAlive is carried
    client-side where WireGuard puts it.
  • perf(clients): apply a multi-inbound client create concurrently
    Creating or attaching a client across N inbounds called AddInboundClient
    once per inbound, strictly one after another. When those inbounds live on
    different nodes each call is a full node round-trip bounded by the 10s
    remote timeout, so the request cost the SUM of every node's latency: two
    nodes felt instant, three took ~13s and timed out bot callers, which is
    how it surfaced as "two out of four account creations fail".
    
    Split the per-inbound preparation from the apply. Preparation stays
    ordered and single-threaded because fillProtocolDefaults mints the shared
    credentials on the first inbound and every later one reuses them; the
    applies then run concurrently, capped at inboundFanoutConcurrency. A
    4-node create measured 1.205s -> 0.307s with peak overlap 1 -> 4.
    
    Consequences of no longer aborting at the first failing inbound:
    
    - Every apply error is tagged with its inbound and the failures are
      joined, so all of them reach the caller instead of just the first.
    - The fanout goroutines recover their own panics. Off the request
      goroutine gin's Recovery no longer covers them, and an unrecovered
      panic would kill the panel rather than fail one inbound.
    - A partly-applied call commits clients on the inbounds that succeeded,
      so the controller and the LDAP job now read needRestart before the
      error check; otherwise Xray was never flagged for the work that landed.
    - limitHwid is applied only when every inbound succeeded. Applying it
      after a failure rewrites limit_hwid and trims the registered devices of
      an email that already existed, which is silent data loss on an
      operation the panel reported as failed.
    
    Update the API docs for the new partial-application contract and the
    inbound-tagged error strings.
  • Feature/fix external subscription client expiry (#6333)
    * fix(sub): honor client expiry for external links
    
    * fix(ui): show client expiry on external links
    
    * fix(sub): address external expiry review
  • fix(amneziawg): H1-H4 generator + queue-depth throughput fixes (#6330)
    * fix(amneziawg): stop H1-H4 generator misclassifying transport packets
    
    Both the Go generator and its frontend mirror picked a random *range*
    per H1-H4 field with only a minimum width enforced (no maximum).
    amneziawg-go's packet classifier only ever compares a fixed-size
    ciphertext prefix against these bounds, so a wide range buys no DPI
    resistance -- the boundaries themselves are never observable on the
    wire. It does cost real throughput: with randomTrailers on (the
    default here), the handshake-size checks relax from == to >, so a
    wide H-range misclassifies a proportional fraction of ordinary
    transport packets as handshakes and silently drops them
    (amnezia-vpn/amneziawg-go#183). A single value per field is strictly
    safer than any range, with no obfuscation trade-off.
    
    Live-tested: narrowing H1-H4 alone took AmneziaWG upload from
    2-3 Mbit/s to 200+ Mbit/s on one box, and ~20 Mbit/s to 120-156 Mbit/s
    on another, single-variable, no other change.
    
    * fix(amneziawgnet): raise tunQueueDepth to absorb slow-start bursts
    
    1024 was sized for a single-connection buffering problem (the
    gVisor-to-amneziawg-go TUN handoff channel needing slack for the
    download direction). tcpip.Stack.Stats() during a real many-connection
    download (20-28 concurrent TCP flows, e.g. a segmented speed test)
    showed SlowStartRetransmits jump by ~770 in a single second the moment
    CurrentEstablished crossed ~20 -- consistent with many connections'
    simultaneous slow-start growth briefly exceeding 1024 outstanding
    packets and gVisor treating the resulting silent drops as real network
    loss.
    
    * fix(amneziawg): trim comment blocks to the repo's 2-line cap
    
    Review feedback: four comment blocks in the previous commits exceeded
    CLAUDE.md's 2-line-per-block hard rule (up to 13 lines). Trimmed each to
    the one non-obvious fact plus the amneziawg-go#183 reference; the fuller
    rationale already lives in the commit message. Also refreshed the stale
    H1-H4 range example in docs/content/docs/en/config/amneziawg.mdx to match
    the new single-value generator output.
  • fix(api-docs): generate request bodies for all encodings (#6296)
    * fix(api-docs): generate request bodies for all encodings
    
    The OpenAPI generator only recognized generic body parameters, so JSON, form, and multipart declarations disappeared into empty application/json objects. Generate the declared media type and schema, preserve optionality and conditional requirements, and encode repeated form arrays the way Gin expects. Correct the request metadata exposed by the complete schemas and keep the panel and docs specifications synchronized.
    
    * fix(api-docs): align alternative request schemas
    
    Keep non-empty constraints on the selected request-body alternative without rejecting empty values for the alternatives that panel requests also include. Allow null client IP lists because model serialization emits them while cleared rows await pruning.
    
    * fix(api-docs): send object urlencoded fields as JSON, document the inbound update body
    
    Four defects the request-body rework exposed or left behind:
    
    - An object-typed field in an x-www-form-urlencoded body got no encoding
      entry, so OpenAPI 3.0 serialized it form-style. Swagger "Try it out"
      and generated clients sent memberWeights=3&memberWeights=0.2 to
      /panel/api/sub-balancers, and parseSubBalancerForm json.Unmarshals the
      raw field, so every such call failed with "invalid memberWeights".
      Emit encoding.<name>.contentType = application/json instead.
    - bodyRequiredOneOf names were never checked against the declared body
      params: a typo emitted an anyOf branch requiring a property that does
      not exist — unsatisfiable — and make gen still passed. Throw now, and
      extend the requestSchema guard to reject bodyRequiredOneOf as well.
    - /panel/api/inbounds/update/:id advertised no request body although its
      own summary says the shape mirrors /add and updateInbound binds one.
      Both entries now share an inboundBody const so they cannot drift.
    - The mixed-locations error was the only buildOperation throw without
      the method and path, aborting make gen without naming the offender.
    
    Regenerated frontend/public/openapi.json and copied it to
    docs/public/openapi.json. No MDX regeneration: no summary changed.
    
    ---------
    
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • chore: upgrade Vitest to v5
    Update frontend dev tooling to Vitest 5 by bumping `vitest`, `@vitest/browser-playwright`, and `@vitest/coverage-v8`, plus `@types/react-dom`. Add an override for `@storybook/addon-vitest` to pin Vitest-related packages to compatible versions and avoid dependency mismatch issues. Also bump the Go toolchain patch version from `1.27.0` to `1.27.1` in `go.mod`.
  • fix(clients): render all tunnel configs for multi-inbound client (#6346) (#6349)
    When a client belongs to multiple AmneziaWG or WireGuard inbounds (e.g. across
    remote nodes), findAmneziaWGInbounds and findWireguardInbounds only returned the
    first matching inbound. Consequently, ClientInfoModal and ClientQrModal rendered
    only one config block, making other inbounds' configs unreachable.
    
    - Add findAmneziaWGInbounds and findWireguardInbounds returning all matching inbounds
    - Add formatTunnelConfigMeta helper to unify label, fileName, and qrRemark resolution
    - Support addressOverride in buildWireguardClientConfig from tunnelAllowedIPs
    - Render all tunnel configs in ClientInfoModal and ClientQrModal with node remarks
    - Distinguish download filenames with inbound remark suffix to avoid collisions
    - Add component integration tests covering multi-inbound modal rendering
  • fix(hysteria): standard geco share links and persistent uTLS None (#6325)
    - Export standard gecko obfs query params in hysteria2 share links
    - Enforce packet size bounds across Go and TypeScript link handlers
    - Persist uTLS None explicitly and initialize new TLS inbounds to chrome
    - Tear down stackTun safely without closeMu deadlock against WriteNotify
    
    Co-authored-by: rqzbeh <rqzbeh@users.noreply.github.com>
  • fix(sub): randomize fresh panel subscription paths (#6375)
    * fix(sub): randomize fresh panel subscription paths
    
    Seed distinct cryptographically random paths for base64, JSON, and Clash subscriptions when a panel database is first created. Persist them so restarts keep published URLs stable while upgrades preserve existing settings.
    
    Generated-by: OpenCode:gpt-5.6-sol
    
    * fix(sub): regenerate paths on settings reset
    
    Keep subscription paths unpredictable after a factory reset, close the test database on failure, and update the builder, OpenAPI, and localized docs to describe panel-specific paths instead of obsolete fixed defaults.
    
    Generated-by: OpenCode:gpt-5.6-sol
  • fix(frontend): isolate subscription language preference (#6394)
    * fix(frontend): isolate subscription language preference
    
    * fix(frontend): defer date locale resolution
  • fix(frontend): improve dense QR readability (#6396)
    Dense AmneziaWG configs crossed a QR version boundary at the fixed display size, and the generated symbol had no quiet zone. Use low error correction and a four-module margin to reduce module density while keeping the payload unchanged.
  • chore(deps): bump docs and frontend deps
    Update dependency versions across `docs` and `frontend`, including Next/Fumadocs packages in docs and Ant Design, React Query, Storybook, and related tooling in frontend. Also updates lint/format tool versions (`oxlint`, `oxfmt`), bumps docs `pnpm` package manager version, and refreshes workspace release-age exclusions for the newly upgraded docs packages.
  • feat(routing): add panel-only comment field to routing rules (#6361)
    Can annotate rules with a human-readable note for easier management.
    The comment is stripped before sending the config to xray-core (same
    pattern as the existing 'enabled' flag).
    
    Backend: stripDisabledRules now removes 'comment' from generated config.
    Frontend: input field in RuleFormModal, column in desktop table, chip
    with tooltip in mobile card list. Schema and type definitions updated.