Commit Graph
20 Commits
  • feat(sub): allow identity tokens on every subscription link (#5935)
    Keep usage tokens first-link-only while adding an opt-in setting for repeating EMAIL and USERNAME in subscription-body remarks.
    
    Co-authored-by: x06579 <x06579@ai-dashboard>
  • fix(ui): explain the REALITY client version gate and drop the impossible placeholder (#6125)
    * fix(ui): explain the REALITY client version gate and drop the impossible placeholder
    
    An empty Min Client Ver looks unrestricted, but Xray-core silently
    falls back to a built-in minimum (currently 26.3.27) that rejects
    third-party cores such as Mihomo and sing-box with a bare REALITY
    verification failure, and nothing in the panel points at the field.
    Add tooltips to both version fields explaining the fallback and its
    TLS-fingerprint-freshness rationale.
    
    The Max Client Ver placeholder (25.9.11) sat below the built-in
    minimum, so filling in both placeholders produced a range that
    rejects every client. Remove it; empty genuinely means no upper
    limit for that field.
    
    Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
    
    * docs(reality): warn that an empty min client version rejects old cores
    
    Common pitfalls covered bad targets, SNI mismatches, leaked keys and
    wrong flow, but not the client version gate that currently bites
    Mihomo and sing-box users. Add it to all four doc languages.
    
    Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
    
    * fix(ui): word the version hints against the effective minimum
    
    Address the automated review: the Max Client Ver hint said only 'not
    lower than Min Client Ver', which re-establishes the empty-means-unset
    mental model when the effective floor is the core's built-in minimum.
    Both hints now name the effective minimum and tie the quoted 26.3.27
    to the core build the panel runs, since operators can install any
    Xray-core version.
    
    Also from review: full-width quotes and a missing verb in the zh doc
    bullet, the idiomatic Arabic opening, and a format-only x.y.z
    placeholder on Max Client Ver so the field still conveys its shape.
    
    Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
  • chore(deps): migrate to react-router 8 and refresh frontend dependencies
    react-router-dom 7 is superseded by react-router 8, which folds the DOM
    bindings back into the core package. RouterProvider now comes from
    `react-router/dom`, while the hooks and `createBrowserRouter` move to
    `react-router`. Updates the nine importing modules and the router line in
    docs/architecture.md to match.
    
    Also refreshes antd, react-i18next, storybook, eslint, lint-staged and
    playwright to current patch/minor releases, and restores alphabetical order
    in devDependencies for the @vitest/browser-playwright and playwright entries.
    
    Bumps brace-expansion to 5.0.8, the only release outside the affected range
    of GHSA-mh99-v99m-4gvg (unbounded expansion length causing an OOM crash).
    `npm audit fix` could not apply this on its own: the lockfile pinned 5.0.7
    and npm will not re-resolve a transitive-only dependency in place, so the
    entry was updated directly and reinstalled.
  • fix(docs): force transitive sharp up to patched 0.35.3
    sharp <0.35.0 inherits four libvips CVEs (GHSA-f88m-g3jw-g9cj). It comes
    in as an optional dependency of next, which still declares ^0.34.5 on its
    current release, so only an override reaches the fixed line. Brings
    libvips 8.18.3 via @img/sharp-libvips-* 1.3.2.
  • feat(sub): expose live online status and add ?format=info endpoint
    Custom subscription templates only received the lastOnline timestamp, so
    template authors had to fake an online indicator by comparing it against
    the current time, and the page was a one-shot server render with no way
    to refresh usage without reloading the whole HTML.
    
    The template context (and window.__SUB_PAGE_DATA__) now carries isOnline,
    computed from the panel's own online-client tracking (local xray plus
    remote nodes) at render time. The subscription URL also answers
    ?format=info with the page view-model as JSON — minus the links, with
    emails deduplicated — so templates can poll live status cheaply. The
    shared view-model construction moved into buildSubPageData/subPageContext
    so the HTML page, the SPA payload and the info JSON cannot drift apart.
    
    Also documents the previously injected but undocumented announce
    template variable.
  • chore(deps): bump docs and frontend dependencies
    Routine minor/patch updates: Next.js 16.2.11 + eslint-config-next,
    fumadocs, React 19.2.8, Storybook 10.5.3, and assorted tooling.
    
    Docs stays on ESLint 9 (^9.39.5): eslint-config-next pulls in
    eslint-plugin-react 7.37.5, whose newest release still calls the
    context.getFilename API that ESLint 10 removed, so eslint crashes on
    every file under ESLint 10. The frontend workspace already ran ESLint
    10 without eslint-plugin-react and is unaffected.
  • chore: standardize the toolchain on Node 24 LTS
    The repo now pins Node 24 everywhere instead of mixing 22 and hardcoded workflow versions. The docs workflows read .nvmrc like the main CI already did, so the Storybook bundle in the Pages deploy builds on the same runtime as the PR gate. The docs gen:api script runs its TypeScript entry natively, dropping the experimental type-stripping flag that Node 24 makes default; the matching frontend cleanup (engines and gen:api) landed with the Storybook commit.
  • feat(docs): publish the component Storybook on the docs site
    The docs site and the component workbench were entirely disconnected. The Pages deploy now builds the frontend Storybook and bundles it into the artifact under /storybook, so the live component reference ships with the documentation, and the navbar links to it. Story changes trigger a redeploy so the published workbench cannot go stale.
  • feat(xray): update xray-core to v26.7.11 and adapt panel
    Bump xtls/xray-core to 50231eaf (v26.7.11) and the three binary pins
    (DockerInit.sh, release.yml x2) in lockstep.
    
    Adapt the panel to the upstream changes:
    
    - Shadowsocks "none"/"plain" and VMess "none"/"zero" were removed from
      the core. A migration rewrites stored none/plain SS methods to a
      supported cipher and none/zero VMess security to "auto" (on both the
      clients column and inbound settings JSON); the SS build-time heal does
      the same so a row injected after boot cannot brick startup. The removed
      values are dropped from every frontend option list, schema and adapter,
      and coerced to "auto" at the Go link/sub/Clash emit sites and both link
      importers. Fix the CipherType_NONE sentinel that no longer compiles.
    
    - Unencrypted vless/trojan outbounds to a public address are now refused
      by the core. Validate outbounds through the vendored config loader when
      saving the xray template and when storing/merging outbound
      subscriptions, so one such outbound cannot keep the core from starting.
    
    - New TCP finalmask type "xmc" (Minecraft mimicry): add it to the sub
      link allowlist, the frontend enum and the FinalMask form (hostname,
      usernames, required password), and document it.
    
    - streamSettings gained a "method" alias for "network"; canonicalize it
      to "network" at inbound save time and in the form adapters/schema so a
      method-keyed config keeps its transport.
    
    - New root "env" config key is passed through xray.Config, compared in
      Equals, and forces a restart in the hot diff.
    
    - REALITY now defaults minClientVer to 26.3.27; update the form
      placeholder.
  • refactor(frontend): replace recharts with uPlot for charts
    Swap the Sparkline chart component (the only chart in the panel) from recharts to uPlot, keeping its public prop API identical so the three consumers (SystemHistoryModal, XrayMetricsModal, NodeHistoryPanel) are untouched. This drops recharts and 32 transitive deps (es-toolkit, victory-vendor, d3, redux, immer), shrinking the chart vendor chunk to ~51KB (22KB gzip).
    
    The uPlot port reimplements every recharts feature on canvas: gradient area fill, spline curves, up to three series, dashed horizontal grid, formatted axes, hover tooltip and marker, reference lines, and min/max extrema dots. Because canvas cannot read CSS variables, axis and ring colors are resolved via getComputedStyle and repainted on theme changes through a MutationObserver on the body class and documentElement data-theme.
    
    Also removes the es-toolkit/compat resolver shim from vite.config.js, which existed only for recharts, and swaps the manualChunks entry to vendor-uplot.
    
    Note: repaint with redraw(false); a bare uPlot redraw() re-runs _setScale and nulls the index-based x-scale, which collapsed the series to a flat, partial line.
  • refactor(frontend): replace axios with the native Fetch API
    Drop the axios (and qs) dependencies in favor of a native fetch wrapper.
    axios only ever handled same-origin JSON/form calls, a CSRF header, a 401
    redirect, and a 403-retry, all of which the platform now provides directly.
    
    - New src/api/http-init.ts (replaces axios-init.ts) reimplements the
      request/response interceptors on fetch: base-path prefixing,
      X-Requested-With, same-origin credentials, the CSRF token on unsafe
      methods, a single 403 retry with token refresh, and the 401
      redirect-and-latch. A small encodeForm() reproduces qs's
      arrayFormat:'repeat' encoding, so the request wire format is unchanged.
    - HttpUtil (src/utils/index.ts) keeps its public signatures and the Msg
      envelope, so the ~49 API call sites are untouched. HttpOptions is now
      hand-rolled instead of extending AxiosRequestConfig.
    - PanelUpdateModal drops its lone direct axios.get in favor of HttpUtil.get
      with { silent, timeout }.
    - Add tests for the fetch core (CSRF header, form/JSON/FormData bodies,
      base-path prefix, 403 retry, 401 redirect, tolerant body parse) and for
      HttpUtil's envelope unwrap / toast / error mapping; this logic was
      previously untested.
    - Remove the vendor-axios manualChunks branch and the qs type shim, and
      reword stale "axios" mentions in docs and route comments.
  • fix(logs): limit Xray log growth (#5840)
    * Limit Xray log growth
    
    * Apply suggestion from @github-actions[bot]
    
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
    
    * Apply suggestion from @github-actions[bot]
    
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
    
    ---------
    
    Co-authored-by: Mahyar Dana <dana.mahyar76@gmail.com>
    Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
  • docs: vendor the documentation site into the monorepo
    Fold the standalone 3x-ui-docs project (Next.js 16 + Fumadocs, deployed to
    docs.sanaei.dev) into docs/ so the panel and its documentation share a single
    source of truth, the way sing-box keeps its docs in-tree. The old repo becomes
    redundant and can be retired.
    
    - Import the full site under docs/ (app, components, content, lib, public,
      scripts, config). The self-contained pnpm project sits alongside the existing
      engineering notes with no filename collisions.
    - Re-point "Edit on GitHub" links from MHSanaei/3x-ui-docs to this repo's
      docs/content/docs path (docs/lib/shared.ts, docs/app/.../page.tsx).
    - Add docs-ci.yml and docs-deploy.yml under .github/workflows/, scoped to
      docs/** and run with working-directory: docs, since GitHub only runs
      workflows from the repo-root .github/. deploy-static.yml's GitHub Pages
      publish (CNAME docs.sanaei.dev) carries over unchanged.
    
    Follow-up (outside this commit): attach the docs.sanaei.dev custom domain to
    this repository's Pages (or set the Vercel project's root directory to docs),
    confirm the site is live from the monorepo, then delete MHSanaei/3x-ui-docs.
  • feat(mtproto): per-client ad-tags, management-API auth, and record secret sync
    Catch the panel up to the mtg-multi README (v1.14.0):
    
    - Each client can now carry its own 32-hex advertising tag overriding the
      inbound-level one. The tag lives on the client (settings JSON is the
      source of truth, clients.ad_tag is the UI projection), is rendered into
      the fork's [secret-ad-tags] section for active secrets only (mtg rejects
      a config whose override names an unknown secret), is pushed per entry
      through PUT /secrets, and is part of the reload fingerprint so a tag
      edit hot-applies without dropping connections.
    - The loopback management API can replace the whole secret set, so every
      mtg process now gets a random per-process api-token; the manager sends
      it as a bearer token on PUT /secrets and GET /stats and reuses it across
      config rewrites, because mtg reads the token only at startup.
    - Malformed tags are rejected at every save path and additionally dropped
      in InstanceFromInbound: one bad tag would otherwise fail the whole
      generated config and take every client of the inbound down with it.
    - SyncInbound never copied a re-keyed mtproto secret into the canonical
      clients table, so the clients page and subscription links kept serving
      the old secret, which mtg then rejects. It is now guarded-copied like
      the other credentials.
  • fix(mtproto): stop dropping connections on client/inbound edits; add live updates + ad-tag (#5838)
    * fix(mtproto): split the mtg fingerprint into structural and secrets parts
    
    A reordered clients array in the stored settings used to read as a config
    change because the fingerprint concatenated secrets in array order, and one
    opaque fingerprint could not tell a restart-worthy change (bind address,
    fronting, throttle) from a secret-set change a reload-capable mtg can absorb
    in place. Sort the secret pairs so order stops mattering, and split the value
    so the upcoming hot-reload path can decide between keeping, reloading, and
    restarting the process.
    
    * fix(mtproto): stop restarting mtg on every inbound edit
    
    Saving an mtproto inbound tore down and respawned its mtg sidecar even when
    nothing material changed, dropping every live Telegram connection: the update
    path pushed DelInbound+AddInbound, and Remove deletes the manager's map entry,
    so Ensure's fingerprint no-op gate could never fire. Route mtproto updates
    through a single Ensure call so an edit that leaves the generated TOML alone
    keeps the process, and only real config changes restart it.
    
    Capturing the pre-edit protocol also fixes a latent leak: changing an
    inbound's protocol away from mtproto never stopped the sidecar, because the
    snapshot handed to the runtime already carried the new protocol and the
    removal took the xray branch, leaving an orphaned mtg holding the port.
    
    An mtproto push failure no longer requests an xray restart - xray cannot fix
    the sidecar, and the 10s reconcile job self-heals it.
    
    The regression test fakes mtg by re-executing the test binary, counting
    spawns through a pid file: an unchanged save and a remark-only edit must keep
    the process, a re-keyed secret must restart it.
    
    * fix(mtproto): exclude depleted clients from the reconcile job to match the sync push
    
    The 10s reconcile job derived mtg secret sets from raw inbound settings while
    the interactive push filtered clients through buildRuntimeInboundForAPI, which
    drops client_traffics-disabled (depleted or expired) clients. The two paths
    therefore disagreed on the fingerprint - each disagreement one needless mtg
    restart dropping live connections - and worse, the job kept serving depleted
    clients' secrets indefinitely, so running out of traffic never actually cut an
    mtproto client's access.
    
    DesiredMtprotoInstances now builds the job's desired state with the same
    depletion overlay the push uses (one bulk client_traffics query), drops
    inbounds whose every secret is filtered away so their sidecar stops, and
    AddInbound pushes the filtered payload too so an imported inbound carrying
    disabled stats does not seed a fingerprint the next reconcile disagrees with.
    
    * feat(mtproto): hot-reload mtg secrets in place instead of restarting
    
    A client add, removal, re-key, or enable-toggle changes only the [secrets]
    section of the generated config, yet the panel could apply it only by killing
    and respawning the mtg sidecar, dropping every Telegram connection on that
    inbound. Split the ensure decision three ways: an identical config is a no-op,
    a secrets-only change rewrites the TOML on the same api port and asks mtg to
    hot-swap it via POST /reload, and a structural change (or a failed reload)
    falls back to the full stop-and-start.
    
    The reload endpoint is served by the mhsanaei/mtg-multi fork; against an older
    binary the POST 404s and the manager restarts exactly as before, so panel and
    binary upgrades stay order-independent.
    
    * feat(mtproto): apply single-client edits to the sidecar immediately
    
    Client CRUD on an mtproto inbound was a runtime no-op, so an add, delete,
    re-key, or enable-toggle only reached mtg on the next 10s reconcile. With the
    sidecar now able to hot-reload, push the change straight after the edit commits:
    applyLocalMtproto rebuilds the inbound's filtered client set and re-applies it,
    so a new client works within a moment (and, on a reload-capable binary, without
    disturbing the others) and deleting the last client stops the process.
    
    The three interactive single-client paths (add, update, delete) call it; bulk
    operations still ride the reconcile job, which converges to the same state.
    
    * chore(mtproto): pin mtg-multi to the mhsanaei fork v1.13.3
    
    The reload endpoint the panel now uses lives in the mhsanaei/mtg-multi fork, so
    point the source-build pin (DockerInit.sh + both release.yml matrices) at it and
    bump to v1.13.3. The install still produces the same mtg-multi binary name, so
    the mtg-<os>-<arch> rename and everything downstream are unchanged. Docs and the
    package comment note the hot-reload path and its restart fallback.
    
    * feat(mtproto): apply live secret updates via the management API and add ad-tag
    
    Two capabilities the mhsanaei/mtg-multi v1.13.3 fork exposes are now surfaced by
    the sidecar manager.
    
    Live updates go through PUT /secrets on the fork's management API instead of
    POST /reload: the panel already holds the whole desired set per inbound, so it
    sends secrets and the advertising tag as one JSON call that mtg applies
    atomically, keeping every unchanged connection and closing only removed or
    re-keyed ones. The config file is still written first so a restart or crash
    recovery reproduces the state, and any non-200 (an older binary, a refused
    connection) still falls back to a full restart.
    
    Per-inbound ad-tag adds an optional 32-hex Telegram advertising tag plus
    public-ipv4/public-ipv6 overrides. The ad-tag rides the reloadable secrets
    fingerprint, so changing it hot-applies without dropping connections; the public
    IPs are proxy-construction parameters and sit in the structural fingerprint, so a
    change there restarts the process. Empty public IPs are omitted so mtg
    auto-detects the reachable address.
    
    * feat(inbounds): expose the mtproto ad-tag and public IP in the inbound form
    
    Adds an Ad-tag field (validated as 32 hex characters) plus optional Public IPv4
    and Public IPv6 overrides to the MTProto inbound form, backed by the same-named
    settings the sidecar writes into the mtg config. The public IPs are optional —
    left blank, mtg auto-detects the reachable address the ad-tag middle proxy needs.
    English strings are added to every locale; the non-English ones carry the
    English text until translated and fall back to it meanwhile.
    
    * ci(mtproto): install mtg-multi from prebuilt release binaries
    
    The fork now publishes release archives for every platform we package, so
    download and unpack the matching mtg-multi-<ver>-<os>-<arch> binary instead of
    compiling it from source with go install. Faster builds and no toolchain step,
    and the archive's platform labels line up with our matrix; the produced
    mtg-<os>-<arch> filenames are unchanged.
    
    * i18n(mtproto): localize the ad-tag and public IP strings
    
    The six mtgAdTag*/mtgPublicIp* keys shipped with English text in every locale as
    a placeholder. Translate them into the twelve non-English locales (Arabic,
    Spanish, Persian, Indonesian, Japanese, Portuguese-BR, Russian, Turkish,
    Ukrainian, Vietnamese, and Simplified/Traditional Chinese); en-US is unchanged.
    
    * retired goreportcard.com
  • feat(mtproto): adopt dolonet/mtg-multi and make MTProto inbounds multi-client
    Replace the upstream 9seconds/mtg sidecar with the dolonet/mtg-multi fork so a single MTProto inbound can serve many per-user secrets. Each panel client is now one named FakeTLS secret in the fork's [secrets] section: clients are first-class (attach/detach, limits, expiry, per-client tg:// links) exactly like every other protocol, mirroring the WireGuard multi-client model. Per-client traffic and online status come from the fork's /stats JSON API (its Prometheus output has no per-user label), fed into the existing email-keyed client_traffics accumulator; an optional throttle caps concurrent connections. A one-time seeder converts each legacy single-secret inbound into a one-client inbound.
    
    The fork ships only linux/darwin amd64/arm64 binaries but is pure Go, so provisioning builds it from source for every supported platform (release.yml, DockerInit.sh) while keeping the panel-expected mtg-<os>-<arch> filename and the 'run' verb, so process.go is untouched. Also fixes a pre-existing update.sh gap that never renamed the mtg binary for armv6/armv7 updates.
  • docs: move architecture map into docs/ and refresh it against the live tree
    The architecture/code map previously lived in .claude/CLAUDE.md, which was
    gitignored (local-only) and auto-loaded into every agent session alongside
    the root CLAUDE.md. Track it in docs/architecture.md instead and reference
    it from CLAUDE.md so it is read on demand.
    
    While moving it, fact-check the whole map against the current tree:
    - add the missing internal/eventbus and internal/tunnelmonitor packages,
      the service/email subpackage, and util/wirecodec
    - document node mTLS (tls_client.go, node_mtls.go, setting_mtls.go) and the
      fourth TLS verify mode
    - add the Host, ClientExternalLink, NodeClientIp and ClientGlobalTraffic
      models plus their symptom-index rows
    - correct the cron table (check_cpu_usage is 1m not 10s; add
      check_memory_usage and free_os_memory), the middleware chain
      (MaxBodyBytes, ConfigEnvelope, CSRF) and the controller route prefixes
    - refresh the sub/ and service/ file listings, frontend pages (hosts/,
      index/), CI workflow list, and replace stale exact line counts with
      rounded sizes
  • feat(inbounds): add Real client IP presets to capture visitor IP behind CDN/relay
    Surface the existing sockopt knobs (acceptProxyProtocol, trustedXForwardedFor) as a guided 'Real client IP' preset selector in the inbound form, so the real visitor IP is recovered behind Cloudflare CDN or an L4 tunnel/relay instead of recording the intermediary address. Presets are mutually exclusive, warn on incompatible transports, and add tooltips, docs, and translations for all locales.
  • refactor: focused service files, leaf subpackages, and an internal/ layout (#5167)
    * refactor(service): split client.go into focused files
    
    client.go had grown to 4455 lines mixing ~10 responsibilities. Split it
    verbatim into cohesive same-package files (no behavior change):
    
      client.go            foundation: ClientService, ClientWithAttachments,
                           ClientCreatePayload, ErrClientNotInInbound, sqlInChunk
      client_locks.go      inbound mutation locks, delete tombstones, compactOrphans
      client_lookup.go     read-only lookups (GetByID, List, EffectiveFlow, ...)
      client_link.go       inbound association sync (SyncInbound, DetachInbound, ...)
      client_crud.go       single-client CRUD + validation + protocol defaults
      client_inbound_apply.go  low-level inbound-settings mutators + by-email setters
      client_bulk.go       bulk attach/detach/adjust/delete/create + DelDepleted
      client_traffic.go    traffic-reset paths
      client_groups.go     client group management
      client_paging.go     paged listing, filtering, sorting, summary
    
    Every declaration moved unchanged (verified: identical func/type/const/var
    signature set before vs after). Imports redistributed per file via goimports.
    go build ./..., go vet, and go test ./web/service/... all pass.
    
    * refactor(service): split inbound.go into focused files
    
    inbound.go was 4100 lines. Split it verbatim into cohesive same-package
    files (no behavior change):
    
      inbound.go             core inbound CRUD + InboundService (keeps pkg doc)
      inbound_protocol.go    protocol / stream capability helpers
      inbound_node.go        node/runtime/remote coordination + online tracking
      inbound_traffic.go     traffic accounting, reset, client stats
      inbound_client_ips.go  per-client IP tracking
      inbound_clients.go     client lookups within inbounds + copy-clients
      inbound_disable.go     auto-disable invalid inbounds/clients
      inbound_migration.go   DB migrations
      inbound_sublink.go     subscription link providers
      inbound_util.go        generic slice/string helpers
    
    Identical func/type/const/var signature set before vs after; package doc
    comment preserved on inbound.go. Imports redistributed via goimports.
    Build, vet, and go test ./web/service/... all pass.
    
    * refactor(service): split tgbot.go into focused files
    
    tgbot.go was 3738 lines dominated by a 1246-line answerCallback. Split it
    verbatim into cohesive same-package files (no behavior change):
    
      tgbot.go           lifecycle, bot setup, caches, small utils
      tgbot_router.go    incoming update / command / callback dispatch
      tgbot_send.go      outbound messaging primitives
      tgbot_client.go    client views, actions, subscription links
      tgbot_inbound.go   inbound listing / pickers
      tgbot_report.go    server usage, exhausted, online, backups, notifications
    
    Identical func/type/const/var signature set before vs after. Imports
    redistributed via goimports. Build, vet, and go test ./web/service/... pass.
    
    * refactor(client): dedupe single-field by-email setters
    
    ResetClientIpLimitByEmail, ResetClientExpiryTimeByEmail, and
    ResetClientTrafficLimitByEmail shared an identical ~50-line body that
    resolves the inbound by email, confirms the client exists, rewrites a
    single-client settings payload, and delegates to UpdateInboundClient.
    
    Extract that into applyClientFieldByEmail(inboundSvc, email, mutate) and
    reduce each setter to a 3-line wrapper. Behavior is unchanged: same checks
    and error strings, same single-client payload contract, same totalGB guard.
    
    SetClientTelegramUserID (resolves by traffic id, different error text) and
    ToggleClientEnableByEmail/SetClientEnableByEmail (different return shape and
    a pre-read of the old state) intentionally keep their own bodies.
    
    * refactor(service): extract panel/ subpackage
    
    Move the panel-administration leaf services out of the flat service
    package into web/service/panel/ (package panel):
    
      user.go         UserService (auth / 2FA / LDAP)
      panel.go        PanelService (restart / self-update) + version helpers
      panel_other.go  non-unix RestartPanel
      panel_unix.go   unix RestartPanel
      api_token.go    ApiTokenService
      websocket.go    WebSocketService
      panel_test.go   version/shellQuote unit tests
    
    These are leaves: they depend on core (SettingService, Release) but no
    core file references them, so the extraction creates no import cycle.
    Core references are now qualified (service.SettingService, service.Release);
    callers in main.go, web/web.go, and web/controller/* updated to panel.*.
    Build, vet, and go test ./web/... pass.
    
    * refactor(service): extract integration/ subpackage
    
    Move the external-provider integration leaves into web/service/integration/
    (package integration):
    
      warp.go        WarpService (Cloudflare WARP)
      nord.go        NordService (NordVPN)
      custom_geo.go  CustomGeoService (custom geo asset management)
      *_test.go      custom_geo / panel-proxy tests
    
    These depend on core (SettingService, ServerService, XraySettingService) but
    no core file references them. xray_setting.go stays in core because it calls
    the unexported SettingService.saveSetting. The shared isBlockedIP SSRF helper
    (used by core url_safety.go and by custom_geo) now has a small copy in each
    package rather than being exported. Core references qualified; callers in
    web/web.go, web/job/*, and web/controller/* updated to integration.*.
    Build, vet, and go test ./web/... pass.
    
    * refactor(service): extract tgbot/ subpackage
    
    Move the Telegram bot (6 files + test) into web/service/tgbot/ (package
    tgbot). It is a leaf: it embeds five core services (Inbound/Client/Setting/
    Server/Xray) and the core never references it, so no import cycle.
    
    To support the package boundary without changing behavior:
      - core exposes XrayProcess() *xray.Process so tgbot keeps calling the
        exact same running-process methods it used via the package-level `p`;
      - three core methods tgbot calls are exported: ClientService.checkIs-
        EnabledByEmail -> CheckIsEnabledByEmail, InboundService.getAllEmails ->
        GetAllEmails (callers updated in-package);
      - tgbot's embedded-field types and the few core type refs (Status,
        ClientCreatePayload, SanitizePublicHTTPURL) are now service-qualified.
    
    Callers in main.go, web/web.go, web/job/*, and web/controller/* updated to
    tgbot.*. Build, vet, and go test ./web/... pass.
    
    * refactor(service): extract outbound/ subpackage
    
    OutboundService (outbound.go) imports only neutral packages (config,
    database, model, xray) and its production code is referenced by no core or
    sibling service file — only by web/controller/xray_setting.go and
    web/job/xray_traffic_job.go. Move it to web/service/outbound/ (package
    outbound); no core qualification needed inside. Callers updated to outbound.*.
    
    The one coupling was a tiny pure test helper, outboundsContainTag, used by
    both outbound.go and the core outbound_subscription_test.go; it now has a
    small copy in that test file rather than being shared across the boundary.
    Build, vet, and go test ./web/... pass.
    
    * refactor(util): move wireguard into its own subpackage
    
    util/wireguard.go was the lone file of the root `util` package (24 lines,
    one exported func GenerateWireguardKeypair), while every other util concern
    lives in a focused subpackage (util/common, util/crypto, util/netsafe, ...).
    Move it to util/wireguard/ (package wireguard) for consistency; its only
    importer, web/service/integration/warp.go, is updated. The root `util`
    package no longer exists.
    
    * refactor(sub): drop redundant sub prefix from filenames
    
    Inside package sub the subXxx.go prefix just repeats the package name
    (like client_*.go did inside service). Rename for consistency; content and
    type names are unchanged:
    
      subController.go    -> controller.go
      subService.go       -> service.go
      subClashService.go  -> clash_service.go
      subJsonService.go   -> json_service.go
      (+ matching _test.go files)
    
    * refactor(controller): rename xui.go -> spa.go
    
    XUIController serves the panel's single-page-app shell; spa.go names that
    role plainly (the other controller files are domain-named). File rename only
    — the type stays XUIController. api_docs_test.go keys route base paths by
    filename, so its "xui.go" case is updated to "spa.go".
    
    * refactor: move backend packages under internal/
    
    Adopt the idiomatic Go application layout: the backend packages now live
    under internal/ (a boundary the toolchain enforces), signalling private
    implementation instead of a library-style flat root. No runtime behavior
    changes — only import paths and a few build/config paths move.
    
    Moved: config, database, logger, mtproto, sub, util, web, xray -> internal/.
    main.go stays at the repo root and tools/openapigen stays under tools/ (both
    still import internal/* because the internal rule keys off the module root).
    The module path github.com/mhsanaei/3x-ui/v3 is unchanged; 149 .go files had
    their import prefix rewritten to .../internal/<pkg>.
    
    Couplings the Go compiler can't see, updated to the new layout:
      - frontend i18n imports of web/translation (react.ts, setup.components.ts)
      - vite outDir + eslint/tsconfig ignore globs -> internal/web/dist
      - Dockerfile COPY paths for web/dist and web/translation
      - locale.go os.DirFS("web") disk fallback -> "internal/web"
      - .gitignore and ci.yml go:embed stub for internal/web/dist
      - api_docs_test.go repo-root relative walk (one level deeper)
      - tools/openapigen filesystem package paths; ApiTokenView repointed to the
        web/service/panel subpackage and codegen regenerated (clears a stale
        type the ci.yml codegen check was failing on)
    
    Verified: go build/vet/test (all packages), and frontend typecheck, lint,
    vitest (478 tests), and production build into internal/web/dist.
    
    * fix(config): keep test runs from writing logs into the source tree
    
    GetLogFolder() returns a CWD-relative "./log" on Windows. Under `go test`
    the working directory is each package's own folder, so InitLogger (called by
    tests in web/job, web/service, xray, web/websocket) created stray log/
    directories scattered through the source tree (e.g. internal/web/job/log/).
    
    Redirect to a shared temp folder when testing.Testing() reports a test run.
    Production behavior is unchanged: Windows still uses ./log next to the binary
    and Linux /var/log/x-ui. The log files were always gitignored (*.log) and
    never committed; this just stops the noise at the source.
    
    * docs: move subscription-template guide out of root into docs/
    
    sub_templates/ was a top-level folder holding only a README and no actual
    templates (3x-ui ships none by design), referenced nowhere and unlinked from
    any doc — it read like an empty placeholder cluttering the repo root.
    
    Move the guide to docs/custom-subscription-templates.md (a proper docs home),
    reword its intro to read as documentation rather than a folder note, link it
    from the Features list in README.md, and drop the empty sub_templates/ folder.
    
    * fix: update stale web/ path references after the internal/ move
    
    The internal/ migration rewrote Go import paths but left some references to
    the old top-level layout in docs, comments, and a few runtime disk paths.
    
    Functional (dev-mode only): the disk-serving fallbacks that read the Vite
    build from disk when running from source still pointed at web/dist/, which
    moved to internal/web/dist/ — so `os.DirFS`/`os.Stat`/`os.ReadFile` in
    internal/web/web.go and internal/sub/{sub,controller}.go are corrected.
    Production was unaffected (it serves the embedded FS; verified by the Docker
    build), but `go run` with a live frontend build silently fell back to embed.
    
    Docs/comments: frontend/README.md, CONTRIBUTING.md, the claude-issue-bot and
    release workflows, the openapigen -root help text, and assorted Go comments
    now reference internal/web, internal/database, internal/sub, internal/xray,
    etc. Package-name mentions (the "web" package), root paths (main.go,
    frontend/, install scripts, /etc/x-ui), routes (/panel/api/xray), and the
    historical "web/assets no longer exists" note were intentionally left as-is.
    
    * refactor(web): remove the legacy /xui -> /panel redirect middleware
    
    RedirectMiddleware existed only for backward compatibility with the old
    `/xui` URL scheme (301-redirecting /xui and /xui/API to /panel and
    /panel/api). That cutover was long ago, so drop the middleware, its
    registration in initRouter, and the now-inaccurate "URL redirection"
    mention in the middleware package doc. Old /xui URLs now 404 like any other
    unknown path. HTTPS auto-redirect and auth redirects are unrelated and stay.
    
    * build: fix .dockerignore for internal/ layout and exclude runtime dir
    
    - web/dist -> internal/web/dist: the embedded frontend moved under internal/,
      so the stale exclude no longer matched and the locally-built dist could be
      sent to the build context (the frontend stage rebuilds it fresh anyway).
    - exclude x-ui/: the local runtime directory (SQLite db, geo .dat files, xray
      binaries, certs — ~150MB) was being shipped into the build context for no
      reason. Verified the pattern excludes only the directory and still keeps
      x-ui.sh, which the Dockerfile copies to /usr/bin/x-ui.