Commit Graph
244 Commits
  • fix(ci): install the docs-pinned pnpm instead of floating on 11.x
    pnpm/action-setup resolved 'version: 11' to the newest 11.x, and its self-installer crashes upgrading to 11.12.0 (Cannot use 'in' operator to search for 'integrity'), failing both docs workflows at setup. Reading docs/package.json instead installs the exact packageManager pin (pnpm@11.9.0), which also keeps the workflows and the lockfile toolchain on a single source of truth.
  • 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(frontend): make Storybook a validated, fully covered component workbench
    Storybook existed only as an undocumented local tool: 9 of 24 reusable components had stories, autodocs pages were bare prop tables, nothing built or tested the stories, and no contributor doc mentioned the workbench existed.
    
    Every reusable component under src/components/ now has a co-located story with enriched autodocs (component descriptions plus per-prop argTypes, kept as string metadata since the repo bans line comments). Stories double as headless Chromium tests through the Storybook vitest addon, with axe accessibility checks enforced as errors and play-function interaction tests covering the modals, the RHF field bridge, the config block, and the select-all buttons. The preview now mirrors the panel's real theme DOM (body class, shared AntD theme config, seeded theme storage) so what stories render matches production.
    
    CI and make verify gain a static Storybook build as a compile gate, and the frontend test job installs Chromium so story tests run on every PR. Contributor docs (frontend README, CONTRIBUTING, agent guides) document the workbench, the story conventions, and the Controls setup. Node engines move to 24 LTS and gen:api drops the type-stripping flags that Node 24 makes default.
  • 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.
  • ci(claude-bot): structure PR review and issue triage prompts
    Rework the handle-pr-review, handle-pr-fix, and handle-issue prompts to produce professional, structured output. The review job now rates findings by severity and confidence across explicit review areas and reports a Summary, Findings, and a text-only verdict in one plain comment; the fix job reuses the same lens to prioritize what it applies versus leaves for the author; issue triage gains a structured bug-confirmation format and explicit outcomes for mislabeled and not-a-bug reports, closing conservatively. Severity uses text labels to respect the no-emoji house style, and the adapted ignore-list keeps i18n and generated files flaggable.
  • ci(claude-bot): auto-open the PR after an owner @claude fix on an issue
    claude-code-action only pushes a branch and posts a Create PR link by design; it never opens the PR itself. Add a post-step to the mention job that opens a PR from the action's branch_name output when the trigger was an issue (guarded against no-op branches and against an existing PR).
    
    Simplify the mention prompt so the agent just makes edits with Edit/Write and lets the workflow commit and open the PR, instead of running git/gh pr create itself (which fought the action's built-in flow and left only a link).
  • ci(claude-bot): gate write capability to trusted actors
    Make every automatic, untrusted trigger read-only and require an explicit trusted actor for any code change.
    
    - handle-issue (issue opened): read-only triage; confirm bugs and tag the maintainer, never edit code or open a PR. Authenticates as GITHUB_TOKEN so replies post as github-actions[bot], not a personal account.
    
    - handle-pr-fix (PR opened): applies fixes only for owner/member/collaborator authors; dropped allowed_non_write_users so the default write gate also applies.
    
    - handle-pr-review (PR opened, external authors): read-only review comment only.
    
    - mention (@claude comment): runs only for the repository owner; may open a PR from an issue or commit to a PR on explicit request.
    
    No job authenticates as the static PAT anymore; the PAT is used only to route git pushes for the trusted PR-fix and owner-mention paths.
  • ci(claude-bot): auto-fix trusted PRs and easy issue bugs
    Split the review-only handle-pr job into handle-pr-fix (owner/member/collaborator PRs: apply refactors and bug fixes directly, commit to the PR branch, no suggestion blocks) and handle-pr-review (external/fork PRs: one review-only comment, no suggestions, no code checkout).
    
    Upgrade handle-issue to open a fix PR for easy bugs (pushed via CLAUDE_BOT_PAT so pull_request CI runs on it), confirm the root cause and tag the maintainer for big bugs, and never open a PR for feature or enhancement requests.
  • fix(inbounds): apply runtime changes after the DB commit (#5768)
    * fix(inbounds): apply runtime changes after commit
    
    * ci: fix staticcheck findings
  • feat(mtproto): enforce per-client quota & expiry via mtg-multi limits
    Map each mtproto client's totalGB and expiryTime onto mtg-multi's new
    [secret-limits] (quota/expires): emit them into the generated config and
    hot-apply through PUT /secrets so live connections survive. Quota is
    written as an exact "<n>B" byte count that round-trips through both the
    config and API parsers without the precision loss of a base-2 unit.
    
    The sidecar's quota counter is not pruned when a secret is dropped, so a
    panel-side traffic reset re-pushes the client's secret and then calls
    POST /secrets/{name}/reset-quota (wired into every reset path) so a
    renewed client is not immediately re-blocked.
    
    Resolve the mtg-multi binary from the fork's latest release tag in
    DockerInit.sh and release.yml instead of a hardcoded version pin, so the
    panel no longer needs a manual bump per fork release.
  • Frontend dev tooling (Husky, lint-staged, MSW, Storybook) + full React Hook Form migration (#5859)
    * chore(frontend): add husky + lint-staged pre-commit gate
    
    Wire a local pre-commit gate that runs eslint --fix on staged
    frontend TypeScript via lint-staged. Because the only package.json
    lives in frontend/ while the git root is one level up, the prepare
    script installs husky hooks at frontend/.husky from the repo root
    (cd .. && husky frontend/.husky), and the pre-commit hook cd's into
    frontend/ before invoking lint-staged so node_modules resolves.
    
    * test(frontend): add MSW request mocking
    
    Add Mock Service Worker so tests can exercise the real http-init.ts
    request pipeline (CSRF acquisition, 403 refetch-and-retry, body
    parsing) instead of only stubbing HttpUtil. A node setupServer is
    started for the vitest unit project with onUnhandledRequest bypass so
    the existing HttpUtil spies and 55 component tests are untouched; the
    browser worker is copied to public/ for Storybook and dev use.
    
    * chore(frontend): add Storybook + component stories
    
    Set up Storybook 10 on the React-Vite builder (compatible with the
    pinned Vite 8.1.3 and React 19). The preview decorator mirrors the
    vitest component harness: an Ant Design ConfigProvider with a
    light/dark toolbar toggle and an en-US i18next instance. main.ts
    neutralizes the app vite config bits that do not belong in a component
    workshop (the three-entry rollup input, renderBuiltUrl, and the shared
    dist outDir) so build-storybook can never clobber internal/web/dist.
    Seeds stories across the presentational library (viz, ui, clients,
    feedback). build-storybook is a local tool and is not wired into the
    CI gate.
    
    * feat(frontend): add React Hook Form primitives
    
    Introduce the shared RHF layer that AntD inputs bind through, ahead of
    migrating the forms off Ant Design's Form store:
    - FormField wraps a Controller in an Ant Design Form.Item shell,
      reconciling the value/onChange shapes of Input, Switch, InputNumber,
      Select and friends via normalizeAntdOnChange, with input/output
      transforms and Zod-issue-key error messages resolved through t().
    - useZodForm wires zodResolver (Zod 4) with the AntD-matching modes
      (validate on submit, then live) and shouldUnregister false so hidden
      and unmounted-tab fields keep their values.
    - rhfZodValidate covers the rare per-field rule sites.
    Covered by a FormField test exercising normalization, transforms, and
    resolver error surfacing.
    
    * refactor(frontend): migrate Pattern-B leaf forms to React Hook Form
    
    Move the controlled-useState leaf forms onto RHF via the FormField
    primitive, keeping Ant Design components and each form's exact submit
    behaviour (same safeParse, same toast on the first Zod issue, same
    payload building):
    - clients: ClientBulkAdjustModal, BulkAddToGroupModal, ClientBulkAddModal
    - xray: RuleFormModal, BalancerFormModal, WarpModal, NordModal
    
    Multi-control widgets that don't fit a single input (inbound dual
    select, subId regen, expiry branches, the balancer tag warning) stay as
    explicit Controller/setValue. Derived visibility now reads live values
    through useWatch. FormField gains a required prop so migrated fields keep
    their required-asterisk affordance.
    
    Settings tabs are intentionally excluded: they are control-panel
    components that live-patch a parent AllSetting via SettingListItem, not
    Ant Design Form submit-forms.
    
    * refactor(frontend): migrate LoginPage to React Hook Form
    
    Replace the Ant Design Form store + antdRule per-field validation with
    useForm + FormField. The AntD Form stays as the layout/submit wrapper,
    now driving methods.handleSubmit(onSubmit) via onFinish. Username and
    password validate through rhfZodValidate(LoginFormSchema.shape.*); the
    two-factor field keeps its conditional required rule (only registered
    when 2FA is enabled). Submit posts the same values to /login.
    
    * refactor(frontend): migrate ClientFormModal to React Hook Form
    
    Move the client add/edit form off controlled useState onto RHF while
    preserving exact submit behaviour (same ClientFormSchema /
    ClientCreateFormSchema safeParse, same toast, same payload + attach/
    detach diff + external-links build). expiryDate is stored as an epoch
    number (never a Dayjs) to survive RHF's value cloning, converted at the
    DateTimePicker boundary. externalLinks uses useFieldArray with stable
    ids. inboundIds and the derived show*/ss2022 visibility read live via
    useWatch. Space.Compact button-group widgets stay manual Controllers so
    the joined borders keep working.
    
    * refactor(frontend): migrate Node and DNS modals to React Hook Form
    
    Both are self-contained Pattern-A forms (no shared fragments). Replace
    Form.useForm with useForm + FormProvider, Form.useWatch with useWatch,
    setFieldValue with setValue, and partial validateFields([...]) with
    methods.trigger([...]). Per-field antdRule becomes rhfZodValidate rules;
    the Node scheme->tlsVerify cascade moves to FormField onAfterChange; the
    DNS domains/expectIPs/unexpectIPs string arrays are driven by
    useWatch + setValue. Submit runs through handleSubmit on the modal OK
    button, preserving each form's exact validation, payload build, and
    save/onConfirm behaviour.
    
    * refactor(frontend): migrate HostFormModal to React Hook Form
    
    The host external-proxy editor's outer form moves to useForm +
    FormProvider. Security/tab visibility reads via useWatch; the three
    json-form editors (HostMuxForm/HostSockoptForm/HostFinalMaskForm) are
    bound as value/onChange black boxes through a Controller (their own
    internal forms are unchanged). remark/inboundId keep their validation
    via rhfZodValidate; submit runs through handleSubmit and builds the
    same payload (isDisabled = !enable) and save call.
    
    * refactor(frontend): migrate OutboundFormModal + fragments to React Hook Form
    
    Move the outbound form cluster off Ant Design's Form store onto RHF.
    The parent uses useForm + FormProvider with a watch() subscription for
    the protocol reseed cascade and setValue-based network/security/xmux
    cascades; the JSON<->Basic bridge and the formValuesToWirePayload
    submit are preserved exactly. Every outbound transport/protocol/security
    fragment now binds through FormField/useWatch via context.
    
    The shared config editors stay untouched and are bound through small
    value/onChange adapters (src/lib/xray/forms/fields: FinalMaskField,
    SniffingField, SockoptCustomField) via Controller; HeaderMapEditor binds
    directly. The host json-form wrappers that reuse the outbound MuxForm/
    SockoptForm (HostMuxForm, HostSockoptForm, OutboundSubtreeJsonForm) move
    to a local RHF provider to match. Outbound render/link tests pass
    unchanged.
    
    * refactor(frontend): migrate InboundFormModal + fragments to React Hook Form
    
    Move the inbound add/edit form (the largest form in the panel) and its
    transport/protocol/security fragments off Ant Design's Form store onto
    RHF, mirroring the outbound migration. The parent uses useForm +
    FormProvider with a watch() subscription for the protocol reseed
    cascade (type==='change' guard so programmatic resets don't reseed) and
    setValue-based network/security cascades; useSecurityActions drives the
    TLS/Reality keypair + scan through setValue. Hidden pass-through
    Form.Items are dropped (their values ride in the reset object and
    survive via shouldUnregister:false), so getValues() still returns the
    settings.clients subtree untouched. accounts / certificates / tun lists
    use useFieldArray; the shared FinalMask/Sniffing/Sockopt editors bind
    through the value/onChange adapters.
    
    Submit keeps the manual InboundFormSchema.safeParse + formatInboundValidation
    toast + formValuesToWirePayload exactly. The golden link/full fixtures
    pass byte-for-byte, confirming identical wire output. inbound-form-blocks
    test harness rewritten from a Form.useForm harness to an RHF provider.
    
    * refactor(frontend): retire antdRule; document the RHF form pattern
    
    All forms now build on React Hook Form, so the AntD-Form Zod adapter
    antdRule (src/utils/zodForm.ts) has no remaining callers — remove it.
    Update frontend/CLAUDE.md: forms use useZodForm + FormField from
    components/form/rhf with zodResolver/rhfZodValidate validation; AntD
    <Form> is layout-only; the shared FinalMask/Sniffing/Sockopt editors
    stay AntD islands wrapped as value/onChange adapters bound via a
    Controller.
    
    * chore(frontend): cover esbuild in the allowScripts allowlist
    
    esbuild (pulled in transitively by Vite/Vitest/Storybook) ships a
    postinstall that npm's allow-scripts flags as uncovered on every
    install. Its platform binary is delivered through the @esbuild/<platform>
    optionalDependencies, so the postinstall isn't needed here; deny it like
    the other entries to silence the warning.
    
    * fix(frontend): restore label layout in Sniffing/FinalMask field adapters
    
    The value/onChange adapters that wrap the shared SniffingFields and
    FinalMaskForm editors put them in their own isolated AntD Form, but that
    Form was missing the label layout the fields used to inherit from the
    inbound/outbound parent form. Their labels rendered full-width instead
    of the compact right-aligned column, so the Sniffing tab and the TCP
    Masks / QUIC Params sections looked broken. Give both adapter forms the
    same colon=false, labelCol/wrapperCol span 8/14, labelWrap layout.
    
    * ci: add least-privilege permissions to Docs CI workflow
    
    The docs-ci workflow had no explicit permissions block, so it inherited
    the repository default for GITHUB_TOKEN. The build job only checks out
    and builds the docs, so restrict it to contents: read, resolving the
    CodeQL actions/missing-workflow-permissions alert.
  • 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.
  • chore(mtproto): bump the mtg-multi binary pin to v1.14.0
    Same asset layout and platform coverage as v1.13.3; picks up the
    sidecar's Docker-style environment variable support.
  • fix(ci): stop executing tag-checkout code in the release smoke test
    CodeQL alert 99 (actions/cache-poisoning/poisonable-step): the workflow_run
    job runs in the default branch's cache scope, so checking out
    workflow_run.head_sha and executing a script from it is a cache-poisoning
    surface. The if-guard (event == 'push') already kept fork PRs out, but the
    checkout pin was never the load-bearing part of the release verification —
    the version argument is, since install.sh downloads that exact release
    binary. Run the smoke script from the default branch instead, which also
    matches what real users execute.
  • 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
  • fix(ci): install mtg-multi without GOBIN for cross-compiled release builds
    go install refuses to run with GOBIN set when GOOS/GOARCH differ from the host, which failed the linux release build for every non-amd64 platform (386, arm64, armv7, armv6). Let it install into GOPATH/bin instead, where cross-compiled binaries land in a GOOS_GOARCH subdirectory, and locate the binary there. DockerInit.sh keeps GOBIN because buildx runs it under emulation for the target platform, making the install native.
  • 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.
  • fix(ci): pin the tag smoke test to the release under test
    The v3.4.2 tag push triggered the smoke workflow immediately, but
    install.sh with no arguments resolves releases/latest, which still pointed
    at v3.4.1 while release.yml was uploading the new assets. The green smoke
    run therefore validated the previous release (#5756). A paths filter alone
    cannot exclude tag pushes because a brand-new tag ref has no diff base.
    
    Restrict the push trigger to branches so tag pushes no longer start the
    unpinned job, and add a workflow_run job that fires after the release
    workflow completes for a v* tag: it checks out the tagged commit, passes
    the tag through smoke-noninteractive.sh into install.sh's explicit-version
    path, and asserts the installed binary reports exactly that version.
    
    Closes #5756
  • chore(ci): upgrade claude-bot to Sonnet 5 and set explicit effort levels
    Sonnet 5 reaches near-Opus quality on coding/agentic work at lower cost;
    pin effort explicitly (xhigh/max) instead of relying on model defaults.
  • chore(deps): bump xray-core to v26.6.27
    Update the xray-core Go module (infra/conf builders + gRPC command clients) and the bundled binary pin in DockerInit.sh and the release workflow from v26.6.22 to v26.6.27. No gRPC command-API breaking changes. The release's other inbound work rides along with the bump: TUN autoSystemRoutingTable/autoOutboundsInterface are already modeled in the frontend tun schema, while Hysteria vlessRoute (UUID-derived) and the TUN traffic counters are internal to xray-core and need no panel changes.
  • chore(ci): bump golangci-lint action to v9
    Update the GitHub Actions CI workflow to use golangci/golangci-lint-action@v9 instead of v8. This keeps the lint job aligned with the latest major version and ongoing action maintenance.
  • style: adopt golangci-lint v2 and resolve all findings
    Add .golangci.yml (v2): the standard linters plus bodyclose, errorlint, noctx, misspell, rowserrcheck, sqlclosecheck, unconvert, usestdlibvars, with gofumpt + goimports formatters. Enable the std-error-handling exclusion preset for idiomatic Close/Remove/Setenv ignores; scope-exclude SA1019 (parser.ParseDir in tools/openapigen) and ST1005 (intentional capitalized user-facing error copy that tests assert verbatim). No inline nolint directives were introduced.
    
    Resolve all 217 findings behavior-preserving: gofumpt/goimports formatting, explicit blank assignment on intentionally ignored errors, errors.Is/errors.As and %w wrapping, context-aware stdlib calls (CommandContext/QueryContext/NewRequestWithContext/Dialer), staticcheck simplifications, removed redundant conversions, http.StatusOK and http.MethodGet, inlined the go:fix intPtr helper, and deferred sql rows Close. Add a golangci CI job mirroring the existing Go jobs.
  • chore(deploy): drop the AWS golden-image build stack
    Remove the release-driven Packer AMI/qcow2 pipeline and everything that existed only to feed it: the image.yml workflow, deploy/packer, deploy/lightsail, deploy/firstboot, the AWS Marketplace checklist, and the first-boot smoke test/job.
    
    Keep the cloud-agnostic unattended-install path (cloud-init + install.sh non-interactive) and the Hetzner notes, which never depended on the workflow. Hetzner's snapshot path is dropped too since it relied on firstboot to avoid admin/admin on clones; cloud-init regenerates per-instance credentials on its own.
    
    Update deploy/README, the cloud-init and Hetzner docs, the root README plus its six translations, and .gitattributes to match.
  • chore: bump deps and modernize test loops
    - release.yml: download-artifact v7 -> v8
    - frontend: i18next 26.3.1 -> 26.3.2, qs 6.15.2 -> 6.15.3
    - go.mod: consolidate indirect requires (go mod tidy)
    - tests: adopt Go 1.22 range-over-int loops
  • feat(update): add rolling dev update channel for per-commit builds
    Adds an opt-in Dev channel so panels running CI per-commit builds can self-update to the latest commit, mirroring the stable online-update flow.
    
    CI publishes/overwrites a single fixed-tag pre-release (dev-latest), force-moved to the newest main commit and marked --latest=false so releases/latest stays the stable tag. Builds stamp the short commit via -ldflags; the panel compares the running commit to the dev release commit to detect an update, and update.sh honors XUI_UPDATE_TAG to install from that tag. Linux/systemd only.
  • Update Xray to v26.6.22
    Point CI workflow and DockerInit.sh to Xray v26.6.22 (update download URLs for Linux and Windows). Update go.mod to the matching github.com/xtls/xray-core pseudo-version and bump github.com/pion/stun to v3.1.6; refresh corresponding go.sum entries.
  • ci(claude-bot): tune models, Copilot-style PR review, issue research mode
    - handle-issue: use Sonnet 4.6 and raise max-turns 150 to 250
    
    - handle-pr: use Opus 4.8; rewrite review as inline comments stating the problem plus a suggestion block, posted as one COMMENT review
    
    - mention: use Opus 4.8; on issues do research only (never commit) with full comment/history context and feature-request feasibility analysis; PR commit-on-request behavior unchanged
    
    - reformat the mention append-system-prompt into a readable multi-line block (verified it still parses as a single CLI argument)
  • feat(ci): let mention bot push commits to fork PR branches
    claude-code-action checks out the PR head branch and pushes Claude's
    commits with `git push origin ...`. For PRs opened from a fork the head
    branch lives on the contributor's repo, and the workflow GITHUB_TOKEN
    cannot push there, so commits ended up as a stray branch on this repo
    and never landed on the PR.
    
    Redirect origin's push URL to the PR head repository (the fork for fork
    PRs, this repo otherwise) using a PAT secret (CLAUDE_BOT_PAT) that has
    push access; fetches still come from origin. persist-credentials is
    disabled so the PAT in the push URL is used instead of the GITHUB_TOKEN
    auth header. Requires the fork PR to have "Allow edits by maintainers"
    enabled.
  • feat(ci): add PR review job and commit-capable mention bot
    Rename claude-issue-bot.yml to claude-bot.yml and broaden it beyond
    issues:
    
    - handle-pr: review pull requests on open (read diff, label, post one
      grounded review comment); review-only, no code changes.
    - mention: allow committing. Add Edit/Write and git tools, contents:
      write, and instruct it to make the smallest correct change and commit
      to the current branch only on an explicit code-change request. Kept
      default user gating (no allowed_non_write_users) so only write-access
      users can trigger commits.
    - Refresh the repository map (add internal/eventbus and the
      service/email subpackage) across all three prompts.
    - Raise max-turns.
    @
  • chore(deps): bump actions/checkout from 6 to 7 (#5454)
    Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7.
    - [Release notes](https://github.com/actions/checkout/releases)
    - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
    - [Commits](https://github.com/actions/checkout/compare/v6...v7)
    
    ---
    updated-dependencies:
    - dependency-name: actions/checkout
      dependency-version: '7'
      dependency-type: direct:production
      update-type: version-update:semver-major
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • chore(deps): bump actions/upload-artifact from 4 to 7 (#5427)
    Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 7.
    - [Release notes](https://github.com/actions/upload-artifact/releases)
    - [Commits](https://github.com/actions/upload-artifact/compare/v4...v7)
    
    ---
    updated-dependencies:
    - dependency-name: actions/upload-artifact
      dependency-version: '7'
      dependency-type: direct:production
      update-type: version-update:semver-major
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • chore(deps): bump aws-actions/configure-aws-credentials from 4 to 6 (#5426)
    Bumps [aws-actions/configure-aws-credentials](https://github.com/aws-actions/configure-aws-credentials) from 4 to 6.
    - [Release notes](https://github.com/aws-actions/configure-aws-credentials/releases)
    - [Changelog](https://github.com/aws-actions/configure-aws-credentials/blob/main/CHANGELOG.md)
    - [Commits](https://github.com/aws-actions/configure-aws-credentials/compare/v4...v6)
    
    ---
    updated-dependencies:
    - dependency-name: aws-actions/configure-aws-credentials
      dependency-version: '6'
      dependency-type: direct:production
      update-type: version-update:semver-major
    ...
    
    Signed-off-by: dependabot[bot] <support@github.com>
    Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • Test-quality audit: fix 2 prod bugs, strengthen weak tests, add mutation/fuzz/CI tooling (#5345)
    * test(audit): add gremlins/rapid/coverage tooling + AUDIT.md scaffold
    
    * test(audit): hygiene sweep (race-clean except logger global; Finding #2) + smell inventory
    
    * test(audit): cover untested error/edge branches (TLS proxy+pin, migration tag cleanup=Finding #1)
    
    * test(audit): strengthen internal/sub link tests (dedup key, TLS/Reality mapping, clash well-formedness)
    
    * test(audit): property (rapid) + fuzz tests for joinHostPort/userinfo/pin/ParseLink
    
    * test(audit): tighten frontend subSortIndex rejection assertions + wire coverage
    
    * ci(audit): add shuffle gate + non-blocking race job (Finding #2) + fuzz-smoke; document mutation policy
    
    * chore(audit): gitignore frontend coverage output
    
    * test(audit): exhaustive whole-repo pass — strengthen 5 weak/fake tests (netproxy, CSP, modal per-protocol loops, schema coercions)
    
    * docs(contributing): add Testing section (conventions, race/shuffle, fuzz, mutation policy); drop AUDIT.md ledger
    
    * fix(logger,migration): guard logBuffer with mutex; execute legacy tag cleanup (tx.Exec); make CI race gate blocking
    
    * ci(mutation): add nightly scoped gremlins workflow (informational artifacts)
    
    * test(audit): strengthen runtime tests — baseURL scheme/port bounds, isNonEmptySlice, trafficReset
    
    * test(audit): strengthen clash tests — reality field mapping + tcp-header validation
    
    * test(audit): runtime — egress-proxy + content-type tests; drop redundant bp=='' branch
    
    * test(audit): strengthen link parser/helper tests (defaultPort, splitComma, base64, canonicalQuery, tls/reality/transport mapping)
    
    * test(audit): strengthen sub/xray/common/netsafe/mtproto/config/middleware tests (kill surviving mutants)
    
    * test(audit): raise timeout on protocol-iteration modal tests (heavy re-renders, slow on CI)
    
    * fix(logger): GetLogs returns at most c entries (off-by-one fix; addresses PR review)
    
    * perf(logger): snapshot logBuffer under lock so GetLogs doesn't block logging; clarify fuzz-seed docs (addresses PR review)
  • ci(smoke): set least-privilege GITHUB_TOKEN permissions
    Add a top-level `permissions: contents: read` block so the smoke-test
    workflow no longer inherits the repository default token permissions.
    Resolves CodeQL actions/missing-workflow-permissions.
  • feat: release-driven golden-image & unattended-install deployment pipeline (#5323)
    * feat(install): add non-interactive install path for cloud/golden-image use
    
    Trigger non-interactive mode when XUI_NONINTERACTIVE=1 or stdin is not a
    TTY (curl | bash, cloud-init). Every prompt is then replaced by an env var
    or a sane default; interactive prompts stay byte-for-byte identical.
    
    Honored env vars: XUI_USERNAME, XUI_PASSWORD, XUI_PANEL_PORT,
    XUI_WEB_BASE_PATH (unset => random, as before), XUI_SSL_MODE=none|ip|domain
    (default none), XUI_DOMAIN, XUI_ACME_EMAIL, XUI_DB_TYPE/XUI_DB_DSN, plus
    additive XUI_ACME_HTTP_PORT, XUI_SSL_IPV6, XUI_SERVER_IP.
    
    On success, write /etc/x-ui/install-result.env (mode 600) with the panel
    creds + access URL + api token, in both interactive and non-interactive
    modes, so cloud-init/MOTD can surface them. Postgres in non-interactive
    mode requires XUI_DB_DSN or installs locally; never silently downgrades.
    
    * feat(deploy): add first-boot per-instance credential generation
    
    Golden images ship with no x-ui.db. x-ui-firstboot.sh runs once (guarded by
    /etc/x-ui/.firstboot-done), before x-ui.service, and replaces the seeded
    admin/admin with fresh random username/password on a random high port,
    regenerates the session secret/panel GUID via 'x-ui setting -reset', mints an
    API token, and writes the creds to /etc/x-ui/credentials.txt (600) + /etc/motd.
    
    Idempotent: skips regeneration if a non-default admin already exists. The
    oneshot unit is ordered After=network-online/cloud-init and Before=x-ui.service
    so the panel never serves default credentials.
    
    * chore(deploy): force LF for cloud-image deploy assets (.service/.hcl/.yaml)
    
    * feat(deploy): add Packer config + provisioning scripts for golden image
    
    One build, two sources: amazon-ebs (AWS AMI, Canonical Ubuntu 24.04 base via
    source_ami_filter) and qemu (qcow2 + raw, NoCloud-seeded for build-time SSH).
    Provisioner order is fixed: provision.sh -> harden.sh -> cleanup.sh.
    
    - provision.sh: downloads the released x-ui tarball (no Go build), installs the
      panel + firstboot unit, enables but does NOT start services, creates NO DB.
    - harden.sh: key-only SSH, no root password login, locks default account
      passwords, enables unattended-upgrades (scanner-compliant).
    - cleanup.sh: wipes any DB/creds, SSH host keys, authorized_keys, machine-id,
      cloud-init state, logs and history; fails the build if any secret survives.
    
    packer fmt -check clean; packer validate passes for both sources.
    
    * feat(deploy): add generic cloud-init user-data for unattended install
    
    cloud-init.yaml installs the latest 3x-ui non-interactively (XUI_NONINTERACTIVE=1)
    on any cloud-init platform, generating unique per-instance credentials and
    surfacing them via /etc/x-ui/install-result.env, serial console and MOTD.
    README documents per-provider usage (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
    and all XUI_* knobs.
    
    * ci: add image.yml to build cloud images on release
    
    On release: published (or workflow_dispatch with a tag), waits for the
    x-ui-linux-amd64.tar.gz asset (handles the release-matrix upload race), then:
    - qemu-image (always): builds the qcow2 with Packer and attaches a compressed
      .qcow2.xz + sha256 to the GitHub release. Uses KVM when /dev/kvm exists,
      else TCG.
    - ami-image (gated): builds the AWS AMI only when AWS creds exist (OIDC role
      preferred, else access keys), so forks skip cleanly. Prints the AMI ID to the
      job summary. No secrets or AMI IDs are committed.
    
    * test(deploy): add container smoke tests for install + firstboot
    
    smoke-noninteractive.sh: runs install.sh piped (no TTY) with
    XUI_NONINTERACTIVE=1 in an Ubuntu container; asserts install-result.env (600)
    holds random non-default creds, hasDefaultCredential is false, and the panel
    serves HTTP.
    
    smoke-firstboot.sh: installs the released binary with no DB, runs
    x-ui-firstboot.sh; asserts per-instance creds + credentials.txt (600) + MOTD,
    no admin/admin, and that a second run is a no-op (sentinel honored).
    
    smoke.yml runs both as gated jobs on PRs/pushes touching install.sh or deploy/**.
    Both pass locally against the v3.3.1 release binary.
    
    * docs(deploy): add Packer/marketplace docs and link from README
    
    - deploy/README.md: index of the cloud-deploy tooling and the two models
    - deploy/packer/README.md: how to build locally, variables, first-boot behavior
    - deploy/marketplace/aws/README.md: seller registration -> AMI scan ->
      limited-visibility preview -> go-public checklist
    - deploy/marketplace/hetzner/README.md: cloud-init-first guidance + snapshot
      caveat (delete x-ui.db first) + hetznercloud/apps reference
    - README.md: link the unattended-install / cloud-image docs from Quick Start
    
    * feat(deploy): build golden images for arm64 as well as amd64
    
    The install path was already multi-arch (install.sh auto-detects arch); this
    extends the golden image + CI to arm64:
    
    - packer: xui_arch (amd64|arm64, validated) now derives the base AMI filter and
      the Ubuntu cloud image; the qemu source switches to qemu-system-aarch64 + virt
      machine + AAVMF UEFI firmware for arm64. amd64 path unchanged.
    - image.yml: arch matrix. AMIs for amd64 (t3.small) + arm64 (t4g.small/Graviton)
      from one runner; qcow2 for amd64 on a standard runner and arm64 on a native
      ubuntu-24.04-arm runner. Waits for both release tarballs.
    - smoke.yml: run install + firstboot smoke tests on amd64 and arm64 runners;
      smoke-firstboot.sh now resolves the arch tarball via dpkg.
    - docs updated for both arches.
    
    packer fmt/validate pass for amd64 and arm64; actionlint + shellcheck clean.
    Verified locally: non-interactive install AND firstboot run on the real arm64
    release binary under emulation (ELF aarch64, no admin/admin).
    
    * chore(deploy): default AWS region to eu-central-1 (Frankfurt)
    
    Replace the us-east-1 fallback in image.yml (4 sites) and the Packer 'region'
    default + doc examples. Still overridable via the AWS_REGION repo variable / the
    -var 'region=...' flag.
    
    * feat(deploy): add Amazon Lightsail support (launch script + snapshot builder)
    
    Lightsail can't launch from an EC2 AMI and its blueprint list isn't
    self-publishable, so add the two self-service paths instead:
    
    - launch-script.sh: paste into Lightsail 'Add launch script' (or --user-data) to
      install 3x-ui non-interactively with unique per-instance credentials.
    - snapshot-userdata.sh + build-snapshot.sh: AWS CLI pipeline that provisions a
      build instance (panel installed, NO DB, firstboot enabled), runs the shared
      cleanup.sh, then snapshots it. Instances launched from the snapshot mint their
      own credentials on first boot. Optional --panel-port pins a known port for the
      Lightsail firewall.
    - README documents both paths, the firewall caveat, and the blueprint reality.
    
    EC2 AMI / Marketplace path kept untouched alongside. All scripts shellcheck-clean.
    
    * fix(deploy): address Copilot PR review findings
    
    - install.sh + firstboot: write install-result.env / credentials.txt values with
      printf %q so the files stay safe to source even if creds are pinned with shell
      metacharacters (no-op for the alphanumeric random defaults).
    - firstboot: fail closed if 'x-ui setting -show' can't be parsed to true/false —
      exit without writing the sentinel so the next boot retries, instead of silently
      skipping regeneration and risking admin/admin.
    - firstboot + cloud-init + lightsail launch-script: keep secrets out of the
      world-readable /etc/motd (show URL + username only; full creds via the mode-600
      file / serial console).
    - lightsail build-snapshot: handle download-default-key-pair returning either a
      PEM or base64, and assert a valid PEM before using it for SSH.
    - image.yml: pin hashicorp/setup-packer@v3 (was @main).
    - deploy/README: document XUI_ACME_HTTP_PORT / XUI_SSL_IPV6 / XUI_SERVER_IP.
    
    Both container smoke tests still pass; shellcheck + actionlint clean.
  • ci(bot): update issue-bot repo map and tighten reply style
    - Refresh repository map: add internal/mtproto, web/entity, web/global,
      web/session, web/locale, frontend/, tools/openapigen, docs/, windows_files
    - Correct stack facts: Xray-core runs as a managed child process; full env
      var list incl. XUI_INIT_WEB_BASE_PATH, XUI_LOG_FOLDER, XUI_BIN_FOLDER,
      XUI_SKIP_HSTS; protocol list matches the model.go enum incl. MTProto
    - Add COMMENT STYLE section for professional, precise, answer-first replies
    - Raise --max-turns for both jobs
  • 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.
  • feat(mtproto): add MTProto (FakeTLS) protocol via managed mtg sidecar (#5076)
    * feat(mtproto): add MTProto (FakeTLS) protocol via managed mtg sidecar
    
    Xray-core has no mtproto proxy, so mtproto inbounds run as standalone
    mtg (9seconds/mtg) sidecar processes managed by the panel — one per
    inbound — and are excluded from the generated Xray config entirely.
    
    - model: MTProto protocol constant, validator, and FakeTLS secret
      helpers (GenerateFakeTLSSecret/HealMtprotoSecret)
    - mtproto package: per-inbound mtg process manager with reconcile,
      graceful stop, and best-effort Prometheus traffic scraping
    - runtime: delegate mtproto inbounds to the mtg manager instead of the
      Xray gRPC API; skip mtproto when building the Xray config
    - web: boot reconcile + StopAll wiring, periodic reconcile/traffic job,
      port-conflict transport, secret healing on inbound add/update
    - sub: tg:// proxy share-link generation
    - frontend: protocol option, Zod schema, Protocol tab (FakeTLS domain +
      regenerable secret), info-modal link, and i18n
    - provisioning: fetch mtg v2.2.8 in install.sh, DockerInit.sh, and the
      Linux + Windows release workflows
    
    * fix
    
    * fix
    
    * fix: address Copilot review comments on mtproto PR
    
    - web/web.go: create NewMtprotoJob once and reuse for cron + initial run
    - mtproto/manager.go: StopAll cleans up per-inbound config files on shutdown
    - mtproto/manager.go: CollectTraffic releases mutex before HTTP scrapes to
      avoid blocking Ensure/Reconcile/Remove during network I/O
    - database/model/model.go: panic on crypto/rand failure in mtprotoRandomMiddle
      instead of silently producing a weak all-zero secret
    - install.sh: fix chmod to handle renamed bin/mtg-linux-arm on armv5/v6/v7
  • feat(api-docs): generate response examples from Go structs; fix SS2022 PSK regen (#4996)
    Stop hand-writing OpenAPI response examples, which kept drifting from the real payloads (clients/traffic missing fields, inbounds/list exposing userId which is json:"-", the fictional inbound-443 tag instead of the real in-<port>-<transport> form).
    
    tools/openapigen now emits frontend/src/generated/examples.ts: a per-struct example instance built from type defaults, validate oneof/min bounds, and example: struct tags, with nested-ref expansion and a cycle guard. build-openapi.mjs composes the {success,obj} envelope from it for any endpoint annotated with responseSchema (+ responseSchemaArray for lists); the hand-written response is dropped for those. Service DTOs InboundOption/ApiTokenView/ProbeResultUI are added to the walker.
    
    #4996: client password regeneration now produces a valid Shadowsocks 2022 PSK (correct base64 length per cipher) when an SS2022 inbound is attached, in both the single and bulk client forms; backend surfaces ssMethod on /inbounds/options so the UI can pick the right length.
    
    Also: Swagger UI persists the Authorization token across reloads (persistAuthorization).
  • ci(issue-bot): ground the assistant in repo source with an investigation step
    Give the issue and @claude-mention assistants the repository map, verified runtime facts, and an explicit INVESTIGATE step so every answer is grounded in the checked-out source instead of guesses. Raise max-turns (issues 45->90, mentions 40->70) and expand the mention system prompt to match.
  • chore: bump bundled Xray-core to v26.6.1
    Update the Xray-core download URLs in the release workflow and DockerInit.sh from v26.5.9 to v26.6.1.
  • fix(ci): raise issue-bot max-turns so full triage completes
    The handle-issue job capped at 25 turns, which only covered the
    early-exit spam/duplicate paths. Real bug reports went through the full
    flow (categorize + Read/Grep the code + post an answer) and hit the cap
    mid-step 5, leaving the issue labeled but with no reply. Raise to 45 to
    match the heavier path; the mention job already uses 40.
    @
  • fix(ci): let issue bot run for non-collaborator issue authors
    The handle-issue job uses claude-code-action, which by default refuses
    to run unless the triggering user has write access. Public issue authors
    never do, so the job failed on essentially every real issue. Set
    allowed_non_write_users: "*" on the triage job (mention job left gated).
  • feat(postgres): in-panel backup/restore and consistent CLI backend
    Two PostgreSQL gaps on the panel:
    
    1. x-ui setting and other CLI subcommands read XUI_DB_TYPE/XUI_DB_DSN from
       the process environment, which systemd injects via EnvironmentFile but a
       plain shell invocation does not. On a PostgreSQL install the CLI silently
       fell back to SQLite, so changes made from the management menu never
       reached the panel's database. Load the systemd EnvironmentFile
       (/etc/default/x-ui and distro equivalents) at startup; godotenv.Load does
       not override existing vars, so it stays a no-op for the managed service.
    
    2. DB backup/restore (panel endpoints and the Telegram bot) only handled the
       SQLite file, so on PostgreSQL Back Up returned a stale/absent x-ui.db and
       Restore silently did nothing. Add pg_dump/pg_restore based backup/restore:
       - GetDb/ImportDB run pg_dump (custom format) / pg_restore, passing
         credentials via the PG* environment instead of argv.
       - getDb downloads x-ui.dump on Postgres, x-ui.db on SQLite.
       - Telegram backup sends the matching file via GetDb.
       - BackupModal shows a Postgres note and accepts .dump; the dist page
         injects window.X_UI_DB_TYPE; new strings translated for all locales.
       - install.sh installs postgresql-client for the external-DSN path and
         points the user to in-panel Backup & Restore.
    
    Closes #4658