Commit Graph
36 Commits
  • docs(api): document WireGuard and mtproto secret generation on clients/add (#6282)
    * docs(api): document WireGuard and mtproto secret generation on clients/add
    
    The POST /panel/api/clients/add summary enumerated the protocols whose
    secrets the server fills in, and that list stopped being complete when
    WireGuard gained per-client keys and mtproto gained a FakeTLS secret.
    Read literally it says the endpoint is unusable for WireGuard without a
    hand-made keypair and address, while defaultWireguardClients in fact
    generates the keypair, derives the public key from a supplied private
    one, and allocates a free /32.
    
    Rather than extend an enumeration that goes stale on every new protocol,
    the summary now states the rule alone and the per-protocol detail moves
    into the operation description - a field Endpoint already declares and
    build-openapi.mjs already maps, but that no endpoint used until now.
    Swagger UI in the panel and the docs site both render it.
    
    The attach operation gets the rule added for #5785 that nothing
    documented: a client already carrying allowedIPs brings them into the
    new inbound instead of being given a fresh address, and is rejected when
    another client of that inbound holds it.
    
    Closes #6276
    
    * docs(api): correct the clients/add generation rules flagged in review
    
    Three claims in the new description did not hold:
    
    Shadowsocks does not keep every supplied password. fillProtocolDefaults
    regenerates it when validShadowsocksClientKey rejects it, which on a
    2022-blake3-* inbound means any password that does not base64-decode to
    16 or 32 bytes - the call still returns success, so the caller has to
    read the client back to notice. Split off from Trojan and spelled out.
    
    The UUID is not always fresh: re-adding an email that already exists,
    with the stored subId, reuses the stored id, password, auth and secret
    so the identity stays in sync across its inbounds. That branch was
    documented nowhere.
    
    The mtproto secret falls back to www.cloudflare.com when the inbound
    carries no fakeTlsDomain.
  • feat(clients): allow removing a single HWID device (#6265)
    * feat(clients): allow removing a single HWID device
    
    Only "list" and "clear all" existed for registered HWID devices, so
    freeing one slot under a client's HWID limit meant clearing every
    device and waiting for the ones you kept to re-register. Adds a
    per-device delete: DELETE /panel/api/clients/hwids/:email/:id, scoped
    to the client's own sub_id (device ids are a global auto-increment,
    not per-subID, so this also prevents deleting another client's
    device), plus a delete button next to each device in the existing
    HWID modal.
    
    Addresses MHSanaei/3x-ui#6245.
    
    * feat(clients): surface HWID limit + device log in the client info card
    
    Mirrors the existing IP-limit row/eye-icon-modal pattern that's
    already in this card. The HWID devices modal reuses the same
    list/clear-all/per-device-delete UI already shipped for the edit
    form's own HWID modal, so a device can be removed without opening the
    edit form at all.
    
    * i18n: add HWID single-delete strings to all 13 locales
    
    deleteHwid/deleteHwidConfirm/hwidDeleted were only added to en-US and
    ru-RU in the previous commit; backfilling the other 11 locales the
    project's own translation set covers.
    
    * fix(clients): address automated review of HWID single-delete PR
    
    - ClientInfoModal: use the existing dateLabel() helper (Jalali-aware)
      for HWID first/last-seen instead of a raw dayjs format, matching
      every other timestamp in the same modal.
    - Add okText/cancelText to the delete-device Popconfirm in both
      ClientInfoModal and ClientFormModal so all 13 locales get a
      translated confirm dialog instead of Antd's English default.
    - deleteHwid controller: stop reusing the success toast key on both
      error paths, which rendered a red "Update successful" toast on a
      real (not just theoretical) failure such as a stale HWID modal.
    - Trim DeleteClientHwid's doc comment to the repo's 2-line cap and
      correct it: deletion is scoped by sub_id, which can span more than
      one ClientRecord, not strictly "this client only".
    - Add TestDeleteClientHwid covering cross-sub_id id rejection, unknown
      id rejection, and a real successful delete.
    
    * chore: retrigger CI (previous run stuck installing Playwright Chromium)
    
    * fix(clients): address the arbiter review on the HWID single-delete PR
    
    - Extract the HWID device list into a shared frontend/src/lib/clients/
      hwid-log.ts type/normalizer, a shared useClientHwids hook, and a
      shared ClientHwidListModal component, mirroring the existing IP-log
      pattern. ClientInfoModal and ClientFormModal both render the same
      component now, so the two copies can no longer drift the way they
      already had (different date formatting, different tag styles).
    - Add a Popconfirm to the HWID "Clear all" button (previously
      unconfirmed, unlike the per-device delete right next to it) — closes
      the confirm/no-confirm asymmetry the review flagged as the main risk.
    - Sync docs/public/openapi.json with the two hwids paths and regenerate
      clients.mdx. Scoped to just those two paths rather than a full copy
      from frontend/public/openapi.json: the docs copy is far enough behind
      on unrelated paths (a host-group API rename) that a full sync breaks
      the Next.js build on locale pages referencing the old shape — out of
      scope for this PR.
    
    * fix(clients): trim HWID list comment blocks to 2 lines
    
    Repo convention caps comment blocks at 2 lines; both were 1 line over.
    
    * chore: retrigger CI
    
    build (arm64) and build (armv6) failed on a transient Go module proxy
    network error (INTERNAL_ERROR stream reset), unrelated to this PR's
    changes.
  • chore(docs): update dependencies and adapt to zbsearch 4
    fumadocs-core 16.14.5 switched its search engine from Orama to zbsearch 4,
    so the panel docs follow it up to the same major.
    
    zbsearch 4 still rejects locale codes as tokenizer languages ("en" throws,
    only "english" is accepted), so the custom search dialog that forces an
    English index stays necessary — verified by loading the built static index
    for all four locales and searching it through fumadocs' own client.
    
    Around that:
    - use `staticClient`, as `oramaStaticClient` is now a deprecated alias
    - drop @orama/orama, which nothing depends on or imports any more
    - correct the two comments that still described Orama and pointed at its
      docs and tokenizer package, one of them suggesting a language zbsearch
      does not have
    - restore the corepack integrity hash on `packageManager`, which CI reads
      through pnpm/action-setup
    - prune minimumReleaseAgeExclude entries for versions no longer installed
    
    The API reference MDX changes are serialization-only: fumadocs-openapi
    11.2.4 emits plain scalars where it used folded ones. Parsed frontmatter
    and page bodies are unchanged.
  • Move to TypeScript 7 and the oxc toolchain (oxlint + oxfmt) (#6262)
    * chore(frontend,docs): move to TypeScript 7 and replace ESLint with oxlint
    
    TypeScript 7 is the native Go port and ships no programmatic compiler
    API, so typescript-eslint cannot run at all: it peer-pins
    typescript >=4.8.4 <6.1.0 (canary too) and hard-crashes with
    "typescript-eslint does not support TS 7.0". Upstream support is
    tracked in typescript-eslint#10940 and targets TS >=7.1.
    
    Rather than wait, or carry Microsoft's side-by-side alias (which keeps
    a second TS 6 install alive purely to feed the linter), both projects
    move to oxlint, which never depended on the TypeScript API.
    
    Typecheck drops from ~9.7s to ~2.2s and 167 packages leave frontend/.
    
    oxlint has no no-restricted-syntax, so the #6121/#6127 cleared-
    InputNumber guard is reimplemented as a JS plugin in
    frontend/tools/oxlint/. It was verified to still fire in
    pages/settings/** and pages/xray/** and to stay exempt in *Modal.tsx.
    
    The type-aware @deprecated sweep survives too, as
    `npm run lint:deprecated`: oxlint's type-aware mode runs on
    oxlint-tsgolint, which drives the TS 7 typescript-go checker, so the
    TS 7 move is what makes it possible.
    
    Behaviour is preserved rather than tightened. jsx-a11y/prefer-tag-over-role
    is off in both configs because it was never part of the recommended sets
    ESLint actually ran, and oxlint honours the existing eslint-disable
    comments, so no source churn was needed.
    
    Two real fixes fell out of the stricter linting:
    - outbound-link-parser.test.ts used `out?.streamSettings` behind an `as`
      cast, which hid the optional chain from ESLint and would throw on a
      null parse; the rest of the file already used `out!`.
    - InputAddon's conditional role/tabIndex/onKeyDown is genuinely
      accessible but oxlint cannot evaluate it, so it gets a scoped disable.
    
    * chore(docs): replace Prettier with oxfmt
    
    oxfmt is the oxc project's Prettier-compatible formatter, so this pairs
    with the oxlint move and drops the last JS-based tool from the docs
    toolchain.
    
    The swap is behaviour-preserving. Running Prettier and oxfmt over the
    same files, with the existing .prettierrc.json settings migrated via
    `oxfmt --migrate=prettier`, produces byte-identical output on every
    file. (Comparing them outside the project directory is misleading:
    Prettier silently falls back to its defaults when it cannot find its
    config, which looks like a mismatch but is not one.)
    
    The 18 files reformatted here were already failing `pnpm format:check`
    before this change — Prettier wanted the exact same edits. The check is
    not part of docs-ci.yml, which is why the drift went unnoticed.
    
    .prettierignore becomes ignorePatterns in .oxfmtrc.json, keeping the
    deliberate MDX exclusion: reflowing MDX prose merges headings into
    paragraphs and collapses lists inside Steps/Callout components. Both
    that and the generated fumadocs-openapi reference output were verified
    untouched.
    
    oxfmt is pinned to 0.63.0 rather than latest. pnpm 11's built-in
    minimumReleaseAge policy rejects same-day releases, and 0.64.0 would
    have made pnpm silently append 20 waiver lines to pnpm-workspace.yaml.
    
    * style(frontend): adopt oxfmt and format src
    
    frontend/ has never had a formatter, so this reformats 344 of 497 files
    in src/. The change is purely whitespace, quoting and line wrapping —
    no logic is touched. It is kept in its own commit so it does not bury
    the TypeScript 7 / oxlint migration or the git blame for the code
    itself.
    
    Settings match docs/ and the code as it was already written: single
    quotes, semicolons, trailing commas, 2-space indent, 100 columns. That
    was measured rather than assumed — src/ was already uniformly
    single-quoted and 2-space indented, with p90 line length at 75.
    
    Formatting is scoped to src/ (mirroring `oxlint src`) and
    .oxfmtrc.json ignores src/generated. Both matter: `make gen-check`
    compares src/generated and public/openapi.json, and
    `make msw-worker-check` byte-compares public/mockServiceWorker.js
    against the installed MSW runtime, so reformatting any of them breaks
    the gate.
    
    Reflowing also moves `eslint-disable-next-line` comments off the line
    they guard, which broke two suppressions that had been silently
    correct before:
    - clone-inbound-modal.test.tsx: the object literal became multi-line,
      leaving `} as any;` four lines below its no-explicit-any disable.
    - ClientsPage.tsx: the useMemo dependency array moved onto its own
      line, out from under its exhaustive-deps disable.
    Both comments were relocated onto the line they actually guard, and
    verified to still suppress by removing them and watching the errors
    return.
    
    * ci: enforce formatting in CI and make verify
    
    Adding oxfmt in the previous two commits gave both projects a formatter
    but nothing that checks it, which is how docs/ had already drifted to 18
    unformatted files: docs-ci.yml runs typecheck, lint, test and build, but
    never format:check, so Prettier's complaints were only ever visible to
    whoever ran it by hand.
    
    Wire `format:check` into the frontend job in ci.yml and the docs job in
    docs-ci.yml, and add a `format-check` target to `make verify` so the
    local gate keeps mirroring CI as the Makefile header promises.
    
    Verified the step actually bites rather than passing vacuously: adding
    a badly formatted line to a source file in each project makes both
    `make format-check` and `pnpm format:check` fail, and reverting it makes
    them pass again.
    
    No workflow referenced ESLint or Prettier by name — they all invoke the
    package scripts — so the tooling swap needed no other CI changes.
    
    * ci: trigger CI on Makefile changes
    
    The path filters listed **.go, go.mod, go.sum, frontend/**, .nvmrc and
    ci.yml itself, but not the Makefile — so a change to the canonical task
    runner that ci.yml is meant to mirror could land without any job
    running. The previous commit, which edits both, only triggers because
    it happens to touch ci.yml too.
    
    * fix(frontend): replace deprecated Ant Design 6 APIs in the geo components
    
    `npm run lint:deprecated` reported five uses of props Ant Design 6 has
    deprecated. All five are gone, and the matching runtime warnings no
    longer appear in the test output.
    
    Tag `bordered={false}` becomes `variant="filled"` and Space `direction`
    becomes `orientation`; both are the one-to-one replacements named in
    antd's own deprecation messages, and `direction`/`orientation` share the
    same Orientation type.
    
    Input `addonAfter` is the one that is not a rename. It becomes a
    `Space.Compact block` wrapping the Input and the browse Button, which is
    antd's documented migration. `block` keeps the field filling its form
    row as the addon did. Note this is a deliberate visual change: the
    button used to be a borderless `type="text"` icon sitting inside the
    addon's grey box, and is now a regular button whose border joins the
    input. The tooltip, aria-label, ref, id and onBlur wiring are unchanged,
    so the react-hook-form binding in RuleFormModal and the existing tests
    still address it the same way.
    
    Only these five were deprecated. The other `bordered` props in the tree
    sit on QRCode, Table, Descriptions and Alert, where the prop is not
    deprecated, and these were the only two Space `direction` uses in the
    codebase.
    
    * fix(frontend): restore lint rules lost in the oxlint migration, and test the guard
    
    Addresses the review on #6262.
    
    The frontend config re-enabled only no-explicit-any and no-unused-vars
    and left the rest of tseslint's recommended set to oxlint's correctness
    category. It does not cover all of it. Confirmed by linting one probe
    file against both configs: docs/ (which enumerates the rules) reports
    all nine, frontend/ reported four. So ban-ts-comment,
    no-empty-object-type, no-namespace, no-require-imports and
    no-unsafe-function-type had silently stopped being enforced — a `//
    @ts-ignore` or a `namespace` block would have landed unflagged. The ten
    rules are now mirrored from docs/.oxlintrc.json, and src/ still passes.
    
    The #6121/#6127 guard was 57 lines of hand-written AST walking with no
    test. It now has one: fixtures for the three banned shapes plus an
    onNumber()-wrapped control, asserting the rule fires three times and
    that .oxlintrc.json still wires it to the right paths. Verified it fails
    for the right reason by making walk() enumerate nothing, which is the
    silent-death mode the review described — the traversal depends on
    Object.keys() seeing AST children as own enumerable properties.
    
    The fixtures deliberately violate the rule, so their oxlint config is
    named guard.oxlintrc.json rather than .oxlintrc.json: oxlint discovers
    nested configs by directory, which would otherwise turn the fixtures
    into three lint errors. The test passes it explicitly with -c.
    
    Also from the review:
    - lint and format now cover tools/ as well as src/, so the one piece of
      hand-written lint logic in the repo is no longer the least covered
      file in it.
    - lint-staged runs oxfmt before oxlint --fix. Formatting became a hard
      CI gate in this PR while the hook only ran the linter, so a commit
      could pass the hook and fail CI on formatting alone.
    - .oxfmtrc.json ignores public/, so the artefacts that make gen-check
      and make msw-worker-check byte-compare stay safe even if oxfmt is
      invoked without a path argument.
    - The MDX and generated-reference rationales that .prettierignore
      carried are back as comments in docs/.oxfmtrc.json — oxlint and oxfmt
      both accept JSONC, so relocating them was unnecessary.
    
    Not applied: the review also suggested restoring ../internal/web/dist to
    the ignore lists. Both tools reject `..` patterns outright ("patterns
    are resolved within the config file's directory"), and being outside
    frontend/ it is unreachable anyway.
  • feat(web): add network-only PWA installability (#6190)
    * feat(web): add network-only PWA installability
    
    Serve the manifest, registration script, network-only service worker, and icons under the runtime web base path so panels remain installable at arbitrary configured URLs.
    
    This does not add offline caching or change panel, API, database, or Xray behavior.
    
    * chore(docs): remove development planning notes
    
    Keep the pull request focused on the PWA implementation, tests, and user-facing verification documentation.
    
    * feat(web): adopt the 3X logo PWA icon set from #1865
    
    Replace the two placeholder SVG icons with the six-size PNG set
    (16/24/32/64/192/512) contributed by @Incognito-Coder in PR #1865.
    The PNGs have transparent rounded corners, so the manifest entries
    drop the maskable purpose claim and rely on the default any.
    
    ---------
    
    Co-authored-by: korsun009 <277924786+korsun009@users.noreply.github.com>
    Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
  • feat(inbounds): add a narrow endpoint for subscription sort order (#6179)
    * feat(inbounds): add a narrow endpoint for subscription sort order
    
    Changing an inbound's position in subscription output currently goes through
    /update/:id, which takes a whole inbound: the caller has to send settings and
    the entire client list back, and whatever it read before the edit is what gets
    written. Two people reordering and editing clients in the same inbound race on
    one blob, and the reorder wins by overwriting.
    
    Mirror the existing /setEnable/:id shape. The handler takes only the index and
    the service reads the stored inbound, so nothing in the request can reach the
    settings JSON. Node-owned inbounds are marked dirty in the same transaction and
    pushed through the existing runtime update.
    
    * fix(nodes): scope sub sort index updates
    
    ---------
    
    Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
  • 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>
  • fix(nodes): apply a rotated master mTLS certificate without restarting the panel (#6194)
    * fix(mtls): invalidate pooled clients after credential rotation
    
    * fix(mtls): make connection reload read-only
    
    ---------
    
    Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
  • feat(api): scoped, optionally expiring API tokens (#6201)
    * security(api): add scoped expiring API tokens
    
    * security(api): make scoped token lifecycle enforceable
    
    ---------
    
    Co-authored-by: n0ctal <293235942+n0ctal@users.noreply.github.com>
  • chore(docs): bump docs dependencies
    Update fumadocs-core/mdx/ui to 16.14.3, lucide-react to 1.31.0, @types/node to 26.2.0, typescript-eslint to 8.67.0, esbuild to 0.28.2, shiki to 4.4.3, and various other transitive dependencies.
  • fix(docs): restore theme switch without runtime warnings
    Move html/body shell and global css to root app layout to avoid hydration/script warnings from nested document nodes. Disable provider theme injection and add a custom script-free theme switch in shared layout slots.
    
    Also migrate docs search static client initializer to ZBSearch (initDB), add zbsearch dependency, and align docs lint tooling with ESLint 9 compatibility so npm run lint passes.
  • chore(deps-dev): bump postcss (#6173)
    Bumps the npm_and_yarn group with 1 update in the /docs directory: [postcss](https://github.com/postcss/postcss).
    
    
    Updates `postcss` from 8.5.21 to 8.5.23
    - [Release notes](https://github.com/postcss/postcss/releases)
    - [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
    - [Commits](https://github.com/postcss/postcss/compare/8.5.21...8.5.23)
    
    ---
    updated-dependencies:
    - dependency-name: postcss
      dependency-version: 8.5.23
      dependency-type: direct:development
      dependency-group: npm_and_yarn
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • docs(claude): correct enforced-guard claims and add the runtime dispatch rule
    Fact-checked every line of CLAUDE.md against the tree. Six claims were wrong,
    and two told an agent the opposite of the truth.
    
    The file said nothing checks endpoints.ts against the Go routes and nothing
    fails the build on a missing i18n key. Both guards exist and both run in
    make verify: TestRouteRegistryContract diffs the real router against the
    registry in both directions, and i18n-dead-keys.test.ts rejects a locale that
    misses an en-US key as well as an en-US key nothing references. An agent
    trusting the old text either skips a step it thinks is unenforced or is
    blindsided when a "silent" omission turns the suite red.
    
    The rest: the Go locale returns an empty string for an unknown key, not the raw
    key; mtg-multi is a prebuilt binary fetched at build time, not a Go dependency
    built from source; commits are type(area): summary, not <area>: summary, and
    perf is in active use; make verify is the fast gate, not a mirror of CI, which
    also runs race, vulncheck, a live-Postgres job where a SKIP is a failure, and a
    fuzz smoke.
    
    Add the five facts most likely to burn an agent, all reproduced before writing
    them down. A fresh clone has no internal/web/dist, so go build dies on the embed
    pattern while thirty-odd packages pass — it reads as a broken repo rather than a
    missing make dist-stub. Every state-changing inbound/client op must dispatch
    through runtime.Runtime; a direct xray/api.go call passes all local tests and
    silently breaks every multi-node install, which is exactly what a hard rule is
    for. Node 24 is required because make gen imports .ts directly. Postgres, xray
    e2e and scale tests skip themselves without their env vars. An endpoint change
    has a fourth step nothing checks: syncing docs/public/openapi.json.
    
    Definition of done loses its first step — verify's gen-check already runs gen
    and fails on a dirty generated diff.
  • fix(sub): honor trustedProxyCIDRs before forwarded URLs (#6135)
    * fix(sub): honor trustedProxyCIDRs before forwarded URLs
    
    * fix(sub): avoid unused trust-setting lookups
    
    Skip the trustedProxyCIDRs lookup when no forwarded header can affect a subscription URL. Keep the shipped proxy default in one exported setting constant and document the subscription-link behavior for custom proxy boundaries.
    
    * fix(frontend): meet config text contrast requirements
    
    Keep compact configuration text readable in the light theme and satisfy the Storybook accessibility check.
    
    ---------
    
    Co-authored-by: PathGao <gaoyanbo@gaoyanbodeMacBook-Air.local>
  • 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.