Commit Graph
12 Commits
  • feat(geodata): add standard source presets (#6504)
    * feat(geodata): add standard source presets
    
    Expose the existing geofile allowlist to the Geodata editor so administrators can configure the supported scheduled downloads without copying URLs manually
    
    Tested with npm run test, npm run lint, npm run typecheck, npm run format:check, and go test ./internal/web/service ./internal/web/controller -run '^(TestStandardGeodataSources|TestGeodata)' -count=1
    
    Assisted-by: OpenCode:openai/gpt-5.6-terra (mostly)
    
    * fix(geodata): preserve custom source entries
    
    Add missing standard sources instead of replacing existing custom entries.
    
    Assisted-by: OpenCode:openai/gpt-5.6-terra (mostly)
  • 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(pia): add PIA login-and-add WireGuard outbounds (#6272)
    * feat(pia): add login-and-add WireGuard outbounds (#2)
    
    * fix(pia): keep PIA outbounds identifiable after the editor strips hostname
    
    The outbound editor drops piaHostname, so last-segment matching failed for hyphenated servers. Identify rows by the computed tag, re-encrypt stored tokens onto the active key, skip unusable catalog rows, and always release the catalog refresh latch.
  • feat(xray): browse geosite/geoip categories from routing rules (#6165)
    * feat(xray): browse geosite/geoip categories from routing rules
    
    Routing rules made you type category names from memory: nothing showed which
    categories a database actually contains, what is inside one, or whether a
    name resolves at all — a typo only surfaced when Xray refused the config.
    
    The panel now reads Xray's .dat databases itself and exposes them over four
    endpoints: databases in the asset folder, a database's categories, one page
    of a category's rules, and validation of the tokens already in a rule. The
    reader walks the protobuf wire format directly rather than decoding into Go
    structs, because a 10 MB geosite.dat holds well over a million domains and
    materialising them costs ~284 MB where streaming costs ~19 MB. Only the
    category index is cached, entry pages are scanned on demand, and scans are
    serialised, so twenty concurrent requests peak at 87 MB instead of 1 GB.
    A database's type is decided by its contents, not its file name, since
    custom .dat files are named freely.
    
    In the rule form, the source-IP, IP and domain fields gain a database button
    opening the browser: search over categories, a preview of what a category
    holds, and a multi-select that merges into the field. Plain domains, CIDRs
    and categories the panel does not know are left untouched; categories already
    present come back ticked, and unticking one removes it from the rule.
    
    * fix(xray): read geo databases through os.Root and match codes verbatim
    
    CodeQL flagged the database read as a path built from a user-supplied value,
    and it was right about the shape of it. The file name arrives in a request;
    resolve() rejects traversal and stats the file through an os.Root, but the
    read itself went through a joined path with os.ReadFile. That left the
    symlink defence incomplete: the stat could pass while the read followed a
    link planted — or swapped in — afterwards.
    
    Reads now go through the same root, so a request-supplied name never becomes
    a path this code resolves on its own, and the size limit is applied to the
    opened file rather than to a separate stat of it.
    
    Lookup no longer trims the category code either. It backs the routing-token
    validator, and the core matches codes verbatim: "geosite: cn" will not start
    Xray, so repairing that space here hid exactly the typo the validator exists
    to report.
    
    * fix(xray): address review findings on the geo category browser
    
    Asset folder. The browser read config.GetBinFolderPath() unconditionally,
    but the core honours a preset XRAY_LOCATION_ASSET and only falls back to the
    bin folder (ensureXrayAssetLocation). On an install pointing at a shared
    asset directory the panel listed an empty folder and reported perfectly
    valid geosite:/geoip: tokens as missing — the validator warning about a
    correct config. The directory is now resolved with the core's precedence.
    
    Paging. Serving one page read and rescanned the whole database, so walking
    category-ads-all re-read it per page. The index now records each category's
    byte range and a page reads only that record through the os.Root handle,
    with the current category's records held for the duration of a paging
    session. Profiling that also showed the real cost was not the read but the
    slice of payload pointers built per call — a category holds a hundred
    thousand of them — so records are now walked with a callback instead.
    Ten pages over category-ads-all: 239 MB allocated, now 4.3 MB.
    
    Cached failures. Any error from reading a file was latched under the file's
    size+mtime, so a transient ENOMEM or EMFILE marked a healthy database as
    damaged until it changed on disk. Only deterministic failures are cached.
    
    Wrong kind. A geoip: token typed into a domain field parsed as a plain
    domain and was waved through, though the core cannot resolve it as one. It
    is now reported, with its own reason and wording.
    
    Frontend. The category filter fed the query key on every keystroke, so each
    character triggered a request that re-scanned the database; it is debounced
    now. GeoTokenInput accepts and forwards a ref, so React Hook Form can focus
    these three fields on a validation error again. A failed validation shows
    that it failed instead of rendering the same empty state as "no issues".
    
    Also drops an unreachable branch in the token-count guard and corrects the
    categories endpoint docs, where limit is unbounded by default.
    
    ---------
    
    Co-authored-by: STRENCH0 <17428017+STRENCH0@users.noreply.github.com>
  • Bug-label issue sweep: 16 fixes (#6083)
    * fix(xray): block private-range egress in default freedom finalRules (#6037)
    
    With domainStrategy AsIs the router never resolves domains, so a domain
    with a private A record (e.g. 127-0-0-1.nip.io) sails past the
    geoip:private routing block and freedom's allow-all finalRules let it
    reach loopback services such as the xray gRPC API and metrics listener.
    
    Prepend a block rule for geoip:private to the default template and add
    the FreedomFinalRulesPrivateEgressBlock seeder so existing installs
    still carrying the stock allow-only (or legacy private-only-allow)
    finalRules are upgraded in place; customized rules are left untouched.
    
    * fix(sub): version-gate unencrypted-outbound drops in outbound subscriptions (#6033)
    
    Commit d38c912d taught CheckXrayConfig to keep unencrypted vless/trojan
    outbounds when the running core predates the v26.7.11 rejection, but
    filterOutboundsRejectedByCore still consulted the embedded validator
    unconditionally, so outbound subscriptions kept silently dropping those
    outbounds even on downgraded cores.
    
    Apply the same shouldSkipLegacyUnencryptedOutboundRejection gate when
    filtering fetched subscription outbounds.
    
    * fix(xray): resolve geodata assets before building outbound configs (#5928)
    
    Saving routing or template settings validates each outbound through the
    embedded config loader, and a freedom outbound whose finalRules
    reference geoip:private opens geoip.dat during that build. Unlike
    ApplyRoutingConfig, ValidateOutboundConfig and AddOutbound never pointed
    the in-process loader at the bin folder, so xray-core resolved the file
    relative to the panel executable and saving failed with
    'stat /usr/local/x-ui/geoip.dat: no such file or directory'.
    
    Call ensureXrayAssetLocation before both build paths.
    
    * fix(api): use a real i18n key in the client get handler (#5911)
    
    The client fetch endpoint localized its error prefix with the bare key
    'get', which exists in no translation file, so every lookup of a deleted
    client's email logged 'message "get" not found in language ...' noise
    alongside the expected record-not-found warning. Reuse the same
    pages.inbounds.toasts.obtain key the sibling list handler uses.
    
    * fix(sub): carry host record Host header and path into Clash/JSON output (#5944)
    
    The raw-link path overrides the host/path share params from a Host
    record via applyEndpointHostPath, but the Clash and JSON renderers read
    the transport settings object, which applyHostStreamOverrides never
    touched — so a Host record's WebSocket Host header (and path) silently
    vanished from Clash/Mihomo and JSON subscriptions whenever the inbound's
    own ws settings left them empty.
    
    Inject hostHeader/path into the ws/httpupgrade/xhttp settings of the
    per-host stream, mirroring the raw-link override.
    
    * fix(metrics): accept Unicode outbound tags in the observatory (#5972)
    
    The observatory validator whitelisted ASCII word characters, so any
    outbound whose tag carries a flag emoji or other non-ASCII text was
    silently dropped from the metrics snapshot, delay history, and health
    notifications. The history store is an in-process map, so the strict
    charset bought nothing.
    
    Validate tags as non-empty, bounded, control-character-free UTF-8
    instead, keeping spaces and emoji while still rejecting garbage input on
    the query path.
    
    * fix(database): default sqlite to WAL to stop background-job lock storms (#6057, #6068)
    
    With journal_mode=DELETE every write serializes the whole database and
    blocks readers, so under normal multi-job load (traffic sampling, node
    sync, mtproto reconcile) transactions regularly outwaited the 10s busy
    timeout and jobs failed with 'database is locked'.
    
    Move to WAL by default: readers no longer block writers and vice versa,
    which removes the observed contention while writer-writer access still
    serializes safely. The single-file-at-rest property is preserved where
    it matters — Checkpoint() now issues wal_checkpoint(TRUNCATE), so panel
    and Telegram backups read a complete main file, and sqlite folds the WAL
    back into the db on clean shutdown. XUI_DB_JOURNAL_MODE=DELETE restores
    the previous behavior for setups that copy the live file directly.
    
    * fix(database): strip finalmask.tcp from REALITY inbounds on upgrade (#6038)
    
    validateFinalMaskRealityCombo blocks saving finalmask.tcp together with
    REALITY because that combination crashes Xray-core 26.7.11 on the first
    connection (XTLS/Xray-core#6453), but it only runs on add/update. An
    inbound saved before the validator existed sailed through the upgrade
    untouched and took the core down at boot.
    
    Add the InboundRealityFinalmaskTcpStrip seeder: one-time scan that
    removes finalmask.tcp from REALITY inbounds (other finalmask transports
    survive), so upgraded panels start cleanly.
    
    * fix(xray): stop deleting hand-written direct routing rules on save (#6056)
    
    The DNS allow-rule sync recognized 'its' rules purely by shape
    (type=field, ip, port, outboundTag=direct, nothing else), so any manual
    rule of that shape — e.g. routing a LAN CIDR to a NAS port over direct —
    was silently stripped on every settings save.
    
    Mark managed rules with ruleTag=xui-dns-allow (round-tripped untouched
    by both xray-core and the Routing tab editor) and only strip rules that
    carry the tag. Untagged legacy managed rules are adopted when their
    exact ip-set/port matches a currently configured private DNS endpoint;
    anything else is left alone. A stale pre-tag managed rule whose DNS
    server was removed now lingers until deleted manually — the safe side of
    the trade against eating user rules.
    
    * fix(clients): resolve email lookups through client_inbounds after a move (#6059)
    
    GetClientInboundByEmail trusted the client_traffics.inbound_id pointer
    whenever that inbound still existed, but a client moved between inbounds
    leaves the row pointing at its old (still existing) inbound. The lookup
    then searched the wrong inbound's clients and failed with 'Client Not
    Found In Inbound For Email', which broke the Telegram bot's link and QR
    generation for moved clients.
    
    When the pointed-at inbound no longer carries the email, re-resolve
    through the authoritative client_inbounds link to the inbound that
    actually hosts the client.
    
    * fix(nodes): replicate inbound fallbacks to nodes (#5963)
    
    Fallbacks live in the inbound_fallbacks table and were only merged into
    settings by the master's local config builder; the runtime inbound
    pushed to nodes rebuilt settings without them, and the reconcile job
    additionally fingerprinted the raw DB row, so fallback edits neither
    reached nodes nor triggered a re-push.
    
    Inject settings.fallbacks in buildRuntimeInboundForAPI (mirroring the
    local builder, gated on inboundCanHostFallbacks) and make ReconcileNode
    push and fingerprint that same runtime-built payload, aligning the
    interactive and reconcile paths.
    
    * fix(database): survive PostgreSQL outages without a runaway restart loop (#6023)
    
    A PostgreSQL that was down or still starting made InitDB fail instantly;
    the process exited with a generic startup error and systemd restarted it
    every 5s forever, flooding the journal.
    
    Retry the initial postgres connection with backoff (~70s total) and log
    the real driver error on every attempt, and cap the systemd units with
    StartLimitIntervalSec/StartLimitBurst so a persistently unreachable
    database stops the unit instead of looping indefinitely.
    
    * fix(xray): force a full restart when REALITY stream settings change (#6010)
    
    A changed inbound is normally hot-swapped over gRPC as RemoveInbound +
    AddInbound, but xray-core does not reliably rebuild a REALITY listener's
    authenticator on a runtime re-add — key or shortId edits appeared
    applied yet clients kept authenticating against the old parameters until
    someone restarted the core manually, on nodes in particular.
    
    Treat any non-client change to an inbound that uses (or starts using)
    REALITY as not hot-appliable so the panel restarts the core instead.
    Client-only edits on REALITY inbounds keep flowing through the per-user
    AlterInbound path and still avoid restarts.
    
    * feat(sub): allow insecure TLS for outbound subscription fetches (#6067)
    
    An outbound subscription served over HTTPS with a self-signed or
    private-CA certificate could never be fetched: the fetch client had no
    TLS options, so refreshes died with 'x509: certificate signed by unknown
    authority' and there was nothing the admin could toggle.
    
    Add a per-subscription 'Allow insecure' switch (persisted as
    allow_insecure, default off) that sets InsecureSkipVerify on the fetch
    transport — including when the fetch is routed through the panel egress
    proxy. The SSRF-guarded dialer and redirect re-validation stay in force
    either way.
    
    * fix(reality): send PROXY protocol header in the target scanner when xver is set (#6082)
    
    The REALITY target scanner always probed with a plain TLS handshake, so
    a target fronted by an Nginx listener that requires the PROXY protocol
    (matching the inbound's xver>=1) reset the connection and the panel
    reported a false 'TLS handshake failed'.
    
    Thread the inbound's xver into the scan request and, when it is >=1,
    lead with the matching PROXY protocol header (v1 for xver 1, binary v2
    for xver 2) built from the dialed connection's own address pair. Batch
    candidate scans against public sites are unaffected (xver 0).
    
    * fix(frontend): default sockopt fields when editing a stored inbound (#5956)
    
    Opening an existing inbound ran rawInboundToFormValues over the raw DB
    row, and only xhttpSettings was re-parsed through its Zod schema to fill
    defaults. A sockopt object saved before the TProxy control existed has
    no tproxy key, so the Select rendered blank; picking Off didn't help
    because the wire normalizer drops tproxy=off, recreating the missing
    key on the next edit.
    
    Re-parse streamSettings.sockopt through SockoptStreamSettingsSchema on
    load, mirroring the xhttpSettings handling, so absent keys (tproxy,
    tcpcongestion, …) get their schema defaults every time the form opens.
  • 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.
  • feat(outbound): add real-delay connection test mode
    The HTTP probe reports the warm per-request round-trip, which reads
    lower than the delay figure client apps show for the same server. Add a
    third "real" test mode that reuses the temp-instance HTTP probe but
    reports the cold request's full elapsed time - tunnel establishment
    included - and skips the warm request. UDP-transport outbounds forced
    out of the TCP lane still report "http"; in real mode they report
    "real". The mode joins the TCP/HTTP toggle on the outbounds tab, with
    the label translated in all 13 locales.
  • refactor(frontend): move form-item hints from extra to tooltip
    Switch reality target, node options, and WARP auto-update-IP hints from
    inline extra text to label tooltips for a cleaner form layout.
  • feat(outbound): batched connection tester with direct timed HTTP probes
    Replace the per-outbound burstObservatory polling (one temp xray spawn +
    up to 15s of /debug/vars polling per outbound, serialised) with one
    shared temp xray instance per batch: every tested outbound gets its own
    loopback SOCKS inbound plus an inboundTag->outboundTag routing rule, and
    the panel times a real HTTP request through each one in parallel. The
    probe returns as soon as the response lands and records the HTTP status
    plus an httptrace breakdown (proxy connect / TLS via outbound / first
    byte) shown in the result popover.
    
    New POST /panel/api/xray/testOutbounds endpoint (array in, results in
    input order, max 50); the legacy /testOutbound endpoint now delegates to
    the same engine. Test All chunks HTTP probes 16 per request, and a batch
    whose shared process never comes up (one structurally-broken outbound
    poisons the config) retries each item in an isolated instance so the
    broken outbound reports xray's real error while the rest still test.
  • feat: apply inbound/outbound/routing changes live via Xray gRPC API
    Add a hot-apply layer that computes a diff between the old and new
    generated config and applies only the changed parts through the Xray
    gRPC HandlerService and RoutingService, avoiding a full process restart
    whenever possible. A restart is still performed when sections that have
    no reload API (log, dns, policy, observatory, ...) actually change.
    
    Key additions:
    - internal/xray/hot_diff.go: ComputeHotDiff with canonical-JSON
      comparison (sorted keys, null=absent, full number precision) so UI
      reformatting never triggers a spurious restart
    - internal/xray/api.go: AddOutbound/DelOutbound, ApplyRoutingConfig,
      GetBalancerInfo, SetBalancerTarget, TestRoute gRPC wrappers
    - internal/web/service/xray.go: tryHotApply, ensureAPIServices,
      GetBalancersStatus, OverrideBalancer, TestRoute service methods
    - internal/web/controller/xray_setting.go: balancerStatus,
      balancerOverride, routeTest API endpoints
    - frontend: BalancersTab live-status/override columns, RouteTester
      component, Restart button removed (Save now hot-applies)
    - balancer-helpers.ts: syncObservatories never creates observatory
      sections for random/roundRobin balancers (no reload API → restart)
    - i18n: balancerLive/Override/routeTester keys added to all 13 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.