Compare commits

...

78 Commits

Author SHA1 Message Date
MHSanaei f3a57d4c57 3.4.2 2026-06-29 20:28:08 +02:00
MHSanaei 86813758cc fix(node): stop the offline-sync toast firing on saves to online nodes
IsNodePending fed the user-facing "saved locally, node offline, will
sync on reconnect" toast off three conditions, one of which was the
node's config_dirty flag. But every node-backed client/inbound edit
marks the node dirty unconditionally inside its write transaction — it
is the reconcile self-heal marker, set even for edits pushed live to a
healthy online node. The controller reads that freshly-set flag right
after the save, so the warning fired on every save to a node-backed
inbound regardless of the node actually being online.

Drop the dirty term so the predicate reflects only what the message
claims: the node being unreachable (offline or disabled). Offline and
disabled nodes still mark dirty and still surface the toast.

Add regression tests: online+dirty must not be pending; offline and
disabled must be.
2026-06-29 18:35:38 +02:00
MHSanaei 8332ba67ae chore(deps): bump antd to 6.5 and migrate deprecated component props
Upgrade frontend deps (antd 6.4.5 -> 6.5.0, Ant Design icons, TanStack
Query, i18next, eslint) and fasthttp 1.71 -> 1.72.

AntD 6.5 deprecated several Input/Card/Space props, so adapt the panel UI:
- Input/InputNumber addonBefore/addonAfter -> prefix/suffix
- Card bordered -> variant="outlined"
- Space direction -> orientation
- swap the hand-rolled Telegram SVG for the new TelegramFilled icon
- guard SettingListItem against cloning aria-labelledby onto a Fragment,
  which only accepts key/children
2026-06-29 16:57:55 +02:00
MHSanaei d8221a8153 fix(sub): bake Host VLESS Route into subscription UUIDs
The Host VLESS Route field was stored and shown in the panel but never applied to any generated subscription (raw, JSON, Clash), so the UUID was emitted unmodified (#5655).

Xray reads the route from the UUID's 3rd group (bytes 6-7, net.PortFromBytes) and masks those bytes to zero before authenticating, so a value can be baked into the share/JSON/Clash UUIDs without breaking the user match. A shared applyVlessRoute helper encodes a single 0-65535 value as the 3rd group; empty/invalid/non-UUID input is left unchanged, so legacy data never yields a broken link and no DB migration is needed.

The field was wrongly validated as a multi-segment port spec (that form belongs to the separate server-side routing rule). It is now a single value 0-65535, with frontend validation, link-preview parity (genVlessLink/hostToExternalProxyEntry), hint + error translations across all 13 locales, and tests on every path.

Closes #5655
2026-06-29 14:32:23 +02:00
MHSanaei 789e92cddc fix(clients): re-enable depleted clients on API renewal (#5619)
Renewing a subscription via POST /panel/api/clients/bulkAdjust extended a client's expiry/quota but left it disabled. The enforcement loop disables a depleted client across client_traffics, client_records and the inbound settings JSON (and pushes that to the node), while BulkAdjust only updated expiry/total and never cleared enable. On a node its UpdateUser push was built from the stale ClientRecord (Enable=false), which the next traffic poll merged back onto the master, so the client never recovered.

BulkAdjust now re-enables a client only when it was disabled because it was depleted and the adjustment lifts it back within limits, computed as a set-difference of the production depletedCond predicate and applied through the canonical BulkSetEnable (run after the per-inbound loop, since lockInbound is non-reentrant). Manually-disabled or still-depleted clients stay disabled.

Update now writes the clients.enable column explicitly so re-enabling sticks for inbound-less clients and stops feeding a stale record into node pushes.
2026-06-29 13:39:03 +02:00
nima1024m 7a5d6da28c fix(xray): clean stale routing references when a balancer or outbound is deleted (#5648)
* feat(xray): reference-cleanup helpers for entity deletion

When an outbound or balancer is deleted on the Xray page, routing rules and
balancers that reference it must be repaired in the same edit, or the saved
config breaks the core: a dangling balancerTag stops Router.Init (whole core
down), a dangling outboundTag black-holes matched traffic at the dispatcher.

Add pure plan*/apply* helpers that compute and apply the cleanup. A rule is
kept when a destination (outboundTag or balancerTag) remains and dropped when
none does. Deleting an outbound cascades: emptying a balancer selector removes
that balancer too, then repairs its rules in one pass against the full removed
set; fallbackTag and dialerProxy references are cleared and observatories
re-synced.

* fix(balancers): clean routing rules referencing a deleted balancer

Deleting a balancer left routing rules pointing at its balancerTag. xray-core's
Router.Init then fails ("balancer <tag> not found"), the core won't restart and
every inbound drops — the saved config passes CheckXrayConfig (JSON shape only),
so it breaks only on the next restart.

The delete confirm now lists the affected rules (modified vs removed) next to
the existing observatory warning and applies planBalancerDeletion's cleanup: a
rule keeps its outboundTag when present, otherwise the whole rule is dropped.
Adds the shared DeletionImpactList and refCleanup strings across all 13 locales.

* fix(outbounds): clean rules, balancer selectors and dialerProxy on outbound delete

Deleting an outbound left routing rules pointing at its outboundTag (matched
traffic black-holed at the dispatcher), plus stale references in balancer
selectors / fallbackTag and other outbounds' dialerProxy.

The delete confirm now shows planOutboundDeletion's impact and applies the
cascade: rules keep a remaining balancerTag (else are dropped), the tag is
pulled from balancer selectors and fallbacks, dialerProxy references are
cleared, and a balancer whose selector is emptied is removed along with its
own now-targetless rules.

* refactor(xray): share one rule classifier across preview and apply

Code review flagged that the keep/drop predicate was transcribed twice — in
ruleImpacts (the delete-modal preview) and in applyCleanup (the mutation) — kept
in sync only by a parity test. Extract a single classifyRule() that both call,
so the preview can never disagree with what apply actually does.

Also harden balancersEmptiedBy to skip tagless balancers: an empty/missing tag
would otherwise enter the removed set as "" and silently drop every other
tagless balancer (only reachable via a hand-edited config, but a silent data
loss). And remove observersRemovedByDeletingBalancer, orphaned once BalancersTab
switched to planBalancerDeletion.

* fix(xray): null-guard reference cleanup against unvalidated configs

The PR review noted that classifyRule and applyCleanup dereferenced rule /
balancer entries directly, while the sibling propagateOutboundTagRename uses
optional chaining — because fetchXrayConfig falls back to the unvalidated parsed
object when Zod validation fails, a stray null in rules / balancers can survive
into the editor and would throw during the delete preview/apply.

Match that defensive style: classifyRule and balancersEmptiedBy read through
optional chaining, the balancer loop skips nullish entries, and the dialerProxy
walk guards the outbound. A delete on a hand-edited config with null entries now
degrades gracefully instead of throwing.
2026-06-29 12:52:18 +02:00
nima1024m 71aca2018a feat(a11y): screen-reader & keyboard accessibility across the panel (#5486) (#5652)
* feat(a11y): label list, toolbar & dashboard actions for screen readers

Phase 1 of #5486 (Android TalkBack support). Icon-only controls across
the management surfaces previously announced only their untranslated
icon name (e.g. "edit", "ellipsis") or nothing at all.

- Add aria-label to icon-only row-action and toolbar buttons across
  inbounds, clients, groups, hosts, nodes and xray
  (outbounds/routing/dns/balancers) lists, plus the dashboard cards.
- Make clickable bare icons and AntD Card actions keyboard-operable via
  role/tabIndex + Enter/Space (new activateOnKey helper); convert mobile
  dropdown triggers to buttons so they open from the keyboard.
- Fix the sidebar hamburger's mislabeled aria-label (was the dashboard
  label) and translate previously-hardcoded outbound menu labels.

New i18n keys in all 13 locales: sort, menu.openMenu,
pages.xray.outbound.moveToTop.

* feat(a11y): label modal, QR and copy/download controls for screen readers

Phase 2 of #5486. Modal and overlay controls relied on tooltips (not a
reliable accessible name) or were bare clickable icons with no keyboard
or screen-reader support.

- Add aria-label to copy/QR/download/info icon buttons in the inbound and
  client info modals, sub-links modal, QR panel, backup/log modals, and
  to the bare search/select inputs of the attach/detach client modals.
- Make click-to-copy QR codes and the IP-log refresh/clear, geofile
  reload and log refresh icons keyboard-operable (role/tabIndex +
  Enter/Space) with translated labels.
- Label the 2FA code input; drop the QrPanel download-image string
  fallback now that the key exists.

New i18n key in all 13 locales: downloadImage.

* feat(a11y): label form fields and shared form components for screen readers

Phase 3 of #5486. Form controls and shared form widgets were largely
unlabelled, and several remove controls were not keyboard-operable.

- SettingListItem now ties its title to the control via aria-labelledby,
  giving accessible names to the ~90 settings-tab inputs at once.
- InputAddon gains button semantics (role/tabIndex/Enter+Space) and an
  ariaLabel prop when used as an interactive remove control.
- Sparkline charts expose a role="img" summary of their latest values.
- Add aria-label to add/remove/regenerate icon buttons and bare
  inputs/selects across inbound, client and xray (dns/routing/balancer/
  outbound) forms; make clickable remove icons keyboard-operable; mark
  decorative help/target icons aria-hidden; label the JSON editor,
  date-time clear button, header-map remove, notification select-all and
  remark token chips.

New i18n keys in all 13 locales: regenerate, jsonEditor,
pages.xray.balancer.{costMatch,costValue,costRegexp}.

* chore(a11y): add eslint-plugin-jsx-a11y harness and fix flagged interactions

Phase 4 of #5486. Adds eslint-plugin-jsx-a11y (recommended ruleset,
scoped to .tsx) so screen-reader/keyboard regressions fail lint.

- Make the mobile node-card header a proper keyboard disclosure
  (role=button, aria-expanded, Enter/Space activation that ignores
  clicks on the nested action buttons) and drop the now-redundant
  stop-propagation click handlers the linter flagged on card-action
  wrappers in the node, client and inbound mobile cards.
- Disable jsx-a11y/no-autofocus: the autofocus on the login field and
  modal primary inputs is intentional focus management that helps
  screen-reader and keyboard users land on the right control.

make lint passes with the a11y ruleset enforced.

* feat(a11y): cover remaining deferred spots (settings tabs, sockopt, API docs)

Completes the panel sweep for #5486 by labelling the spots previously
left out of phases 1-4:

- NotifyTimeField (Telegram notifications): the mode, interval, unit and
  custom-cron inputs now carry aria-labels.
- The Sockopt toggle in transport options.
- Settings category tabs in icons-only (mobile) mode now expose the tab
  name as the icon's aria-label instead of the raw icon name.
- The Swagger API-docs view is wrapped in a labelled region landmark.

New i18n keys in all 13 locales: pages.settings.notifyTime.{interval,unit}.

* feat(a11y): label shared xray form components and remark field

Code review surfaced frontend/src/lib/xray/forms/ — shared form components
used by the host and inbound JSON forms — which the initial audit missed.

- FinalMaskForm (TCP/UDP final-mask editor): label the icon-only add and
  regenerate buttons and make all six remove icons keyboard-operable
  (role/tabIndex/Enter+Space); adds useTranslation to its sub-components.
- CustomSockoptList: the remove icon is now keyboard-operable.
- SniffingFields: aria-label on the otherwise label-less destOverride select.
- RemarkTemplateField: aria-label on the remark-variable picker button.

New i18n key in all 13 locales: pages.inbounds.sniffingDestOverride.

* feat(a11y): label client info modal and WireGuard config block

After rebasing onto the WireGuard client-config feature, re-apply the
ClientInfoModal copy/QR/IP-log aria-labels (the modal was restructured
upstream, so the original labels did not carry over) and label the new
ConfigBlock component's copy/download/QR actions. ConfigBlock's action
wrapper keeps its stop-propagation handler (a non-interactive guard for
the Collapse header) under a scoped jsx-a11y exception.

* fix(frontend): let npm install jsx-a11y under ESLint 10

eslint-plugin-jsx-a11y@6.10.2 declares a peer range that stops at ESLint 9,
but the panel is on ESLint 10, so `npm ci` aborts with ERESOLVE even though
the plugin runs fine on ESLint 10 with flat config. Add an npm override so
jsx-a11y accepts the project's ESLint version. This keeps normal peer
resolution (recharts' react-is peer still auto-installs) — no global
legacy-peer-deps and no manual react-is pin needed.

* fix(a11y): size mobile row triggers and move node expand role to chevron

Address automated review on #5652:
- add size="small" to the inbound/client/node mobile-card "more" dropdown
  triggers so they match the adjacent small Switch and the established
  desktop RowActions pattern.
- move the node card-head disclosure semantics (role/tabIndex/aria-expanded/
  keyboard) onto the chevron affordance so the expand control is no longer a
  role="button" wrapping the Switch, info button and dropdown. Mouse
  click-anywhere-to-expand is preserved on the header div.
2026-06-29 12:51:29 +02:00
MHSanaei 6c71b725da fix(clients): hide WireGuard config after detaching the WG inbound
The client info and QR modals rendered a WireGuard config whenever the
client still carried leftover WG key material (privateKey / publicKey /
allowedIPs / preSharedKey / keepAlive), regardless of whether a WireGuard
inbound was actually attached. After detaching the WG inbound the config
kept showing, built with an empty endpoint port and public key.

Gate wgConfigText on an attached WireGuard inbound (wgInbound) being
present, not just isWireguardClient(client), in both ClientInfoModal and
ClientQrModal.

Also rename the i18n key pages.clients.conf -> config and add the missing
pages.clients keys (wireguardConfig, config, bulkFlow, bulkFlowNoChange,
bulkFlowDisable) to all 12 non-English locales so each one matches en-US.
2026-06-29 01:15:37 +02:00
MHSanaei a329882e0e feat(wireguard): client config UX, collapsible config card, configurable DNS
Land the WireGuard client-config UX work on main (the upstream PR #5642
branch could not be pushed to).

- Reusable collapsible ConfigBlock (copy/download/QR, actions aligned right)
  for the client .conf, used by client info and the public sub page.
- Correct .conf: canonical PresharedKey casing and DNS sourced from the inbound
  (configurable per-inbound, default 1.1.1.1, 1.0.0.1).
- Configurable per-inbound DNS for WireGuard (schema + form + backend hint via
  InboundOption.WgDns); inert at the Xray layer.
- Public sub page now shows the WireGuard config, rebuilt from the share link;
  the Go wireguard:// link carries dns/presharedkey/keepalive for completeness.
- QR enabled for the wireguard:// link; link rows are compact like other protocols.
- Client information order is subscription, copy URL, WireGuard config; the
  redundant config tab is removed from the add/edit client modal.
- Drop the Inbound Information and QR Code row actions for WireGuard inbounds.
2026-06-29 00:50:34 +02:00
Nikan Zeyaei 60c54827aa feat: ldap skip tls verify (#5637)
* feat(ldap): add InsecureSkipVerify field and tlsConfig helper

Extract the inline TLS config at both LDAPS dial sites (FetchVlessFlags,
AuthenticateUser) into a tlsConfig(cfg) helper, and add a new
Config.InsecureSkipVerify bool that flows through to
tls.Config.InsecureSkipVerify. This unblocks enterprise environments
(e.g. Microsoft AD CS with internal CAs) where the server certificate
chain cannot be imported into the system trust store.

Behavior is identical when InsecureSkipVerify is false (the default) -
pure refactor + plumbing. The helper is unit-testable without a live
server, which is why it is extracted.

Closes https://github.com/MHSanaei/3x-ui/issues/5538

* feat(settings): add LdapInsecureSkipVerify setting

Plumb the new LDAP skip-TLS-verify toggle through the settings stack:
- AllSetting struct field (json/form tag: ldapInsecureSkipVerify)
- defaultValueMap default ("false")
- GetLdapInsecureSkipVerify() getter
- ldap_sync_job wiring into ldaputil.Config (FetchVlessFlags path)
- panel/user.go wiring into ldaputil.Config (AuthenticateUser path;
  the original issue's file list missed this)

Persistence is handled by UpdateAllSetting's reflect loop, matching
the existing pattern used by ldapUseTLS (no explicit setter).

Closes https://github.com/MHSanaei/3x-ui/issues/5538

* feat(ui): add Skip TLS verification switch in LDAP settings

Wire the new ldapInsecureSkipVerify setting into the hand-written
frontend model and Zod schema, and render it as a new Switch in
GeneralTab right under "Use TLS (LDAPS)". The switch is disabled
when TLS is off (the setting is meaningless without LDAPS) and shows
an insecure-warning description to make the security implication
visible to operators.

Also adds a Vitest round-trip test pinning schema acceptance and
model default-to-false behavior.

Closes https://github.com/MHSanaei/3x-ui/issues/5538

* chore(i18n): add Skip TLS verification strings to all locales

Add pages.settings.ldap.skipTlsVerify and skipTlsVerifyDesc to all 13
backend-served translation files, matching the existing repo
convention of keeping LDAP keys present in every locale (en-US, fa-IR,
ru-RU, zh-CN, zh-TW, pt-BR, ar-EG, uk-UA, id-ID, tr-TR, vi-VN, ja-JP,
es-ES). No translation-parity test exists in CI, but every other
LDAP key is replicated across all files, so this keeps the
invariant intact.

Closes https://github.com/MHSanaei/3x-ui/issues/5538

* chore(codegen): regenerate frontend artifacts

Regenerate frontend/src/generated/{zod,types,schemas,examples}.ts
and frontend/public/openapi.json via `npm run gen` to reflect the
new ldapInsecureSkipVerify field. The codegen CI job runs
`git diff --exit-code` on these files; failing to commit them would
break the build.

Closes https://github.com/MHSanaei/3x-ui/issues/5538
2026-06-28 18:10:38 +02:00
n0ctal aef35ee0de fix(sync): mark node dirty inside the mutation transaction (atomic ConfigDirty) (#5611)
* fix(sync): mark node dirty inside the mutation transaction

ConfigDirty is currently set by MarkNodeDirty AFTER the mutation, on a
separate DB handle outside the mutation's transaction. A crash or error
between the committed change and the mark leaves a committed config
change that never reconciles to the node (silent drift). Add
MarkNodeDirtyTx(tx, id) and call it inside each mutation's transaction so
the dirty mark commits atomically with the change.

* fix(test): initialize DB in TestResolveInboundAddress and group gorm import

Two CI failures on this branch:

- race (-shuffle=on): TestResolveInboundAddress reaches resolveInboundAddress -> configuredPublicHost -> GetSubDomain, which reads the global DB. The test never initialized one, relying on another sub-package test to do so first; under shuffle it ran first and nil-dereferenced gorm. Call initSubDB(t) so it is self-sufficient (empty DB yields an empty subDomain, so the subscriber-host fallback still holds).

- golangci goimports: gorm.io/gorm was grouped with the github.com/mhsanaei/3x-ui local imports in node_dirty_test.go. Move it into the third-party group.
2026-06-28 15:18:28 +02:00
n0ctal 2b10808fbd fix(settings): require re-2FA confirmation for sensitive setting changes (#5610)
* fix(settings): require server-side 2fa for sensitive changes

* fix(lint): group third-party imports separately from local (goimports)

golangci-lint goimports flagged setting.go and setting_security_test.go because xlzd/gotp and gorm.io/gorm were mixed into the github.com/mhsanaei/3x-ui local-prefix group. Move them into the third-party group so the local imports stand alone.
2026-06-28 15:17:15 +02:00
nima1024m 25a86b9ee2 feat(balancers): tabbed Observatory/Burst Observatory form (#5627)
* feat(balancers): tabbed Observatory/Burst form replacing raw JSON

Replace the raw JSON editor for the Observatory / Burst Observatory sections
with a proper Ant Design form, and split the Balancers page into two sub-tabs:
"Balancer Settings" (the existing table) and "Observatory".

Observers stay fully auto-managed by balancer strategy through the existing
syncObservatories logic: users edit only the tunable probe fields, the
subjectSelector is shown read-only since it is derived from the balancers, and
deleting the last balancer that needs an observer now warns in the confirm
dialog that the observer will be removed too. Overlapping selectors keep an
observer alive while any balancer still references it.

Also add the previously missing pingConfig.httpMethod field (HEAD/GET) and
translations for the new strings across all 13 locales.

* refactor(balancers): tighten httpMethod typing and align connectivity default

Address automated review feedback on the Observatory form:
- Use the ObservatoryHttpMethodSchema enum for pingConfig.httpMethod instead of
  a free-form z.string(), and drive the HTTP method Select from its options.
  Removes the previously dead enum export and the duplicate local list, and
  types the field as 'HEAD' | 'GET'.
- Align the schema's connectivity default with DEFAULT_BURST_OBSERVATORY (the
  hicloud URL) so it matches what burst observers are actually created with.

No behavior change.
2026-06-28 15:02:18 +02:00
nima1024m 51ffba5961 fix(balancers): defer validation errors until touched or save (#5626)
The Add Balancer modal parsed its empty initial state through
BalancerFormSchema on mount and bound Form.Item validateStatus/help
directly to the result, so "Tag is required" and "Pick at least one
outbound" rendered the moment the modal opened, before any user input.

Gate the inline errors behind per-field touched tracking plus a
submit-attempted flag, and drop the disabled Create button so a save
attempt surfaces the errors (matching RuleFormModal). The existing
key-based remount in BalancersTab resets the flags on each open.

Add a regression test asserting no errors on open and errors only
after a save attempt.
2026-06-28 15:01:53 +02:00
n0ctal 5713c09980 fix(runtime): refresh cached node remotes on identity change (#5614) 2026-06-28 15:01:18 +02:00
n0ctal 7f8cbf4c4b fix(web): tighten database restore body-cap exemption (#5609) 2026-06-28 15:00:55 +02:00
MHSanaei bbfbd7eba6 Bump minimum eligible Xray version
Update Xray release filtering to only include versions at or above v26.6.27 (previously v26.4.25). Also mark `google.golang.org/protobuf` as a direct dependency in `go.mod` by removing the `// indirect` annotation.
2026-06-28 14:57:43 +02:00
MHSanaei 79069d2b64 fix(wireguard): allocate client IPs in the existing peer subnet
defaultWireguardClients always allocated new tunnel addresses from the
hardcoded 10.0.0.0/24 base, so a legacy or migrated inbound whose peers
live in a different subnet (e.g. 172.16.0.0/24) got new clients in an
unrelated, unroutable range. Derive the allocation base from the existing
peers' /24 and fall back to 10.0.0.0/24 only when there are none.
2026-06-28 14:41:24 +02:00
MHSanaei 9c8cd08f90 feat(wireguard): multi-client support
WireGuard inbounds now manage per-client peers using xray-core's native WireGuard users (AddUser/RemoveUser). Each client lives in settings.clients (canonical, like every other protocol) and is projected to peers[] only when emitting the xray config, at level 0 so the dispatcher's per-user traffic/online counters work with no extra plumbing.

Backend: internal/util/wireguard gains KeyToHex (base64 to hex for the gRPC path), PublicKeyFromPrivate and GenerateWireguardPSK; xray/api.go builds a wireguard account in AddUser with hex keys (RemoveUser already worked); client CRUD generates a keypair and allocates a unique tunnel address per client and never rotates keys on edit; an idempotent migration converts legacy settings.peers into managed clients; WireGuard is included in the raw subscription.

Frontend: WireGuard in the add-client modal with keys on the credential tab, client schema, per-client QR/link/.conf, inbound form reduced to server settings; i18n added across 13 locales.

Fix: guard the settings[clients] assertion in add/update so a legacy WireGuard inbound stored without a clients key no longer panics.
2026-06-28 00:44:38 +02:00
MHSanaei 33aada0c7c feat(xhttp): default xmux maxConnections to 6
xray-core v26.6.27 changed the XHTTP client xmux default to maxConnections=6 (anti-RKN). The panel previously sent maxConnections=0, which overrode that default; default XHttpXmuxSchema to 6 so new outbounds adopt it and the wire-exclusivity rule drops maxConcurrency accordingly.
2026-06-27 20:26:03 +02:00
MHSanaei e44075a6e0 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.
2026-06-27 20:25:45 +02:00
MHSanaei 56b0be0b6a fix(lint): use errors.Is for io.EOF comparison in sys_linux
The errorlint linter rejects direct error comparison with != because it
fails on wrapped errors. Compare via errors.Is(err, io.EOF) instead.
2026-06-27 16:38:07 +02:00
MHSanaei 9b8a0c9b17 feat(groups): reset group traffic without touching client counters
The group page shows traffic counting per group, but the only reset
available zeroed every member client's up/down counters (and their
quotas) via bulkResetTraffic. Group traffic is a derived sum of client
traffic, so zeroing the group display previously required mutating the
clients themselves.

Add a display-only baseline: ClientGroup gains reset_up/reset_down
columns (additive, handled by AutoMigrate). ResetGroupTraffic snapshots
the group's current up/down sum into the baseline, and ListGroups now
reports max(0, sum - baseline). Client counters are left untouched and
no Xray restart is triggered. A new POST /panel/api/clients/groups/
resetTraffic endpoint drives it, creating the client_groups row when the
group exists only as a derived label.

The groups page action now calls the new endpoint; confirm/success
strings updated across all 13 locales to reflect group-only semantics.
2026-06-27 16:33:36 +02:00
MHSanaei d1c0d77023 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.
2026-06-27 15:58:36 +02:00
MHSanaei 63fca9ef88 docs: correct false RTL claim and stale Vite version in CONTRIBUTING.md
RTL is not wired through AntD ConfigProvider direction (no such code exists; only the Jalali date picker is RTL-aware), so the guide now states that accurately instead of claiming a mechanism that is absent. Replace the hardcoded Vite version (said 8.0.16; package.json pins 8.1.0) with a pointer to read the live version, removing the drift source.
2026-06-27 15:48:51 +02:00
MHSanaei 2e851978e6 chore: add Makefile as canonical task runner
make verify reproduces the CI PR gate locally (gen-check, lint, typecheck, test, build) with the same flags as ci.yml: go test -shuffle=on -count=1 over the node_modules-filtered package list, the internal/web/dist go:embed stub, and the generated-file staleness diff. Run make help for all targets.
2026-06-27 15:42:23 +02:00
MHSanaei fa1a19c03c 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.
2026-06-27 15:42:22 +02:00
MHSanaei 7efa0d9ddd docs: add CLAUDE.md agent guides for root and frontend
Operational guides the Claude Code CLI auto-loads. The root file covers the stack, repo map, hard rules (no // comments, the endpoints.ts registry, the openapigen StructAllow allowlist, i18n locales, migrations), Go and frontend conventions, and the make verify gate. frontend/CLAUDE.md covers the React + AntD 6 + Vite setup. Both link to CONTRIBUTING.md and frontend/README.md instead of duplicating them, and every claim was fact-checked against the source.
2026-06-27 15:42:11 +02:00
MHSanaei d12b186a69 test(sub): align identity-token test with first-link-only EMAIL
876d55f2 made {{EMAIL}}/{{USERNAME}} appear on the first sub-body link
only, but TestIdentityTokensEverywhere still asserted the email survived
on every repeat body link, breaking the go-test and race CI jobs. Update
it to assert the repeat body link drops the identity token while the
display/QR remark keeps it; the first-link case is covered by
TestEmailOnFirstLinkOnly.
2026-06-27 13:56:45 +02:00
MHSanaei 39eb5baf42 fix(inbound): convert legacy externalProxy to hosts on import
An inbound exported from a build that predated the hosts table carries
its external proxies inline in streamSettings.externalProxy. The startup
migration that converts those to host rows runs once and is gated off
afterwards, so it never sees a freshly imported inbound, leaving its
external proxies stranded in streamSettings (never surfaced as Hosts).

Extract the migration's per-inbound conversion into a shared
database.CreateHostsFromExternalProxy and run it inside the AddInbound
transaction. No-op for inbounds without externalProxy (everything the
current UI builds), so it only fires on such imports.
2026-06-27 13:50:06 +02:00
MHSanaei 876d55f274 fix(sub): show {{EMAIL}} on first sub-body link only
The remark template's {{EMAIL}}/{{USERNAME}} were repeated on every link
of a subscription. Strip them from subsequent body links like the usage
tokens, so the email appears once on the first link. Display/QR remarks
and the other client tokens are unaffected.
2026-06-27 12:42:12 +02:00
Nikan Zeyaei 1bad2fcba1 feat(backup): prefix backup filenames with date and time (#5606)
* feat(backup): add YYYY-MM-DD_ date prefix to backup filenames

Refs #5584

* feat(backup): prefix backup filenames with date and time

* fix(backup): put host before date in backup filename

Backup filenames now read {host}_{date}{ext} (e.g. panel.example.com_2026-06-27_000000.db) instead of {date}_{host}{ext}, so files group by server first then sort chronologically within each server.
2026-06-27 12:08:20 +02:00
MHSanaei 4c177f0cf1 fix(shadowsocks): send per-user Account for SS-2022 runtime AddUser
SS-2022 user updates passed shadowsocks_2022.ServerConfig (the inbound-level
config) as the gRPC user account. The core rejects it with "Unknown account
type" because only shadowsocks_2022.Account implements AsAccount(), so live
AddUser failed and renewed/reset/added users stayed inactive until the 30s
auto-restart rebuilt the inbound from the DB.

Use shadowsocks_2022.Account{Key: password} (the per-user type, matching
xray-core's own multi-user builder) so changes apply immediately without a
restart.

Fixes #5597
2026-06-27 12:00:38 +02:00
MHSanaei 797b08cd07 fix(balancers): create burst observer for random/roundRobin with fallbackTag
xray-core's Random/RoundRobinStrategy calls RequireFeatures(Observatory) whenever a fallbackTag is set, so a balancer that declares a fallback but has no observatory aborts startup with 'core: not all dependencies are resolved'. syncObservatories never created an observer for these strategies, crashing the core on any load balancer that used a fallback (the default 'random' strategy with a fallbackTag, exactly issue #5605).

Treat random/roundRobin balancers that set a fallbackTag as requiring the burst observer. Also make the burst observer strictly requirement-driven (mirroring the leastPing/observatory path) so clearing the last fallbackTag drops it again instead of leaving a dead observer that forces needless restarts and probing.

Closes #5605
2026-06-27 11:46:19 +02:00
MHSanaei 439245d42b feat(inbounds): apply remark template to Export all inbound links
Export-all now renders links through the subscription engine via a new GET /panel/api/inbounds/allLinks endpoint, so the configured remark template (name-only display part) is applied per client -- matching the client info/QR pages. Previously it generated links client-side with a hardcoded inbound-email remark.

Host-aware: managed Host endpoints win over the plain link, so HOST and per-host variants render; duplicate client JSON entries are deduped by email and the list is scoped to the logged-in user.
2026-06-27 11:22:45 +02:00
MHSanaei 535b89a352 fix(routing): write lowercase L4 network to xray config, display uppercase in UI 2026-06-27 11:15:13 +02:00
Tomi lla 7a2179535a fix(settings): normalize API token timestamps (#5599)
* fix(settings): normalize API token timestamps

* refactor(api-token): share timestamp threshold

---------

Co-authored-by: Tomilla <5007859+Tomilla@users.noreply.github.com>
2026-06-27 10:30:58 +02:00
MHSanaei 6964d84742 feat(reality): add live REALITY target scanner with IP/CIDR discovery
Replace the static reality-targets list with a server-side TLS 1.3 probe that checks TLS 1.3 + HTTP/2 + X25519 + a trusted certificate.

- Single-domain validate auto-fills target and serverNames from the cert SAN
- Discovery scans an IP/CIDR without SNI to find new targets from their certificates, deduped and ranked by feasibility then latency, private-IP guarded via netsafe
- New endpoints scanRealityTarget and scanRealityTargets with RealityScanResult, plus openapigen and api-docs entries
- Add scanner strings to all 13 locales
- Replace deprecated AntD Alert message prop with title across the panel
2026-06-26 22:18:47 +02:00
MHSanaei 451263f1db feat(sidebar): add documentation link button
Add a Docs button next to the donate button in the sidebar and mobile drawer linking to https://docs.sanaei.dev/, with menu.docs translations across all 13 languages.
2026-06-26 18:55:32 +02:00
MHSanaei 8e4c368200 feat(update): allow opting into the dev channel from a stable build
The panel version button opened the GitHub releases page on a stable, up-to-date build, and the dev-channel toggle only rendered on dev builds, so there was no in-panel path from stable to dev. Drop the IsDevBuild() guard in devChannelActive (the toggle alone drives the channel now), always open the update modal instead of releases, and always render the Dev channel switch.
2026-06-26 18:01:51 +02:00
MHSanaei 522b1b64b0 fix(logger): prevent nil-deref panic in migrate/setting CLI paths
The package-level logger is nil until InitLogger runs, which only happens in runWebServer. The migrate and setting subcommands log without initializing it; PR #5520 added a logger.Info on a success path in MigrationRestoreVisionFlow, so 'x-ui migrate' segfaults on installs with a VLESS inbound needing Vision-flow restoration.

Initialize logger to a usable default at package load so no code path can nil-deref it, and set up the dual backend in migrateDb so migration steps are logged like runWebServer.

Fixes #5581
2026-06-26 11:40:13 +02:00
MHSanaei b1fb39c486 v3.4.1 2026-06-26 00:52:00 +02:00
MHSanaei 9381fa284b feat(logs): add auto-update toggle to Access Logs and Logs viewers
A checkbox in both the Xray Access Logs and panel Logs modals polls the
existing refresh every 5s while enabled, respecting the current row count,
level/filter, and Direct/Blocked/Proxy selections. The poller tears down on
close or untoggle. Adds a localized pages.index.autoUpdate key to all 13 locales.
2026-06-26 00:43:32 +02:00
MHSanaei 30796dc2ce 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.
2026-06-26 00:35:34 +02:00
MHSanaei dc6d13b58f 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
2026-06-26 00:10:30 +02:00
MHSanaei e27f2490b2 feat(logs): label the Xray access-log viewer 'Access Logs' across all languages
Distinguishes the access-log modal from the panel 'Logs' viewer it shares a
title with. Adds the accessLogs key to all 13 translation files.
2026-06-25 23:59:59 +02:00
MHSanaei df0e52cda8 fix(logs): render plain log notices verbatim instead of mangling them as timestamps
A plain message with no timestamp/level (e.g. the Windows 'Syslog is not
supported' notice) was parsed by the app-log branch, which took the first
three words as date/time/level and dropped the rest. Match the strict
'YYYY/MM/DD LEVEL - body' shape only, keep other lines whole, and drop the
leading separator when there is no stamp or level.
2026-06-25 23:59:49 +02:00
MHSanaei 1d69508263 feat(logs): add 1000 rows option and drop 10 from log row count selectors 2026-06-25 23:47:07 +02:00
MHSanaei 8f65aa7e4b fix(hosts): show proper page title instead of falling back to 3X-UI 2026-06-25 23:43:14 +02:00
MHSanaei 293c1e44dc perf(metrics): tiered rollup history (7d at ~1.5MB) and cleaner ranges
Replace the flat 48h@2s ring buffer with a 3-tier rollup ladder (2s/1h, 1m/48h, 10m/7d). A sample feeds every tier and rolls up into progressively coarser averages, so per-metric footprint drops from ~21MB to ~1.5MB (measured, 16 system metrics) while extending the range from 48h to 7 days. aggregate() picks the finest tier covering the requested span; a pre-tier flat gob is migrated by replaying its samples through the rollup.

Tidy the dashboard ranges to a professional ladder: 2m, 1h, 3h, 6h, 12h, 24h, 2d, 7d (drop the irregular 2h/5h, the redundant 30m, and the excessive 30d). The allow-list keeps bucket 30 because the node history panel uses it.

Add an initial FreeOSMemory about 60s after boot to reclaim the startup and metric-restore peak instead of waiting for the periodic release. Cover the rollup, tier selection, round-trip, and footprint with tests.
2026-06-25 23:30:13 +02:00
MHSanaei 69ad8b76e1 perf(memory): report real RSS and cut footprint via GOGC + periodic release
The Usage card showed runtime.MemStats.Sys, a never-shrinking high-water mark of reserved address space that also counts memory already returned to the OS, so it overstated real usage (e.g. ~300 MB on an idle 1-client server). Report process RSS instead so the number matches the OS and drops as memory is freed.

Replace the auto GOMEMLIMIT that targeted ~90 percent of total system RAM (a near no-op while the heap sits far below the limit, and a GC-thrash risk on small/shared VPS per go.dev/doc/gc-guide) with: a lower default GOGC (XUI_GOGC, default 75), a periodic debug.FreeOSMemory job (XUI_MEMORY_RELEASE_INTERVAL, default 10m, 0 disables), and a soft limit applied only from an explicit budget (GOMEMLIMIT, XUI_MEMORY_LIMIT, or a real cgroup cap at 90 percent).
2026-06-25 22:16:38 +02:00
MHSanaei b32837e523 fix(node): import per-client traffic history on first sync of a node-hosted inbound
On the first sync of a node-hosted inbound, the central inbound adopted the
node's full lifetime counter but every client_traffics row was seeded at 0 (with
the delta baseline set to the node's current counter). So adding or migrating a
node that already had traffic kept the inbound total correct while every
per-client counter restarted from zero, and the master under-reported per-client
usage by the entire pre-attach history.

Seed a new client_traffics row from the node counter only when the inbound was
created during the same sync (a genuine node-add / inbound re-import); a client
reappearing under a pre-existing inbound still seeds 0, preserving the ghost
protection in TestGhostData_NoPhantomTraffic. The seed is additionally gated on
the delete tombstone so a just-deleted client cannot be resurrected if its
inbound is recreated. Baseline still equals the seeded value, so the next sync
delta is 0 and no traffic is double counted.

Adds TestNodeAdd_ImportsClientHistoryWithNewInbound and
TestNodeAdd_TombstonedClientNotResurrected.
2026-06-25 21:19:27 +02:00
MHSanaei 9dec15bd4b feat(uninstall): offer to purge PostgreSQL when removing the panel 2026-06-25 19:40:10 +02:00
MHSanaei e64e998194 feat(clients): add bulk enable/disable and move selection actions into More menu
Add bulkEnable/bulkDisable named endpoints backed by a shared internal impl, and consolidate the per-selection actions (attach, detach, add to group, ungroup, enable, disable, adjust, sub links) into the clients table's More dropdown so the toolbar only shows the selection count and delete. Translate the new enable/disable confirm dialogs and toasts across all 13 locales.
2026-06-25 19:21:42 +02:00
MHSanaei a4be5a0deb fix(sub): recover {{TRAFFIC_USED}} for clients with orphaned traffic rows
statsForClient resolved usage only through paths keyed by client_traffics.inbound_id (preloaded ClientStats + the statsByEmail index). That id is written once by AddClientStat and never updated, so an inbound delete+recreate orphans the row from every loaded inbound, both paths miss, and the zero-traffic placeholder makes {{TRAFFIC_USED}} read 0.00B for pre-existing clients while the sub-info header (AggregateTrafficByEmails, email-keyed) stays correct.

Add a last-resort lookup by the globally-unique email, cached into statsByEmail for the request. Closes #5567.
2026-06-25 18:18:47 +02:00
MHSanaei e4b881e58a feat(panel): surface dev-build version in UI, bot, and CLI
A dev build now shows its `dev+<commit>` identity instead of a misleading stable-looking version in the sidebar badge, dashboard card, update modal, Telegram status report, startup log, and `x-ui -v`. Adds a shared formatPanelVersion helper (single v prefix; dev labels shown verbatim) and fixes the mobile-tag double-v.

Renames the version getters for clarity: config.GetVersion to GetBaseVersion (raw embedded version), config.GetReportedVersion to GetPanelVersion (advertised/displayed), and the xray process GetVersion to GetXrayVersion.
2026-06-25 02:36:41 +02:00
MHSanaei 2adb59bd64 feat(install): add dev-latest install option and sync README translations
install.sh now accepts `dev-latest` (or `dev`) to install the rolling per-commit dev pre-release, bypassing the numeric version-floor check.

README.md documents the version-pinned and dev-latest install commands. All six language READMEs are brought back in sync with the English source: the new install instructions plus the previously-missing "Unattended install & cloud images" section, the XUI_TUNNEL_HEALTH_* env vars, and the custom subscription templates link.
2026-06-25 02:36:30 +02:00
MHSanaei bcd1358032 fix(nodes): report dev builds as dev+<commit> so updated nodes aren't flagged stale
A node's status reported config.GetVersion() (3.4.0) even on a dev build, so the master compared it against its own dev latestVersion (dev+<sha>) and every node showed 'update available'. Nodes on a dev build now report dev+<short commit>, matching the master's format, so a node on the current dev commit compares as up to date.
2026-06-25 00:46:43 +02:00
MHSanaei e8878b71a4 feat(nodes): add Dev channel option to node panel updates
The node update confirm dialog now offers a 'Dev channel (latest commit)' choice. The dev flag threads master -> nodes/updatePanel -> UpdatePanels -> remote.UpdatePanel -> the node's updatePanel endpoint, which calls StartUpdateChannel(dev) to install the rolling dev-latest build. With no dev flag the node keeps following its own channel setting.
2026-06-25 00:29:03 +02:00
MHSanaei 11c5b53fac feat(sub): add PROTOCOL, TRANSPORT, SECURITY remark template variables 2026-06-25 00:12:25 +02:00
MHSanaei 896016f7f6 fix(web): remove deleted multi-inbound client from runtime regardless of shared email (#5543)
DelInboundClientByEmail gated the runtime RemoveUser/DeleteUser (and its
push-plan resolution) on !emailShared. But Xray users are keyed by inbound
tag + email, so a client attached to two inbounds left its user live in the
running Xray of every inbound where the email was still shared by a sibling
inbound, until an Xray restart.

Decouple the per-inbound runtime removal from emailShared; keep emailShared
only for preserving the shared email-keyed client_traffics/IP rows.
2026-06-24 22:43:18 +02:00
MHSanaei e2d25d0ac7 fix(web): show subscription outbounds in dialer proxy dropdown (#5540)
The outbound edit form's Dialer Proxy dropdown only listed local outbounds because subscriptionOutboundTags never reached OutboundsTab. Thread it through XrayPage and feed a dedicated dialerProxyTags list (local non-blackhole outbounds plus subscription tags, excluding the outbound being edited) to SockoptForm. Tag-uniqueness validation still uses the full local tag set, so the blackhole outbound is hidden only from the dropdown, matching HostSockoptForm.
2026-06-24 22:35:39 +02:00
Rick Sanchez fe025e8af3 feat(xray): add tunnel health monitor (#5480)
* feat(xray): add tunnel health monitor

* fix(tunnelmonitor): reuse netproxy client and init logger in tests

Replace the duplicated newHTTPClient/dialContextWithProxy with netproxy.NewHTTPClient, which centralises the http/https/socks5 handling and avoids the dial-goroutine connection leak on context cancellation. Cap failures at the threshold during cooldown so the counter stays a true consecutive-failure count. Add TestMain to initialise the logger and fix the nil-pointer panic in the success-after-failure path.

* fix(tunnelmonitor): observable recovery, signal headroom, and hardening

Address the remaining review findings on the tunnel health monitor:

- Recovery is now synchronous and observable: the callback calls
  server.RestartXray() directly and returns its error instead of just
  enqueuing SIGUSR1, so a failed restart no longer masks as success and
  arms the cooldown while the tunnel is still down.
- Give the OS signal channel headroom (buffer 8) so producers cannot
  starve a SIGTERM/SIGINT out of the single slot.
- Warn at startup when the monitor is enabled without a proxy, since the
  probe then measures host connectivity rather than the xray tunnel.
- Cap failures at the threshold in the nil-recover branch too, matching
  the cooldown cap.
- Document the XUI_TUNNEL_HEALTH_* vars in .env.example and the README.
- Add tests for status-code classification, Normalize bounds, New proxy
  scheme errors, the recovery-error and nil-recover paths, the cooldown
  cap, and Run context cancellation (coverage 90%).

---------

Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
2026-06-24 22:01:37 +02:00
FunLay123 3ba43bd86d feat(web): vless encryption new modes (#5517)
* feat(web): add vless encryption new modes

* feat(web): add translations for vless encryption modes

* feat(translation): bring "vlessAuthX25519" and "vlessAuthMlkem768" to general form
2026-06-24 21:22:42 +02:00
w3struk ae9bbdf267 fix(web): serve panel SPA routes from NoRoute (#5536)
* fix(web): serve panel SPA routes from NoRoute

Return the React shell for authenticated panel document routes that are not explicitly registered in Gin, such as /panel/hosts. Keep API, CSRF, static-file, method, and Accept exclusions so API misses remain 404 and auth semantics stay unchanged.

* fix(web): remove unreachable panel path guard

The panel path is always built by appending /panel, so it can never be empty.
Remove the redundant fallback branch without changing SPA routing behavior.

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

* fix(web): allowlist static-asset extensions in SPA fallback

The blanket path.Ext check rejected any panel route whose last segment contained a dot, which would reintroduce the refresh 404 for a future client route carrying a dotted parameter (version, domain, or email-like value). Restrict the static-asset exclusion to a known, case-insensitive extension allowlist and add predicate regression cases.
2026-06-24 21:19:12 +02:00
MHSanaei 2830f97f50 feat(x-ui.sh): add Dev channel update option to the management menu 2026-06-24 19:12:44 +02:00
MHSanaei 1d1128cf94 fix(update): read setUpdateChannel body as form field, not JSON
The panel's axios layer posts application/x-www-form-urlencoded, so the dev-channel toggle sent dev=true and ShouldBindJSON failed with 'invalid character d'. Parse c.PostForm("dev") to match the codebase's form-encoded POST convention.
2026-06-24 18:24:54 +02:00
MHSanaei aad2b3eb1e 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.
2026-06-24 18:11:22 +02:00
MHSanaei 93ff60e568 fix(tgbot): reload bot on settings save so a new token takes effect without a panel restart
The Telegram bot was only started at panel boot, so saving a token or toggling tgBotEnable persisted to the DB but never reached the running bot until a full restart, making it look like the token did not save (issue #5539). The settings/update controller now reconciles the bot the same way panelOutbound reconciles Xray: when tgBotEnable, the token, chat ID, or API server change, it stops/(re)starts the bot and updates the event-bus subscription.
2026-06-24 17:34:05 +02:00
MHSanaei 23e73cd4a3 fix(clients): use new email after rename and de-duplicate save toast
On client edit the post-update calls (attach/detach/externalLinks) keyed by the original email, so renaming a client made setExternalLinks fail with record-not-found. Key them by the updated email instead.

Each of those sub-step POSTs also auto-toasted its own success, so a save fired the 'Inbound client has been updated' toast twice (or more). Add a silentSuccess HttpUtil option that suppresses the redundant success toast while still surfacing errors and the node-offline warning, and apply it to the attach/detach/externalLinks mutations.
2026-06-24 17:10:17 +02:00
MHSanaei b0c1156dd6 fix(sub): drive display remarks from the template and split multi-host subpage links
Unify remark generation around the Remark Template. Display contexts (Clients-page QR/Info modals and the HTML sub info page) now render the template name-only client/identity part instead of a hardcoded fallback; the subscription body keeps the full template on a client first link and name-only thereafter. The default template gains the email token so the client email shows by default again (#5532).

BuildPageData now splits each multi-link entry (one link per host of an inbound) into a separate row, so the sub page no longer collapses several host links onto a single mangled line. QR captions on the Clients QR modal and the sub page reuse the link fragment remark.
2026-06-24 16:45:23 +02:00
MHSanaei 5dbd5b1d12 fix(sub): restore client email in panel copy/QR link remark (#5532)
Display-context links (Clients page QR + Information modals and the sub info page) dropped the client email from the link fragment in 3.4.0, showing only the inbound remark. Append the email back so the imported profile keeps its per-client label: inbound-host-email when a host is set, inbound-email otherwise. The usage template stays bypassed in display context, so no traffic or expiry data leaks.
2026-06-24 15:25:41 +02:00
MHSanaei bd60e770f4 fix(outbound): preserve custom headers for HTTP outbounds (#5519)
The Outbounds form routed HTTP through the SOCKS-shared simpleAuth adapter, which only knew address/port/user/pass, so xray's top-level settings.headers was dropped on both load and save. Opening and re-saving an HTTP outbound destroyed its headers.

Add headers to the HTTP wire/form schemas, round-trip it via dedicated httpFromWire/httpToWire helpers, and expose a HeaderMapEditor in the form. Only settings-level headers round-trip; xray-core ignores per-server headers.
2026-06-24 14:22:25 +02:00
MHSanaei a5e865c109 fix(backup): name Telegram backups after webDomain/IP instead of x-ui
The bot's ServerService is a separate instance whose mutex-guarded LastStatus is never populated (only RefreshStatus fills it, which the bot never calls), so backupHost's public-IP fallback never fired and bot backups collapsed to x-ui when no webDomain was set.

Resolve the public IP directly via a new mutex-guarded resolvePublicIPs helper (extracted from GetStatus and shared with it) so the bot path gets a real address. Panel downloads keep using the browser request host; the Telegram bot falls back to webDomain then public IP.
2026-06-24 14:12:41 +02:00
Rouzbeh† 82600936d6 fix(flow): restore XTLS Vision when an inbound becomes flow-eligible (#5520)
* fix(flow): restore XTLS Vision when an inbound becomes flow-eligible

clientWithInboundFlow strips Vision from a VLESS client whenever the target
inbound is not flow-eligible at client-write time — e.g. an XHTTP inbound
before its vlessenc (ML-KEM) encryption is set, or a client attached to such
an inbound. Nothing restored the flow once the inbound later became eligible:
an inbound edit stores its settings verbatim and never re-gates the clients.
So enabling encryption on an existing XHTTP inbound left every client without
flow, and the generated configs, share links and subscriptions silently
dropped flow=xtls-rprx-vision — most visibly on node inbounds and on any
inbound where encryption was turned on after the clients existed.

Restore the flow at the two points where an inbound can become eligible:

- UpdateInbound: after the new stream/settings are final, re-add Vision to
  clients that currently carry no flow but whose intended flow (their
  flow_override on a sibling inbound, via EffectiveFlowByEmail) is Vision —
  only when the inbound is now flow-eligible.
- MigrationRestoreVisionFlow: a one-time, idempotent boot migration that
  applies the same repair to existing installs and refreshes flow_override
  via SyncInbound.

The repair is conservative: it never invents a flow for a client that has
none anywhere, never overwrites an explicit flow, and is a no-op on healthy
installs. Adds EffectiveFlowByEmail and a unit test covering keep/skip/no-op
cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* style(flow): serialize restored settings with MarshalIndent

Match the indented JSON used by the adjacent timestamp block in UpdateInbound
and the externalProxy migration, so a restored inbound's settings column keeps
the same multi-line format as everything else (review nit on #5520).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* perf(flow): batch the intended-flow lookup and run it on the active tx

restoreVisionFlowForEligibleInbound resolved each empty-flow client's intended
flow with EffectiveFlowByEmail, which issued two queries per client
(GetRecordByEmail + EffectiveFlow). A client that genuinely uses no Vision keeps
an empty flow forever, so it was re-queried on every UpdateInbound and every
boot — O(clients) queries per save on a Reality/TCP or XHTTP+vlessenc inbound
carrying many non-Vision clients, executed inside the serialized writer
transaction.

Replace it with EffectiveFlowsByEmails: collect every empty-flow email first and
resolve them in a single batched join over client_inbounds + clients (lowest
inbound_id wins, same rule as before), chunked for the SQLite bind-var limit.

Also thread the active tx through restoreVisionFlowForEligibleInbound so the
read runs on the writer's own connection while it holds the lock instead of a
separate pooled connection (UpdateInbound passes its tx; the boot migration
passes nil → GetDB() as before).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 13:02:42 +02:00
Rouzbeh† 14de0557f9 feat(clients): bulk-set XTLS flow from the Adjust dialog (#5524)
* feat(clients): bulk-set XTLS flow from the Adjust dialog

Add a "Set flow" dropdown to the bulk Adjust dialog so an admin can set or
clear the XTLS flow on all selected clients at once, alongside the existing
days/traffic bumps. Empty by default (no effect on save); "Disable" clears
flow, and the two vision values mirror the per-client credential tab.

Flow rides the existing inbound-JSON -> SyncInbound path (ClientRecord.Flow +
client_inbounds.flow_override), so no new endpoint, DB column, or migration.
Setting a vision flow is gated by inboundCanEnableTlsFlow: ineligible inbounds
are left untouched and reported as skipped; clearing is always allowed. A real
flow change requests an xray restart (local) or a node reconcile (remote).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(clients): keep days/traffic write when bulk flow is ineligible

Address review on the bulk-flow-adjust PR:

- Blocking: a client adjusted with both a days/traffic delta and a flow
  directive on a flow-ineligible inbound had the flow-ineligibility recorded
  into the same skip set that gates the ClientTraffic write, so the inbound
  JSON / ClientRecord advanced but ClientTraffic did not — divergent stores,
  and the client misreported as skipped. Track flow ineligibility in its own
  map (bulkInboundAdjustResult.flowIneligible) so it only feeds the final
  Skipped report and never suppresses the expiry/total persistence.
- Drop the broad delete(skippedReasons, email): flow reasons no longer enter
  skippedReasons, so honoring a flow can no longer erase an unrelated skip
  reason (unlimited expiry, a real persistence error on another inbound).
- Drop the inline comment block from ClientBulkAdjustModal.tsx (file had none);
  move the whitelist-sync note next to bulkFlowAllowed, the source of truth.
- Document the optional flow field in the bulkAdjust API-docs example
  (endpoints.ts) and regenerate openapi.json.
- Add a regression test covering days+flow on an ineligible inbound.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 12:55:08 +02:00
Rouzbeh† c93beef267 fix(inbounds): accept null rewritePort in tunnel settings (#5516) (#5525)
Clearing the Rewrite port field makes AntD InputNumber write null into the
form store. The tunnel schema declared rewritePort as PortSchema.optional(),
which accepts undefined but not null, so saving (or the JSON tab reflecting
null) failed validation with "settings.rewritePort — Invalid input".

Accept null and collapse it to undefined so the field is simply omitted from
the serialized payload, matching the behavior of deleting the key by hand.
The trailing .optional() keeps the key optional in the inferred type.

Closes #5516
2026-06-24 12:54:05 +02:00
MHSanaei 48c2fb27b8 feat(sub): add Incy client integration and routing tab
Add an Incy quick-import button (incy://add) to the Android and iOS app menus on the subscription page, and a new Incy settings tab with routing enable + rules. Incy routing is delivered by injecting an incy://routing/onadd line into the raw subscription body, avoiding a collision with Happ's Routing header. Includes backend settings, regenerated OpenAPI/zod schemas, and translations for all locales.
2026-06-24 12:51:22 +02:00
366 changed files with 16988 additions and 4320 deletions
+13
View File
@@ -4,3 +4,16 @@ XUI_LOG_FOLDER=x-ui
XUI_BIN_FOLDER=x-ui
XUI_INIT_WEB_BASE_PATH=/
# XUI_PORT=8080
# Optional tunnel health monitor (disabled by default). It periodically probes a
# URL and restarts xray-core after repeated failures. Point XUI_TUNNEL_HEALTH_PROXY
# at a local xray inbound so the probe tests the tunnel; without it the probe only
# checks host connectivity and a restart will not fix host network issues. A restart
# drops every connected client.
# XUI_TUNNEL_HEALTH_MONITOR=true
# XUI_TUNNEL_HEALTH_PROXY=socks5://127.0.0.1:1080
# XUI_TUNNEL_HEALTH_URL=https://www.cloudflare.com/cdn-cgi/trace
# XUI_TUNNEL_HEALTH_INTERVAL=30s
# XUI_TUNNEL_HEALTH_TIMEOUT=10s
# XUI_TUNNEL_HEALTH_FAILURES=3
# XUI_TUNNEL_HEALTH_COOLDOWN=5m
+1 -4
View File
@@ -5,8 +5,5 @@ frontend/src/generated/** text eol=lf
frontend/public/openapi.json text eol=lf
frontend/src/test/__snapshots__/** text eol=lf
# Cloud-image deploy assets are consumed on Linux — force LF regardless of host.
*.service text eol=lf
deploy/**/*.service text eol=lf
deploy/**/*.hcl text eol=lf
# Cloud-init deploy assets are consumed on Linux — force LF regardless of host.
deploy/**/*.yaml text eol=lf
+15
View File
@@ -102,6 +102,21 @@ jobs:
go test -run '^$' -fuzz 'FuzzParseLink$' -fuzztime=30s ./internal/util/link/
go test -run '^$' -fuzz 'FuzzDecodeCertPin$' -fuzztime=30s ./internal/web/runtime/
golangci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v6
with:
go-version-file: go.mod
cache: true
- name: Stub internal/web/dist for go:embed
run: mkdir -p internal/web/dist && touch internal/web/dist/.gitkeep
- name: golangci-lint
uses: golangci/golangci-lint-action@v9
with:
version: latest
frontend:
runs-on: ubuntu-latest
steps:
-260
View File
@@ -1,260 +0,0 @@
name: Build Cloud Images
# Build golden cloud images from a published release, for amd64 and arm64:
# * qemu -> qcow2 attached to the GitHub release (always)
# * amazon-ebs -> AWS AMI (only when AWS credentials are configured)
#
# Images contain NO database and NO baked credentials; first boot generates
# unique per-instance credentials (see deploy/firstboot + deploy/packer).
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Release tag to build images for (e.g. v3.3.1)"
required: true
type: string
permissions:
contents: write
concurrency:
group: image-${{ github.event.release.tag_name || inputs.tag }}
cancel-in-progress: false
jobs:
# Resolve the tag and wait until BOTH arch tarballs are actually published
# (the release matrix uploads assets one by one, so 'published' can fire
# before the tarballs exist).
setup:
runs-on: ubuntu-latest
outputs:
tag: ${{ steps.resolve.outputs.tag }}
steps:
- name: Resolve tag
id: resolve
run: |
if [ "${{ github.event_name }}" = "release" ]; then
TAG="${{ github.event.release.tag_name }}"
else
TAG="${{ inputs.tag }}"
fi
[ -n "$TAG" ] || { echo "::error::no tag resolved"; exit 1; }
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
- name: Wait for released binary assets (amd64 + arm64)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ steps.resolve.outputs.tag }}
run: |
want="x-ui-linux-amd64.tar.gz x-ui-linux-arm64.tar.gz"
for i in $(seq 1 30); do
names=$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json assets -q '.assets[].name')
missing=""
for w in $want; do
echo "$names" | grep -qx "$w" || missing="$missing $w"
done
if [ -z "$missing" ]; then
echo "All assets present on $TAG"
exit 0
fi
echo "Waiting for$missing on $TAG ($i/30)..."
sleep 20
done
echo "::error::missing release assets on $TAG after 10 minutes:$missing"
exit 1
# Gate the AWS AMI build so forks without secrets skip it cleanly
# (secrets cannot be referenced directly in job-level `if`).
check-aws:
runs-on: ubuntu-latest
outputs:
enabled: ${{ steps.c.outputs.enabled }}
use_oidc: ${{ steps.c.outputs.use_oidc }}
steps:
- id: c
env:
ROLE: ${{ secrets.AWS_ROLE_ARN }}
KEY: ${{ secrets.AWS_ACCESS_KEY_ID }}
run: |
if [ -n "$ROLE" ]; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
echo "use_oidc=true" >> "$GITHUB_OUTPUT"
elif [ -n "$KEY" ]; then
echo "enabled=true" >> "$GITHUB_OUTPUT"
echo "use_oidc=false" >> "$GITHUB_OUTPUT"
else
echo "enabled=false" >> "$GITHUB_OUTPUT"
echo "use_oidc=false" >> "$GITHUB_OUTPUT"
echo "::notice::No AWS credentials configured; skipping the AMI build."
fi
qemu-image:
needs: setup
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
runner: ubuntu-latest
qemu_pkgs: qemu-system-x86 qemu-utils
- arch: arm64
runner: ubuntu-24.04-arm
qemu_pkgs: qemu-system-arm qemu-efi-aarch64 qemu-utils
runs-on: ${{ matrix.runner }}
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Install QEMU
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends ${{ matrix.qemu_pkgs }}
- name: Setup Packer
uses: hashicorp/setup-packer@v3
with:
version: latest
- name: Verify released binary asset
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ needs.setup.outputs.tag }}
run: |
mkdir -p _asset
gh release download "$TAG" --repo "$GITHUB_REPOSITORY" \
--pattern "x-ui-linux-${{ matrix.arch }}.tar.gz" --dir _asset
ls -la _asset
- name: Select accelerator
id: accel
run: |
if [ -e /dev/kvm ]; then echo "value=kvm" >> "$GITHUB_OUTPUT"; else echo "value=tcg" >> "$GITHUB_OUTPUT"; fi
- name: Packer init
run: packer init deploy/packer/
- name: Build qcow2 image
env:
TAG: ${{ needs.setup.outputs.tag }}
ACCEL: ${{ steps.accel.outputs.value }}
run: |
packer build -only='qemu.x-ui' \
-var "xui_version=${TAG}" \
-var "xui_arch=${{ matrix.arch }}" \
-var "qemu_accelerator=${ACCEL}" \
deploy/packer/
- name: Compress qcow2
id: pack
env:
TAG: ${{ needs.setup.outputs.tag }}
run: |
cd deploy/packer/output-qemu
src="3x-ui-ubuntu-24.04-${{ matrix.arch }}.qcow2"
out="3x-ui-ubuntu-24.04-${TAG}-${{ matrix.arch }}.qcow2.xz"
xz -T0 -6 -c "$src" > "$out"
sha256sum "$out" > "${out}.sha256"
echo "file=deploy/packer/output-qemu/${out}" >> "$GITHUB_OUTPUT"
echo "sha=deploy/packer/output-qemu/${out}.sha256" >> "$GITHUB_OUTPUT"
ls -la
- name: Attach qcow2 to release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ needs.setup.outputs.tag }}
run: |
gh release upload "$TAG" --repo "$GITHUB_REPOSITORY" --clobber \
"${{ steps.pack.outputs.file }}" "${{ steps.pack.outputs.sha }}"
- name: Summary
env:
TAG: ${{ needs.setup.outputs.tag }}
ACCEL: ${{ steps.accel.outputs.value }}
run: |
{
echo "## QEMU image (${{ matrix.arch }})"
echo "- Tag: \`${TAG}\`"
echo "- Accelerator: \`${ACCEL}\`"
echo "- Attached: \`$(basename "${{ steps.pack.outputs.file }}")\`"
} >> "$GITHUB_STEP_SUMMARY"
ami-image:
needs: [setup, check-aws]
if: needs.check-aws.outputs.enabled == 'true'
runs-on: ubuntu-latest
timeout-minutes: 60
permissions:
contents: read
id-token: write
strategy:
fail-fast: false
matrix:
include:
- arch: amd64
instance_type: t3.small
- arch: arm64
instance_type: t4g.small
steps:
- name: Checkout
uses: actions/checkout@v7
- name: Setup Packer
uses: hashicorp/setup-packer@v3
with:
version: latest
- name: Configure AWS credentials (OIDC)
if: needs.check-aws.outputs.use_oidc == 'true'
uses: aws-actions/configure-aws-credentials@v6
with:
role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
aws-region: ${{ vars.AWS_REGION || 'eu-central-1' }}
- name: Configure AWS credentials (access keys)
if: needs.check-aws.outputs.use_oidc != 'true'
uses: aws-actions/configure-aws-credentials@v6
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION || 'eu-central-1' }}
- name: Verify released binary asset
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ needs.setup.outputs.tag }}
run: |
mkdir -p _asset
gh release download "$TAG" --repo "$GITHUB_REPOSITORY" \
--pattern "x-ui-linux-${{ matrix.arch }}.tar.gz" --dir _asset
ls -la _asset
- name: Packer init
run: packer init deploy/packer/
- name: Build AMI
env:
TAG: ${{ needs.setup.outputs.tag }}
REGION: ${{ vars.AWS_REGION || 'eu-central-1' }}
run: |
packer build -only='amazon-ebs.x-ui' \
-var "xui_version=${TAG}" \
-var "xui_arch=${{ matrix.arch }}" \
-var "instance_type=${{ matrix.instance_type }}" \
-var "region=${REGION}" \
deploy/packer/
- name: Publish AMI id to summary
env:
REGION: ${{ vars.AWS_REGION || 'eu-central-1' }}
run: |
AMI_ID=$(jq -r '.builds[] | select(.builder_type=="amazon-ebs") | .artifact_id' packer-manifest.json | tail -1 | cut -d: -f2)
{
echo "## AWS AMI (${{ matrix.arch }})"
echo "- Region: \`${REGION}\`"
echo "- Instance type: \`${{ matrix.instance_type }}\`"
echo "- AMI ID: \`${AMI_ID}\`"
} >> "$GITHUB_STEP_SUMMARY"
+73 -4
View File
@@ -97,7 +97,13 @@ jobs:
export CC=$(realpath "$(find "$TOOLCHAIN_DIR/bin" -name '*-gcc.br_real' -type f -executable | head -n1)")
[ -z "$CC" ] && { echo "No gcc.br_real found in $TOOLCHAIN_DIR/bin" >&2; exit 1; }
cd -
go build -ldflags "-w -s -linkmode external -extldflags '-static'" -o xui-release -v main.go
# Stamp the commit into per-commit (dev channel) builds only; tagged
# stable releases stay unstamped so config.IsDevBuild() returns false.
LDFLAGS="-w -s -linkmode external -extldflags '-static'"
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA::8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
go build -ldflags "$LDFLAGS" -o xui-release -v main.go
file xui-release
ldd xui-release || echo "Static binary confirmed"
@@ -112,7 +118,7 @@ jobs:
cd x-ui/bin
# Download dependencies
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.6.22/"
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.6.27/"
if [ "${{ matrix.platform }}" == "amd64" ]; then
wget -q ${Xray_URL}Xray-linux-64.zip
unzip Xray-linux-64.zip
@@ -245,7 +251,12 @@ jobs:
go version
gcc --version
go build -ldflags "-w -s" -o xui-release.exe -v main.go
# Stamp the commit into per-commit (dev channel) builds only.
LDFLAGS="-w -s"
if [[ "$GITHUB_REF" != refs/tags/* ]]; then
LDFLAGS="$LDFLAGS -X github.com/mhsanaei/3x-ui/v3/internal/config.buildCommit=${GITHUB_SHA:0:8} -X github.com/mhsanaei/3x-ui/v3/internal/config.buildDate=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
fi
go build -ldflags "$LDFLAGS" -o xui-release.exe -v main.go
- name: Copy and download resources
shell: pwsh
@@ -256,7 +267,7 @@ jobs:
cd x-ui\bin
# Download Xray for Windows
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.6.22/"
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.6.27/"
Invoke-WebRequest -Uri "${Xray_URL}Xray-windows-64.zip" -OutFile "Xray-windows-64.zip"
Expand-Archive -Path "Xray-windows-64.zip" -DestinationPath .
Remove-Item "Xray-windows-64.zip"
@@ -302,3 +313,61 @@ jobs:
asset_name: x-ui-windows-amd64.zip
overwrite: true
prerelease: true
# =================================
# Rolling dev channel (per-commit)
# =================================
# Publishes/overwrites the build artifacts to a single fixed-tag pre-release
# `dev-latest`, force-moved to the new commit on every push to main. The panel's
# "Dev" update channel installs from this tag. `--latest=false` is load-bearing:
# it keeps releases/latest pointing at the real stable tag, so the stable
# channel is unaffected.
publish-dev:
name: Publish rolling dev release
needs: [build, build-windows]
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
contents: write
# Serialize racing pushes; never cancel an in-flight upload, or the dev
# release could be left with a partial asset set.
concurrency:
group: dev-release
cancel-in-progress: false
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Download all build artifacts
uses: actions/download-artifact@v8
with:
path: dev-artifacts
merge-multiple: true
- name: Publish dev-latest pre-release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
COMMIT: ${{ github.sha }}
run: |
set -e
short="${COMMIT::8}"
notes="Rolling development build — installs via the panel's Dev update channel.
commit=${COMMIT}
built=$(date -u +%Y-%m-%dT%H:%M:%SZ)
Automated per-commit build from main. Not a stable release."
# Force-move the dev-latest tag to this commit so the release tracks it.
git tag -f dev-latest "${COMMIT}"
git push -f origin refs/tags/dev-latest
if gh release view dev-latest >/dev/null 2>&1; then
gh release edit dev-latest --prerelease --latest=false \
--title "Dev build ${short}" --notes "${notes}"
else
gh release create dev-latest --prerelease --latest=false \
--target "${COMMIT}" --title "Dev build ${short}" --notes "${notes}"
fi
gh release upload dev-latest dev-artifacts/*.tar.gz dev-artifacts/*.zip --clobber
+2 -14
View File
@@ -1,7 +1,7 @@
name: Deploy Smoke Tests
# Container smoke tests for the unattended install path and first-boot
# credential generation. Runs only when the install/deploy assets change.
# Container smoke test for the unattended (cloud-init) install path.
# Runs only when the install/deploy assets change.
on:
push:
@@ -30,15 +30,3 @@ jobs:
- uses: actions/checkout@v7
- name: Non-interactive install smoke test
run: bash deploy/test/smoke-noninteractive.sh
first-boot:
strategy:
fail-fast: false
matrix:
runner: [ubuntu-latest, ubuntu-24.04-arm]
runs-on: ${{ matrix.runner }}
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- name: First-boot credential smoke test
run: bash deploy/test/smoke-firstboot.sh
+53
View File
@@ -0,0 +1,53 @@
version: "2"
run:
build-tags: []
timeout: 5m
linters:
default: standard
enable:
- bodyclose
- errorlint
- noctx
- misspell
- rowserrcheck
- sqlclosecheck
- unconvert
- usestdlibvars
exclusions:
generated: lax
presets:
- std-error-handling
paths:
- frontend
- internal/web/dist
rules:
- path: _test\.go
linters:
- errcheck
- bodyclose
- noctx
# tools/openapigen relies on go/parser.ParseDir; migrating it to
# golang.org/x/tools/go/packages is a generator change, out of scope here.
- linters:
- staticcheck
text: "SA1019: parser.ParseDir"
# ST1005 (capitalized error strings) conflicts with intentional
# user-facing error copy that tests assert verbatim.
- linters:
- staticcheck
text: "ST1005:"
formatters:
enable:
- gofumpt
- goimports
settings:
goimports:
local-prefixes:
- github.com/mhsanaei/3x-ui
exclusions:
paths:
- frontend
- internal/web/dist
+101
View File
@@ -0,0 +1,101 @@
# CLAUDE.md
Operational guide for AI agents working in this repo. Long-form human docs:
`CONTRIBUTING.md` (setup, testing philosophy) and `frontend/README.md`.
Read those before large changes. This file is the short, must-follow version.
## Stack
- Backend: Go 1.26 (`module github.com/mhsanaei/3x-ui/v3`), Gin, GORM.
Runs Xray-core as a managed child process (`internal/xray/process.go`) and
imports `github.com/xtls/xray-core` for config types + gRPC stats/handler/router
API. MTProto inbounds run a second managed child — the `mtg` binary
(`internal/mtproto/`) — outside Xray.
- Storage: SQLite by default (`/etc/x-ui/x-ui.db` on Linux; the executable dir on
Windows), PostgreSQL optional (`XUI_DB_TYPE` / `XUI_DB_DSN`). The CGo SQLite
driver (`mattn/go-sqlite3`) needs a C compiler — `CGO_ENABLED=0` builds fail.
- Frontend: React 19 + Ant Design 6 + Vite 8 + TypeScript in `frontend/`,
built into `internal/web/dist/` (gitignored) and embedded via `embed.FS`.
## Repo map
- `main.go` — entry point + `x-ui` CLI (run, migrate, migrate-db, setting, cert).
- `internal/config/` — env parsing (XUI_DEBUG, XUI_LOG_LEVEL, XUI_LOG_FOLDER,
XUI_BIN_FOLDER, XUI_SKIP_HSTS, XUI_PORT, XUI_DB_*).
- `internal/database/` + `internal/database/model/` — GORM schema (Inbound,
Client, Setting, User), inbound Protocol enum, AutoMigrate + hand-written
migrations in `db.go`.
- `internal/xray/` — Xray child-process lifecycle, config generation, gRPC API.
- `internal/mtproto/` — MTProto inbounds via the bundled `mtg` binary.
- `internal/sub/` — subscription server (raw / JSON / Clash).
- `internal/eventbus/` — in-process pub/sub (outbound/node health, xray.crash,
cpu.high, memory.high, login.attempt).
- `internal/logger/`, `internal/util/` (link, crypto, sys, ldap, …),
`internal/tunnelmonitor/` — shared infrastructure.
- `internal/web/` — Gin server (embeds `dist/` + `translation/`).
- `controller/` — panel + REST API handlers; OpenAPI at /panel/api/openapi.json.
- `service/` — business logic (InboundService, SettingService, XrayService,
node sync); subpackages tgbot/, email/, outbound/, panel/, integration/.
- `job/` — cron jobs (traffic, fail2ban IP-limit, node heartbeat/sync, LDAP).
- `middleware/`, `entity/`, `global/`, `session/` (CSRF), `network/`,
`runtime/` (master/sub-node over mTLS), `websocket/`.
- `locale/` + `translation/` — i18n, 13 embedded locale JSON files.
- `frontend/` — React + TS source (see `frontend/CLAUDE.md`).
- `tools/openapigen/` — Go generator that emits frontend types + Zod/JSON schemas
into `frontend/src/generated/` from Go structs. The OpenAPI doc itself
(`frontend/public/openapi.json`) is assembled from those + `endpoints.ts` by
`frontend/scripts/build-openapi.mjs`.
## Hard rules (non-negotiable)
- NO `//` line comments in committed Go/TS. Names carry meaning; rename instead
of annotating. Exempt: `//go:build`, `//go:generate`, and other directives.
HTML `<!-- -->` is fine. (A linter cannot enforce this — you must.)
- New `g.POST`/`g.GET` in `internal/web/controller/` REQUIRES a matching entry
in `frontend/src/pages/api-docs/endpoints.ts`, then `make gen` (or
`cd frontend && npm run gen`). It is a hand-maintained registry — nothing checks
it against the Go routes, so an omitted route silently vanishes from the docs.
- Response examples come from Go struct `example:` tags via `tools/openapigen`
never hand-write them. A new struct must be added to openapigen's `StructAllow`
allowlist (`tools/openapigen/main.go`) or it is silently omitted from
schemas/examples (and `build-openapi.mjs` then fails on the missing schema).
- A new English i18n key must be added to EVERY locale JSON in
`internal/web/translation/` (13 files). Missing keys fall back to en-US (or
render the raw key if absent there too); nothing fails the build, so they are
easy to miss.
- DB / model changes require a migration in `internal/database/db.go`.
- Conventional-commit prefixes (`feat`, `fix`, `refactor`, `chore`, `docs`,
`style`): `<area>: short imperative summary`, then a body explaining the why.
## Go conventions
- Stdlib `testing` only (no testify). Table-driven, `t.Run` subtests,
`t.Helper()` on helpers. Assert the exact value / typed error / emitted
string, never just `err != nil`. Prefer real deps over mocks: throwaway DB via
`database.InitDB(filepath.Join(t.TempDir(), "x-ui.db"))` +
`t.Cleanup(func() { _ = database.CloseDB() })`; `httptest` for HTTP.
`internal/sub`'s `initSubDB(t)` is the template.
- Code must pass `golangci-lint run` (gofumpt + goimports formatting): `make lint`.
## Frontend conventions (summary; full version in frontend/CLAUDE.md)
- Ant Design 6 only — no Tailwind/shadcn. Targeted tweaks, not rewrites.
- TS strict; `@typescript-eslint/no-explicit-any` is an error. Zod schemas in
`src/schemas/` are the source of truth; infer types with `z.infer`, never
hand-write. Do not edit `src/generated/`.
- Editing `frontend/src` does NOT change what users see until the Vite build is
regenerated into `internal/web/dist/`. In `XUI_DEBUG=true`, HTML is served from
the frozen embedded FS but JS/CSS off disk — after `npm run build` you MUST
restart `go run .` or you get a blank page with 404s.
- After touching share-link logic (`src/lib/xray/`), run `npm run test` (golden
fixtures); regenerate snapshots (`npx vitest run -u`) only for intentional
output changes, never to make a red test green.
## Build, test, verify
Run `make help` for all targets. The full local gate that mirrors CI:
make verify
Common targets: `make gen` (regenerate Zod/OpenAPI), `make lint` (Go + frontend),
`make test` (Go `-shuffle=on` + frontend), `make race`, `make build`. See `Makefile`.
## Definition of done (before opening a PR)
1. `make gen` and confirm `git diff` on `frontend/src/generated` +
`frontend/public/openapi.json` is clean.
2. `make verify` passes.
3. Diff is focused; refactors are separate from feature work.
+2 -2
View File
@@ -184,11 +184,11 @@ Only a genuinely **standalone bundle** (like `login` or `subpage`, reachable wit
- **Ant Design 6** is the only UI kit — no Tailwind, no shadcn. A previous attempt to migrate was rolled back. Small, targeted UX tweaks beat sweeping rewrites; raise broader visual changes for discussion before implementing.
- **Function components + hooks** everywhere. No class components.
- **No `//` line comments** in committed JS/TS/Vue/Go. HTML `<!-- ... -->` is fine for template structure. Names should carry the meaning; rename rather than annotate. Comments are reserved for the *why*, and only when the reason is surprising.
- **RTL is a first-class concern.** Persian and Arabic users matter — RTL is enabled through AntD's `ConfigProvider direction="rtl"`. When writing Persian text in toasts or labels, isolate code identifiers on their own lines so RTL reading flows.
- **Persian and Arabic users are first-class.** When writing Persian text in toasts or labels, isolate code identifiers on their own lines so RTL reading flows. (Full RTL layout is not currently wired through AntD `ConfigProvider direction` — only the Jalali date picker is RTL-aware — so treat RTL as an open area, not a solved one.)
- **Schemas over `any`.** New config shapes go in `src/schemas/`; `@typescript-eslint/no-explicit-any` is an error and production schemas use no `.loose()`. Validate form fields with `antdRule(Schema.shape.field, t)` rather than inline `z.string()` in rules.
- **Document new endpoints.** Every new `g.POST`/`g.GET` in `internal/web/controller/` needs a matching entry in `src/pages/api-docs/endpoints.ts` — it drives both the in-panel API docs and the generated OpenAPI/Zod (`npm run gen:api` / `gen:zod`).
- **Do not break link generation.** Share-link logic lives in `src/lib/xray/` (`inbound-link.ts`, `outbound-link-parser.ts`, …) and is round-tripped by the golden fixture suite — run `npm run test` after any change to URL generation, defaults, or TLS/Reality handling, and regenerate snapshots (`npx vitest run -u`) only for intentional changes. Two runtime paths consume it: the **inbounds page** and the **clients page** subscription links (`/panel/api/clients/subLinks/:subId` → backend `GetSubs`); exercise both.
- **Vite is pinned to an exact version** (no `^`) in `frontend/package.json` — currently `8.0.16` — so local, CI, and release builds resolve identically. Bump it deliberately and verify both `npm run dev` and `npm run build` afterward.
- **Vite is pinned to an exact version** (no `^`) in `frontend/package.json` — read the live version there rather than trusting a number quoted here — so local, CI, and release builds resolve identically. Bump it deliberately and verify both `npm run dev` and `npm run build` afterward.
### Project layout
+1 -1
View File
@@ -34,7 +34,7 @@ esac
MTG_VER="2.2.8"
mkdir -p build/bin
cd build/bin
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.6.22/Xray-linux-${ARCH}.zip"
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.6.27/Xray-linux-${ARCH}.zip"
unzip "Xray-linux-${ARCH}.zip"
rm -f "Xray-linux-${ARCH}.zip" geoip.dat geosite.dat
mv xray "xray-linux-${FNAME}"
+75
View File
@@ -0,0 +1,75 @@
# Canonical task runner. Mirrors .github/workflows/ci.yml so `make verify`
# reproduces the PR gate locally. Run `make help` for the list.
SHELL := bash
GO_PKGS = $(shell go list ./... | grep -v '/frontend/node_modules/')
FRONTEND = frontend
.DEFAULT_GOAL := help
.PHONY: help
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}'
# go:embed of internal/web/dist needs the dir to exist even when the
# frontend bundle has not been built. CI stubs it the same way.
.PHONY: dist-stub
dist-stub:
@mkdir -p internal/web/dist && touch internal/web/dist/.gitkeep
.PHONY: gen
gen: ## Regenerate Zod schemas + OpenAPI from Go sources
cd $(FRONTEND) && npm run gen
.PHONY: gen-check
gen-check: gen ## Fail if generated files are stale
git diff --exit-code -- frontend/src/generated frontend/public/openapi.json
.PHONY: lint-go
lint-go: dist-stub ## golangci-lint on Go sources
golangci-lint run
.PHONY: lint-fe
lint-fe: ## ESLint on frontend sources
cd $(FRONTEND) && npm run lint
.PHONY: lint
lint: lint-go lint-fe ## All linters
.PHONY: typecheck
typecheck: ## tsc --noEmit
cd $(FRONTEND) && npm run typecheck
.PHONY: test-go
test-go: dist-stub ## Go tests (shuffle, no cache)
go test -shuffle=on -count=1 $(GO_PKGS)
.PHONY: race
race: dist-stub ## Go tests with the race detector (needs a C compiler)
go test -race -shuffle=on -count=1 $(GO_PKGS)
.PHONY: test-fe
test-fe: ## Frontend tests (vitest)
cd $(FRONTEND) && npm test
.PHONY: test
test: test-go test-fe ## All tests
.PHONY: vulncheck
vulncheck: dist-stub ## govulncheck
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
.PHONY: build-fe
build-fe: ## Build the Vite bundles into internal/web/dist
cd $(FRONTEND) && npm run build
.PHONY: build
build: build-fe ## Build the frontend then the Go binary
go build ./...
# The PR gate. Matches ci.yml: codegen freshness, both linters, typecheck,
# both test suites, and a full build.
.PHONY: verify
verify: gen-check lint typecheck test build ## Full local gate (mirrors CI)
@echo "verify: OK"
+30 -1
View File
@@ -33,7 +33,7 @@
- **إحصائيات الترافيك** — لكل اتصال وارد، ولكل عميل، ولكل اتصال صادر، مع عناصر تحكم لإعادة التعيين.
- **دعم العقد المتعددة** — إدارة وتوسيع عبر عدة خوادم من لوحة واحدة.
- **الاتصالات الصادرة والتوجيه** — WARP، NordVPN، قواعد توجيه مخصصة، موازنات تحميل، وتسلسل الوكلاء الصادرة.
- **خادم اشتراك مدمج** بصيغ إخراج متعددة.
- **خادم اشتراك مدمج** بصيغ إخراج متعددة و[قوالب صفحات مخصصة](docs/custom-subscription-templates.md).
- **روبوت تيليجرام** للمراقبة والإدارة عن بُعد.
- **واجهة RESTful API** مع توثيق Swagger داخل اللوحة.
- **تخزين مرن** — SQLite (افتراضي) أو PostgreSQL.
@@ -73,10 +73,32 @@
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
لتثبيت إصدار محدد، أضِف وسمه (مثل `v3.4.0`):
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
لتثبيت بنية **dev** المتجددة (أحدث إصدار أولي لكل التزام (commit) من `main`، وليس إصدارًا مستقرًا)، مرّر `dev-latest`:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
أثناء التثبيت، يتم إنشاء اسم مستخدم وكلمة مرور ومسار وصول عشوائية. بعد التثبيت، شغّل `x-ui` لفتح قائمة الإدارة، حيث يمكنك بدء/إيقاف الخدمة، وعرض أو إعادة تعيين بيانات تسجيل الدخول، وإدارة شهادات SSL، والمزيد.
للحصول على الوثائق الكاملة، يرجى زيارة [ويكي المشروع](https://github.com/MHSanaei/3x-ui/wiki).
### التثبيت غير التفاعلي
يعمل المثبِّت أيضًا **بشكل غير تفاعلي** لـ cloud-init.
عيّن `XUI_NONINTERACTIVE=1` (أو مرّره عبر أنبوب دون TTY) وسيتولى التثبيت من البداية إلى النهاية
دون أي مطالبات، مُنشئًا بيانات اعتماد عشوائية وكاتبًا إياها في
`/etc/x-ui/install-result.env`. راجع [`deploy/`](deploy/) لـ:
- [بيانات مستخدم cloud-init](deploy/cloud-init/) — تثبيت غير تفاعلي على أي سحابة (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
- [ملاحظات Hetzner Cloud](deploy/marketplace/hetzner/) — نشر يعتمد على cloud-init على Hetzner
## المنصات المدعومة
**أنظمة التشغيل:** Ubuntu، Debian، Armbian، Fedora، CentOS، RHEL، AlmaLinux، Rocky Linux، Oracle Linux، Amazon Linux، Virtuozzo، Arch، Manjaro، Parch، openSUSE (Tumbleweed / Leap)، Alpine و Windows.
@@ -134,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | تفعيل فرض حدود IP المعتمد على Fail2ban | `true` |
| `XUI_LOG_LEVEL` | مستوى السجل (`debug`، `info`، `warning`، `error`) | `info` |
| `XUI_DEBUG` | تفعيل وضع التصحيح | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | تفعيل مراقب صحة النفق (يفحص عنوان URL ويعيد تشغيل xray بعد فشل متكرر؛ إعادة التشغيل تقطع جميع العملاء) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | الوكيل الذي يُرسَل عبره الفحص؛ وجّهه إلى اتصال xray وارد محلي ليختبر الفحص النفق (مثل `socks5://127.0.0.1:1080`). القيمة الفارغة تعني أن الفحص يتحقق فقط من اتصال المضيف | — |
| `XUI_TUNNEL_HEALTH_URL` | عنوان URL الذي يُفحَص لمعرفة صحة النفق | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | الفترة بين عمليات الفحص | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | مهلة كل عملية فحص | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | عدد حالات الفشل المتتالية قبل تشغيل إعادة التشغيل | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | الحد الأدنى للتأخير بين عمليات إعادة التشغيل المتتالية | `5m` |
## اللغات المدعومة
+30 -1
View File
@@ -33,7 +33,7 @@ Construido como un fork mejorado del proyecto X-UI original, 3X-UI añade un sop
- **Estadísticas de tráfico** — por entrada, por cliente y por salida, con controles de reinicio.
- **Soporte multinodo** — gestiona y escala a través de varios servidores desde un único panel.
- **Salida y enrutamiento** — WARP, NordVPN, reglas de enrutamiento personalizadas, balanceadores de carga y encadenamiento de proxy de salida.
- **Servidor de suscripción integrado** con múltiples formatos de salida.
- **Servidor de suscripción integrado** con múltiples formatos de salida y [plantillas de página personalizables](docs/custom-subscription-templates.md).
- **Bot de Telegram** para monitorización y gestión remotas.
- **API RESTful** con documentación Swagger dentro del panel.
- **Almacenamiento flexible** — SQLite (predeterminado) o PostgreSQL.
@@ -73,10 +73,32 @@ Construido como un fork mejorado del proyecto X-UI original, 3X-UI añade un sop
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
Para instalar una versión específica, añade su etiqueta (p. ej. `v3.4.0`):
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
Para instalar la versión **dev** continua (la última prelanzamiento por commit desde `main`, no una versión estable), pasa `dev-latest`:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
Durante la instalación se generan un nombre de usuario, una contraseña y una ruta de acceso aleatorios. Tras la instalación, ejecuta `x-ui` para abrir el menú de gestión, donde puedes iniciar/detener el servicio, ver o restablecer tus credenciales de acceso, gestionar certificados SSL y mucho más.
Para la documentación completa, visita la [Wiki del proyecto](https://github.com/MHSanaei/3x-ui/wiki).
### Instalación desatendida
El instalador también se ejecuta de forma **no interactiva** para cloud-init.
Define `XUI_NONINTERACTIVE=1` (o canalízalo sin TTY) y realizará la instalación de principio a fin sin
ninguna pregunta, generando credenciales aleatorias y escribiéndolas en
`/etc/x-ui/install-result.env`. Consulta [`deploy/`](deploy/) para:
- [User-data de cloud-init](deploy/cloud-init/) — instalación desatendida en cualquier nube (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
- [Notas de Hetzner Cloud](deploy/marketplace/hetzner/) — despliegue basado en cloud-init en Hetzner
## Plataformas Compatibles
**Sistemas operativos:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine y Windows.
@@ -134,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | Habilitar la aplicación de límites de IP basada en Fail2ban | `true` |
| `XUI_LOG_LEVEL` | Nivel de registro (`debug`, `info`, `warning`, `error`) | `info` |
| `XUI_DEBUG` | Habilitar el modo de depuración | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | Habilitar el monitor de salud del túnel (sondea una URL y reinicia xray tras fallos repetidos; un reinicio desconecta a todos los clientes) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | Proxy a través del cual se envía el sondeo; apúntalo a una entrada local de xray para que el sondeo pruebe el túnel (p. ej. `socks5://127.0.0.1:1080`). Vacío significa que el sondeo solo comprueba la conectividad del host | — |
| `XUI_TUNNEL_HEALTH_URL` | URL sondeada para verificar la salud del túnel | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | Intervalo entre sondeos | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Tiempo de espera por sondeo | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | Fallos consecutivos antes de que se active un reinicio | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Retardo mínimo entre reinicios consecutivos | `5m` |
## Idiomas Compatibles
+30 -1
View File
@@ -33,7 +33,7 @@
- **آمار ترافیک** — به‌ازای هر اینباند، هر کلاینت و هر اوتباند، همراه با کنترل بازنشانی (reset).
- **پشتیبانی از چند نود** — مدیریت و مقیاس‌دهی روی چندین سرور از یک پنل واحد.
- **اوتباند و مسیریابی** — WARP، NordVPN، قوانین مسیریابی سفارشی، متعادل‌کننده‌های بار (load balancer) و زنجیره‌کردن پراکسی اوتباند.
- **سرور سابسکریپشن داخلی** با چندین فرمت خروجی.
- **سرور سابسکریپشن داخلی** با چندین فرمت خروجی و [قالب‌های صفحه‌ی سفارشی](docs/custom-subscription-templates.md).
- **ربات تلگرام** برای نظارت و مدیریت از راه دور.
- **RESTful API** همراه با مستندات Swagger درون‌پنل.
- **ذخیره‌سازی منعطف** — SQLite (پیش‌فرض) یا PostgreSQL.
@@ -73,10 +73,32 @@
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
برای نصب یک نسخه‌ی مشخص، تگ آن را در انتها اضافه کنید (مثلاً `v3.4.0`):
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
برای نصب نسخه‌ی غلتانِ **dev** (آخرین پیش‌انتشار به‌ازای هر کامیت از شاخه‌ی `main`، نه یک انتشار پایدار)، مقدار `dev-latest` را پاس دهید:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
در حین نصب، یک نام کاربری، رمز عبور و مسیر دسترسی تصادفی تولید می‌شود. پس از نصب، دستور `x-ui` را اجرا کنید تا منوی مدیریت باز شود؛ در آنجا می‌توانید سرویس را شروع/متوقف کنید، اطلاعات ورود خود را ببینید یا بازنشانی کنید، گواهی‌های SSL را مدیریت کنید و کارهای دیگری انجام دهید.
برای مستندات کامل، لطفاً به [ویکی پروژه](https://github.com/MHSanaei/3x-ui/wiki) مراجعه کنید.
### نصب بدون نظارت
نصب‌کننده به‌صورت **غیرتعاملی** نیز برای cloud-init اجرا می‌شود.
`XUI_NONINTERACTIVE=1` را تنظیم کنید (یا بدون TTY از طریق pipe اجرا کنید) تا نصب به‌صورت سرتاسری و بدون
هیچ پرسشی انجام شود، اطلاعات ورود تصادفی تولید کرده و آن‌ها را در
`/etc/x-ui/install-result.env` می‌نویسد. برای موارد زیر به [`deploy/`](deploy/) مراجعه کنید:
- [user-data مربوط به Cloud-init](deploy/cloud-init/) — نصب بدون نظارت روی هر ابری (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
- [یادداشت‌های Hetzner Cloud](deploy/marketplace/hetzner/) — استقرار مبتنی بر cloud-init روی Hetzner
## پلتفرم‌های پشتیبانی‌شده
**سیستم‌عامل‌ها:** Ubuntu، Debian، Armbian، Fedora، CentOS، RHEL، AlmaLinux، Rocky Linux، Oracle Linux، Amazon Linux، Virtuozzo، Arch، Manjaro، Parch، openSUSE (Tumbleweed / Leap)، Alpine و Windows.
@@ -134,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | فعال‌سازی اعمال محدودیت IP مبتنی بر Fail2ban | `true` |
| `XUI_LOG_LEVEL` | سطح گزارش‌گیری (`debug`، `info`، `warning`، `error`) | `info` |
| `XUI_DEBUG` | فعال‌سازی حالت دیباگ | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | فعال‌سازی پایشگر سلامت تونل (یک URL را پروب می‌کند و پس از خطاهای مکرر، xray را ری‌استارت می‌کند؛ یک ری‌استارت همه‌ی کلاینت‌ها را قطع می‌کند) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | پراکسی‌ای که پروب از طریق آن ارسال می‌شود؛ آن را به یک اینباند محلی xray اشاره دهید تا پروب خودِ تونل را آزمایش کند (مثلاً `socks5://127.0.0.1:1080`). خالی بودن یعنی پروب فقط اتصال به هاست را بررسی می‌کند | — |
| `XUI_TUNNEL_HEALTH_URL` | URL ای که برای سلامت تونل پروب می‌شود | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | فاصله‌ی زمانی بین پروب‌ها | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | مهلت زمانی هر پروب | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | تعداد خطاهای متوالی پیش از آن‌که یک ری‌استارت فعال شود | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | حداقل تأخیر بین ری‌استارت‌های متوالی | `5m` |
## زبان‌های پشتیبانی‌شده
+22 -5
View File
@@ -73,21 +73,31 @@ Built as an enhanced fork of the original X-UI project, 3X-UI adds broader proto
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
To install a specific version, append its tag (e.g. `v3.4.0`):
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
To install the rolling **dev** build (latest per-commit pre-release from `main`, not a stable release), pass `dev-latest`:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
During installation a random username, password, and access path are generated. After installation, run `x-ui` to open the management menu, where you can start/stop the service, view or reset your login credentials, manage SSL certificates, and more.
For full documentation, please visit the [project Wiki](https://github.com/MHSanaei/3x-ui/wiki).
### Unattended install & cloud images
### Unattended install
The installer also runs **non-interactively** for cloud-init and golden images.
The installer also runs **non-interactively** for cloud-init.
Set `XUI_NONINTERACTIVE=1` (or pipe with no TTY) and it installs end-to-end with
zero prompts, generating random credentials and writing them to
`/etc/x-ui/install-result.env`. See [`deploy/`](deploy/) for:
- [Cloud-init user-data](deploy/cloud-init/) — unattended install on any cloud (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
- [Packer golden image](deploy/packer/) — build an AWS EC2 AMI + qcow2 (amd64/arm64) with per-instance credentials generated on first boot
- [Amazon Lightsail](deploy/lightsail/) — launch script + reusable snapshot builder
- [AWS Marketplace checklist](deploy/marketplace/aws/)
- [Hetzner Cloud notes](deploy/marketplace/hetzner/) — cloud-init deployment on Hetzner
## Supported Platforms
@@ -146,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | Enable Fail2ban-based IP-limit enforcement | `true` |
| `XUI_LOG_LEVEL` | Log verbosity (`debug`, `info`, `warning`, `error`) | `info` |
| `XUI_DEBUG` | Enable debug mode | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | Enable the tunnel health monitor (probes a URL and restarts xray after repeated failures; a restart drops all clients) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | Proxy the probe is sent through; point it at a local xray inbound so the probe tests the tunnel (e.g. `socks5://127.0.0.1:1080`). Empty means the probe only checks host connectivity | — |
| `XUI_TUNNEL_HEALTH_URL` | URL probed for tunnel health | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | Interval between probes | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Per-probe timeout | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | Consecutive failures before a restart is triggered | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Minimum delay between consecutive restarts | `5m` |
## Supported Languages
+30 -1
View File
@@ -33,7 +33,7 @@
- **Статистика трафика** — по каждому входящему, по каждому клиенту и по каждому исходящему, с возможностью сброса.
- **Поддержка нескольких узлов** — управление и масштабирование на несколько серверов из одной панели.
- **Исходящие подключения и маршрутизация** — WARP, NordVPN, пользовательские правила маршрутизации, балансировщики нагрузки и цепочки исходящих прокси.
- **Встроенный сервер подписок** с несколькими форматами вывода.
- **Встроенный сервер подписок** с несколькими форматами вывода и [пользовательскими шаблонами страниц](docs/custom-subscription-templates.md).
- **Telegram-бот** для удалённого мониторинга и управления.
- **RESTful API** с документацией Swagger внутри панели.
- **Гибкое хранилище** — SQLite (по умолчанию) или PostgreSQL.
@@ -73,10 +73,32 @@
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
Чтобы установить конкретную версию, добавьте её тег (например, `v3.4.0`):
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
Чтобы установить скользящую **dev**-сборку (новейший предварительный релиз по каждому коммиту из ветки `main`, а не стабильный релиз), передайте `dev-latest`:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
Во время установки генерируются случайные имя пользователя, пароль и путь доступа. После установки выполните `x-ui`, чтобы открыть меню управления, где можно запускать/останавливать сервис, просматривать или сбрасывать учётные данные для входа, управлять SSL-сертификатами и многое другое.
Полную документацию смотрите в [вики проекта](https://github.com/MHSanaei/3x-ui/wiki).
### Автоматическая установка
Установщик также работает в **неинтерактивном** режиме для cloud-init.
Задайте `XUI_NONINTERACTIVE=1` (или передайте по конвейеру без TTY), и установка пройдёт от начала до конца
без единого запроса: будут сгенерированы случайные учётные данные и записаны в
`/etc/x-ui/install-result.env`. Смотрите [`deploy/`](deploy/) для:
- [Cloud-init user-data](deploy/cloud-init/) — автоматическая установка в любом облаке (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
- [Заметки по Hetzner Cloud](deploy/marketplace/hetzner/) — развёртывание на Hetzner на базе cloud-init
## Поддерживаемые платформы
**Операционные системы:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine и Windows.
@@ -134,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | Включить применение лимитов IP на основе Fail2ban | `true` |
| `XUI_LOG_LEVEL` | Уровень логирования (`debug`, `info`, `warning`, `error`) | `info` |
| `XUI_DEBUG` | Включить режим отладки | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | Включить монитор состояния туннеля (опрашивает URL и перезапускает xray после многократных сбоев; перезапуск отключает всех клиентов) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | Прокси, через который отправляется проба; укажите локальный входящий xray, чтобы проба проверяла туннель (например, `socks5://127.0.0.1:1080`). Пустое значение означает, что проба проверяет только связь с хостом | — |
| `XUI_TUNNEL_HEALTH_URL` | URL, опрашиваемый для проверки состояния туннеля | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | Интервал между пробами | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Таймаут на одну пробу | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | Число последовательных сбоев до запуска перезапуска | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Минимальная задержка между последовательными перезапусками | `5m` |
## Поддерживаемые языки
+30 -1
View File
@@ -33,7 +33,7 @@ Orijinal X-UI projesinin geliştirilmiş bir çatallaması (fork) olarak inşa e
- **Trafik istatistikleri** — Gelen bağlantı (Inbound), istemci ve giden bağlantı (Outbound) bazında istatistikler ve sıfırlama kontrolleri.
- **Çoklu düğüm (Multi-node) desteği** — Tek bir panel üzerinden birden fazla sunucuyu yönetin ve ölçeklendirin.
- **Giden bağlantı (Outbound) ve yönlendirme** — WARP, NordVPN, özel yönlendirme kuralları, yük dengeleyiciler (load balancers) ve giden bağlantı proxy zincirleme (proxy chaining).
- **Dahili abonelik sunucusu** (Birden fazla çıktı formatı ile).
- **Dahili abonelik sunucusu** (Birden fazla çıktı formatı ve [özel sayfa şablonları](docs/custom-subscription-templates.md) ile).
- Uzaktan izleme ve yönetim için **Telegram botu**.
- Panel içi Swagger dokümantasyonuna sahip **RESTful API**.
- **Esnek depolama** — SQLite (varsayılan) veya PostgreSQL.
@@ -73,10 +73,32 @@ Orijinal X-UI projesinin geliştirilmiş bir çatallaması (fork) olarak inşa e
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
Belirli bir sürümü kurmak için, etiketini (ör. `v3.4.0`) ekleyin:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
Sürekli güncellenen **dev** sürümünü (kararlı bir sürüm değil; `main` dalından her commit'te oluşturulan en son ön sürüm) kurmak için `dev-latest` değerini geçirin:
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
Kurulum sırasında rastgele bir kullanıcı adı, şifre ve erişim yolu oluşturulur. Kurulumdan sonra, hizmeti başlatabileceğiniz/durdurabileceğiniz, giriş bilgilerinizi görüntüleyebileceğiniz veya sıfırlayabileceğiniz, SSL sertifikalarını yönetebileceğiniz ve çok daha fazlasını yapabileceğiniz yönetim menüsünü açmak için terminalde `x-ui` komutunu çalıştırın.
Tam dokümantasyon için lütfen [proje Wiki sayfasını](https://github.com/MHSanaei/3x-ui/wiki) ziyaret edin.
### Etkileşimsiz kurulum
Yükleyici, cloud-init için **etkileşimsiz** olarak da çalışır.
`XUI_NONINTERACTIVE=1` ayarlayın (veya TTY olmadan boru hattına aktarın); kurulum baştan
sona hiçbir soru sormadan tamamlanır, rastgele kimlik bilgileri oluşturup bunları
`/etc/x-ui/install-result.env` dosyasına yazar. Şunlar için [`deploy/`](deploy/) klasörüne bakın:
- [Cloud-init user-data](deploy/cloud-init/) — herhangi bir bulutta etkileşimsiz kurulum (Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle)
- [Hetzner Cloud notları](deploy/marketplace/hetzner/) — Hetzner üzerinde cloud-init tabanlı dağıtım
## Desteklenen Platformlar
**İşletim sistemleri:** Ubuntu, Debian, Armbian, Fedora, CentOS, RHEL, AlmaLinux, Rocky Linux, Oracle Linux, Amazon Linux, Virtuozzo, Arch, Manjaro, Parch, openSUSE (Tumbleweed / Leap), Alpine ve Windows.
@@ -134,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | Fail2ban tabanlı IP limit uygulamasını etkinleştir | `true` |
| `XUI_LOG_LEVEL` | Günlük (Log) ayrıntı seviyesi (`debug`, `info`, `warning`, `error`) | `info` |
| `XUI_DEBUG` | Hata ayıklama (debug) modunu etkinleştir | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | Tünel sağlık izleyicisini etkinleştir (bir URL'yi yoklar ve tekrarlanan başarısızlıklardan sonra xray'i yeniden başlatır; yeniden başlatma tüm istemcilerin bağlantısını düşürür) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | Yoklamanın gönderildiği proxy; yoklamanın tüneli test etmesi için bunu yerel bir xray gelen bağlantısına yönlendirin (ör. `socks5://127.0.0.1:1080`). Boş bırakılırsa yoklama yalnızca ana makine bağlantısını kontrol eder | — |
| `XUI_TUNNEL_HEALTH_URL` | Tünel sağlığı için yoklanan URL | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | Yoklamalar arasındaki aralık | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | Yoklama başına zaman aşımı | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | Yeniden başlatma tetiklenmeden önceki ardışık başarısızlık sayısı | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | Ardışık yeniden başlatmalar arasındaki minimum gecikme | `5m` |
## Desteklenen Diller
+30 -1
View File
@@ -33,7 +33,7 @@
- **流量统计** — 按入站、按客户端、按出站统计,并支持重置控制。
- **多节点支持** — 从单一面板管理并扩展到多台服务器。
- **出站与路由** — WARP、NordVPN、自定义路由规则、负载均衡器和出站代理链。
- **内置订阅服务器**,支持多种输出格式。
- **内置订阅服务器**,支持多种输出格式和[自定义页面模板](docs/custom-subscription-templates.md)
- **Telegram 机器人**,用于远程监控和管理。
- **RESTful API**,带有面板内置的 Swagger 文档。
- **灵活的存储** — SQLite(默认)或 PostgreSQL。
@@ -73,10 +73,32 @@
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)
```
若要安装特定版本,请在命令后附加对应的标签(例如 `v3.4.0`):
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) v3.4.0
```
若要安装滚动更新的 **dev** 版本(来自 `main` 的最新逐次提交预发布版本,而非稳定版本),请传入 `dev-latest`
```bash
bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) dev-latest
```
安装过程中会生成随机的用户名、密码和访问路径。安装完成后,运行 `x-ui` 打开管理菜单,您可以在其中启动/停止服务、查看或重置登录凭据、管理 SSL 证书等。
完整文档请参阅 [项目Wiki](https://github.com/MHSanaei/3x-ui/wiki)。
### 无人值守安装
安装程序也可以**非交互式**运行,适用于 cloud-init。
设置 `XUI_NONINTERACTIVE=1`(或在无 TTY 的情况下通过管道传入),它就会全程
零提示地完成端到端安装,生成随机凭据并写入
`/etc/x-ui/install-result.env`。请参阅 [`deploy/`](deploy/)
- [Cloud-init user-data](deploy/cloud-init/) — 在任意云平台上无人值守安装(Hetzner/AWS/DO/Vultr/GCP/Azure/Oracle
- [Hetzner Cloud 说明](deploy/marketplace/hetzner/) — 在 Hetzner 上基于 cloud-init 的部署
## 支持的平台
**操作系统:** Ubuntu、Debian、Armbian、Fedora、CentOS、RHEL、AlmaLinux、Rocky Linux、Oracle Linux、Amazon Linux、Virtuozzo、Arch、Manjaro、Parch、openSUSE (Tumbleweed / Leap)、Alpine 和 Windows。
@@ -134,6 +156,13 @@ docker run -d --cap-add=NET_ADMIN --cap-add=NET_RAW ... ghcr.io/mhsanaei/3x-ui
| `XUI_ENABLE_FAIL2BAN` | 启用基于 Fail2ban 的 IP 限制 | `true` |
| `XUI_LOG_LEVEL` | 日志级别(`debug``info``warning``error` | `info` |
| `XUI_DEBUG` | 启用调试模式 | `false` |
| `XUI_TUNNEL_HEALTH_MONITOR` | 启用隧道健康监控(探测某个 URL,在连续多次失败后重启 xray;重启会断开所有客户端) | `false` |
| `XUI_TUNNEL_HEALTH_PROXY` | 探测请求所经过的代理;将其指向本地 xray 入站,使探测能够测试隧道(例如 `socks5://127.0.0.1:1080`)。留空表示探测仅检查主机连通性 | — |
| `XUI_TUNNEL_HEALTH_URL` | 用于检测隧道健康状况的探测 URL | `https://www.cloudflare.com/cdn-cgi/trace` |
| `XUI_TUNNEL_HEALTH_INTERVAL` | 两次探测之间的间隔 | `30s` |
| `XUI_TUNNEL_HEALTH_TIMEOUT` | 单次探测的超时时间 | `10s` |
| `XUI_TUNNEL_HEALTH_FAILURES` | 触发重启前的连续失败次数 | `3` |
| `XUI_TUNNEL_HEALTH_COOLDOWN` | 两次连续重启之间的最小间隔 | `5m` |
## 支持的语言
+9 -16
View File
@@ -1,27 +1,20 @@
# Cloud deployment & golden images
# Cloud deployment (unattended install)
Tooling to ship the 3x-ui panel as a cloud image or via unattended install,
with **per-instance credentials generated on first boot** (never `admin/admin`,
never a shared session secret). Everything here supports **amd64 and arm64**.
Tooling to ship the 3x-ui panel via unattended install, with **per-instance
credentials generated on first boot** (never `admin/admin`, never a shared
session secret). Works on amd64 and arm64.
| Path | What it is | Use when |
| --- | --- | --- |
| [`cloud-init/`](cloud-init/) | Generic cloud-init user-data (unattended `install.sh`) | Any cloud, no image build |
| [`packer/`](packer/) | Packer build → AWS AMI + qcow2/raw | Reusable / Marketplace images |
| [`lightsail/`](lightsail/) | Launch script + snapshot builder | Amazon Lightsail |
| [`firstboot/`](firstboot/) | First-boot unit + script that mints per-instance creds | Used by the Packer/Lightsail images |
| [`marketplace/aws/`](marketplace/aws/) | AWS Marketplace submission checklist | Publishing an EC2 AMI |
| [`marketplace/hetzner/`](marketplace/hetzner/) | Hetzner Cloud notes | Hetzner deployments |
| [`test/`](test/) | Container smoke tests | Verifying the install/firstboot paths |
| [`test/`](test/) | Container smoke test | Verifying the install path |
## Two models
## How it works
- **Non-interactive install (cloud-init):** `install.sh` runs unattended when
`XUI_NONINTERACTIVE=1` or stdin is not a TTY. Each instance installs and
configures itself with random credentials. See [`cloud-init/README.md`](cloud-init/README.md).
- **Golden image (Packer):** the image contains the panel but **no DB and no
secrets**; `firstboot` generates unique credentials on first boot. See
[`packer/README.md`](packer/README.md).
`install.sh` runs unattended when `XUI_NONINTERACTIVE=1` or stdin is not a TTY.
Each instance installs and configures itself with random credentials. See
[`cloud-init/README.md`](cloud-init/README.md).
## Unattended install knobs
+4 -9
View File
@@ -1,12 +1,8 @@
# 3x-ui via cloud-init (generic, no golden image)
# 3x-ui via cloud-init
This is the **secondary** deployment path: a single [`cloud-init.yaml`](cloud-init.yaml)
user-data file that installs 3x-ui non-interactively on a fresh Ubuntu/Debian
VM and generates **unique random credentials per instance**. Use it when you do
not want to build a golden image — it works on any cloud-init platform.
> For AWS Marketplace / reusable images, use the Packer build in
> [`../packer/`](../packer/) instead.
A single [`cloud-init.yaml`](cloud-init.yaml) user-data file that installs 3x-ui
non-interactively on a fresh Ubuntu/Debian VM and generates **unique random
credentials per instance**. It works on any cloud-init platform.
## How it works
@@ -53,7 +49,6 @@ Edit the `export XUI_*` lines inside the `write_files` block of
`hcloud server create --image ubuntu-24.04 --user-data-from-file cloud-init.yaml ...`
- **AWS EC2***Advanced details → User data*: paste the file. Or
`aws ec2 run-instances --user-data file://cloud-init.yaml ...`
(For a reusable Marketplace image use the Packer AMI build instead.)
- **DigitalOcean** — *Create Droplet → Advanced options → Add Initialization
scripts (user data)*: paste the file. Or `doctl compute droplet create --user-data-file cloud-init.yaml ...`
- **Vultr***Deploy → Additional Features → Cloud-Init User-Data*: paste the file.
-22
View File
@@ -1,22 +0,0 @@
[Unit]
Description=3x-ui first-boot per-instance credential generation
Documentation=https://github.com/MHSanaei/3x-ui
# Run after the network and cloud-init are up, but BEFORE the panel starts, so
# the panel never serves the default admin/admin account.
After=network-online.target cloud-init.service
Wants=network-online.target
Before=x-ui.service
# Skip entirely once the sentinel exists (cheap guard; the script re-checks too).
ConditionPathExists=!/etc/x-ui/.firstboot-done
[Service]
Type=oneshot
RemainAfterExit=yes
# Inherit the same DB configuration the panel uses (sqlite default / postgres).
EnvironmentFile=-/etc/default/x-ui
EnvironmentFile=-/etc/conf.d/x-ui
EnvironmentFile=-/etc/sysconfig/x-ui
ExecStart=/usr/local/x-ui/x-ui-firstboot.sh
[Install]
WantedBy=multi-user.target
-166
View File
@@ -1,166 +0,0 @@
#!/usr/bin/env bash
#
# x-ui-firstboot.sh — generate per-instance 3x-ui panel credentials on first boot.
#
# A golden image (AMI / qcow2) MUST ship without an initialized x-ui.db: the
# panel seeds a hardcoded admin/admin user and generates its session secret +
# panel GUID on first start, so a baked DB would make every clone share the same
# credentials and secret. This script runs ONCE, before x-ui.service starts, and
# replaces the default admin with fresh random credentials on a random high port.
#
# Idempotent: a sentinel file guards against re-running. If a non-default admin
# already exists (operator pre-configured the box), regeneration is skipped.
#
# Wired up by deploy/packer/scripts/provision.sh; ordered Before=x-ui.service.
set -u
SENTINEL="/etc/x-ui/.firstboot-done"
CRED_FILE="/etc/x-ui/credentials.txt"
MOTD_FILE="/etc/motd"
XUI_DIR="${XUI_MAIN_FOLDER:-/usr/local/x-ui}"
XUI_BIN="${XUI_DIR}/x-ui"
log() { echo "[x-ui-firstboot] $*"; }
# Already provisioned — nothing to do (idempotent on re-run / re-image).
if [ -f "$SENTINEL" ]; then
log "sentinel $SENTINEL present; skipping."
exit 0
fi
if [ ! -x "$XUI_BIN" ]; then
log "ERROR: x-ui binary not found at $XUI_BIN"
exit 1
fi
# Inherit DB configuration (sqlite default; postgres via XUI_DB_TYPE/XUI_DB_DSN)
# from the same env files the systemd unit loads, so the binary talks to the
# same database the panel will use.
for ef in /etc/default/x-ui /etc/conf.d/x-ui /etc/sysconfig/x-ui; do
if [ -r "$ef" ]; then
set -a
# shellcheck disable=SC1090
. "$ef"
set +a
fi
done
install -d -m 755 /etc/x-ui 2> /dev/null || true
# Defense-in-depth: make sure the panel is not running while we mutate the DB.
if command -v systemctl > /dev/null 2>&1; then
systemctl stop x-ui > /dev/null 2>&1 || true
fi
gen_random_string() {
local length="$1"
openssl rand -base64 $((length * 2)) | tr -dc 'a-zA-Z0-9' | head -c "$length"
}
# Best-effort public IPv4 for the displayed access URL (cosmetic only — the
# panel binds 0.0.0.0). Falls back to the primary local IP, then a placeholder.
detect_ip() {
local ip=""
local url
for url in https://api4.ipify.org https://ipv4.icanhazip.com https://4.ident.me; do
ip=$(curl -fsS4 --max-time 3 "$url" 2> /dev/null | tr -d '[:space:]')
if [[ "$ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "$ip"
return 0
fi
done
ip=$(hostname -I 2> /dev/null | awk '{print $1}')
if [ -n "$ip" ]; then
echo "$ip"
return 0
fi
echo "<server-ip>"
}
# Detect whether the seeded admin/admin default is still in place.
default_creds=$("$XUI_BIN" setting -show true 2> /dev/null | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
# The parse MUST yield exactly "true" or "false". If the command failed or its
# output format changed, refuse to proceed: do NOT write the sentinel, so the
# next boot retries instead of silently leaving admin/admin in place.
if [ "$default_creds" != "true" ] && [ "$default_creds" != "false" ]; then
log "ERROR: could not determine credential state (hasDefaultCredential='${default_creds}'); not writing sentinel, will retry next boot."
exit 1
fi
if [ "$default_creds" = "false" ]; then
log "non-default admin already configured; skipping credential regeneration."
{
echo "3x-ui first-boot: a non-default admin account already exists on this"
echo "instance, so credentials were left unchanged."
} > "$MOTD_FILE" 2> /dev/null || true
: > "$SENTINEL" 2> /dev/null || true
chmod 600 "$SENTINEL" 2> /dev/null || true
exit 0
fi
log "generating per-instance credentials..."
NEW_USER="${XUI_USERNAME:-$(gen_random_string 10)}"
NEW_PASS="${XUI_PASSWORD:-$(gen_random_string 16)}"
NEW_PATH="${XUI_WEB_BASE_PATH:-$(gen_random_string 18)}"
NEW_PORT="${XUI_PANEL_PORT:-$(shuf -i 1024-62000 -n 1)}"
# Clean settings slate: drops any baked port/webBasePath and forces the panel
# to regenerate its session secret + panel GUID on next start (per-instance).
"$XUI_BIN" setting -reset > /dev/null 2>&1 || true
# Apply fresh random identity. UpdateFirstUser renames the seeded admin row and
# rehashes the password, so admin/admin no longer exists after this call.
if ! "$XUI_BIN" setting -username "$NEW_USER" -password "$NEW_PASS" -port "$NEW_PORT" -webBasePath "$NEW_PATH" > /dev/null 2>&1; then
log "ERROR: failed to apply new panel settings."
exit 1
fi
API_TOKEN=$("$XUI_BIN" setting -getApiToken true 2> /dev/null | grep -Eo 'apiToken: .+' | awk '{print $2}')
SERVER_IP=$(detect_ip)
ACCESS_URL="http://${SERVER_IP}:${NEW_PORT}/${NEW_PATH}"
# Persist credentials for the operator (root-only). Values are shell-escaped
# with %q so the file stays safe to `source` even if a value contains shell
# metacharacters (the smoke test and operators source this file).
umask 077
{
echo "# 3x-ui per-instance credentials (generated on first boot)"
printf 'XUI_USERNAME=%q\n' "$NEW_USER"
printf 'XUI_PASSWORD=%q\n' "$NEW_PASS"
printf 'XUI_PANEL_PORT=%q\n' "$NEW_PORT"
printf 'XUI_WEB_BASE_PATH=%q\n' "$NEW_PATH"
printf 'XUI_ACCESS_URL=%q\n' "$ACCESS_URL"
printf 'XUI_API_TOKEN=%q\n' "$API_TOKEN"
} > "$CRED_FILE"
chmod 600 "$CRED_FILE" 2> /dev/null || true
# Friendly login banner shown on SSH / console before the panel is reachable.
# /etc/motd is world-readable, so it MUST NOT contain the password or API token;
# those secrets live only in ${CRED_FILE} (mode 600). Show non-secret info only.
cat > "$MOTD_FILE" 2> /dev/null << EOF
========================================================================
3x-ui panel — per-instance credentials (generated on first boot)
========================================================================
Access URL : ${ACCESS_URL}
Username : ${NEW_USER}
The password and API token are NOT shown here (this banner is
world-readable). Read them as root with:
sudo cat ${CRED_FILE}
Change the password after login. If no public IP is shown above,
replace <server-ip> with the address you reach this server on.
========================================================================
EOF
# Mark complete so we never regenerate on subsequent boots.
: > "$SENTINEL" 2> /dev/null || true
chmod 600 "$SENTINEL" 2> /dev/null || true
log "done. Panel will start on port ${NEW_PORT} with a unique admin account."
exit 0
-94
View File
@@ -1,94 +0,0 @@
# 3x-ui on Amazon Lightsail
Two self-service ways to run 3x-ui on Lightsail, both producing **unique
per-instance credentials** (never `admin/admin`, never a shared secret).
> **Reality check.** The Lightsail *blueprint* list (WordPress, LAMP, GitLab…)
> is curated by AWS — you **cannot** self-publish your panel there, and Lightsail
> **cannot** launch from an arbitrary EC2 AMI. What you *can* do yourself is the
> two paths below. (For a public AWS listing you'd use the EC2 **AMI** +
> Marketplace path in [`../marketplace/aws/`](../marketplace/aws/), which is a
> different product from Lightsail.)
---
## Path A — launch script (simplest, self-service)
Install on a fresh instance at creation time. No image to build.
1. **Create instance** → platform **Linux/Unix** → blueprint **OS Only → Ubuntu 24.04**.
2. **Add launch script** → paste [`launch-script.sh`](launch-script.sh).
3. Create the instance.
4. After it boots, read the credentials:
```bash
ssh ubuntu@<public-ip> 'sudo cat /etc/x-ui/install-result.env'
```
5. **Open the panel port** (see the firewall note below) and log in.
CLI equivalent:
```bash
aws lightsail create-instances \
--instance-names my-3xui \
--availability-zone eu-central-1a \
--blueprint-id ubuntu_24_04 \
--bundle-id small_3_0 \
--user-data file://deploy/lightsail/launch-script.sh \
--region eu-central-1
```
By default the panel uses a **random** high port (in `install-result.env`). To
pin a known port so you can pre-open it, set `export XUI_PANEL_PORT=54321` inside
`launch-script.sh`.
---
## Path B — reusable snapshot (your own "ready image")
Build a Lightsail **snapshot** once; launch as many instances from it as you
like, each generating its own credentials on first boot (the golden-image model).
```bash
deploy/lightsail/build-snapshot.sh --region eu-central-1 --panel-port 54321
```
What it does: launches a temporary Ubuntu instance with
[`snapshot-userdata.sh`](snapshot-userdata.sh) (installs the panel, **no DB**,
enables the first-boot unit), strips all state via the shared
[`cleanup.sh`](../packer/scripts/cleanup.sh), then snapshots and deletes the
build instance. Requires `awscli`, `jq`, `ssh` and Lightsail permissions.
Launch instances from the snapshot:
```bash
aws lightsail create-instances-from-snapshot \
--instance-snapshot-name 3x-ui-ubuntu-24.04-<stamp> \
--instance-names my-3xui-1 --bundle-id small_3_0 \
--availability-zone eu-central-1a --region eu-central-1
```
Each launched instance runs `x-ui-firstboot` and writes its unique credentials to
`/etc/x-ui/credentials.txt` + `/etc/motd`. With `--panel-port` the port is the
same across instances (only the credentials differ), so you can pre-open it.
> Lightsail snapshots are **private to your AWS account** (and region). To use one
> elsewhere you can export it to EC2 (`aws lightsail export-snapshot`) and share
> the resulting AMI.
---
## Lightsail firewall note (important)
Lightsail's per-instance firewall only opens **22 / 80 / 443** by default. The
panel runs on a different port, so you must open it:
- Console: instance → **Networking → IPv4 Firewall → Add rule** (TCP, the panel port).
- CLI:
```bash
aws lightsail open-instance-public-ports --region eu-central-1 \
--instance-name my-3xui \
--port-info fromPort=54321,toPort=54321,protocol=TCP
```
The panel port is in `/etc/x-ui/install-result.env` (Path A) or
`/etc/x-ui/credentials.txt` (Path B), or fixed via `--panel-port` / `XUI_PANEL_PORT`.
-192
View File
@@ -1,192 +0,0 @@
#!/usr/bin/env bash
#
# build-snapshot.sh — build a reusable Amazon Lightsail snapshot of 3x-ui.
#
# Flow (mirrors the Packer golden-image model, via the Lightsail API):
# 1. create an Ubuntu Lightsail instance with snapshot-userdata.sh
# (installs the panel, NO database, enables the first-boot unit)
# 2. wait for provisioning, then (optionally) pin a known panel port and run
# the shared cleanup.sh (wipes any DB/creds/keys/host-keys/cloud-init state)
# 3. stop the instance and create an instance snapshot
# 4. delete the build instance (unless --keep-instance)
#
# Every instance you later launch from the snapshot generates its OWN unique
# credentials on first boot (see deploy/firstboot/). The snapshot is private to
# your AWS account.
#
# Requirements: awscli v2, jq, ssh. AWS credentials with Lightsail permissions.
# Usage:
# deploy/lightsail/build-snapshot.sh --region eu-central-1 [options]
# Options:
# --region <r> AWS region (default: $AWS_REGION or eu-central-1)
# --blueprint-id <id> Lightsail blueprint (default: ubuntu_24_04)
# --bundle-id <id> Lightsail bundle/size (default: small_3_0)
# --availability-zone <z> AZ (default: <region>a)
# --panel-port <p> Pin the panel port in the snapshot so you can pre-open
# it in the Lightsail firewall (default: random per instance)
# --snapshot-name <n> Snapshot name (default: 3x-ui-ubuntu-24.04-<timestamp>)
# --keep-instance Do not delete the build instance afterwards
set -euo pipefail
REGION="${AWS_REGION:-eu-central-1}"
BLUEPRINT="ubuntu_24_04"
BUNDLE="small_3_0"
AZ=""
PANEL_PORT=""
SNAPSHOT_NAME=""
KEEP_INSTANCE=0
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
STAMP="$(date +%Y%m%d-%H%M%S)"
INSTANCE_NAME="3xui-build-${STAMP}"
KEY_FILE=""
log() { echo "[build-snapshot] $*"; }
die() {
echo "[build-snapshot] ERROR: $*" >&2
exit 1
}
while [ $# -gt 0 ]; do
case "$1" in
--region) REGION="$2"; shift 2 ;;
--blueprint-id) BLUEPRINT="$2"; shift 2 ;;
--bundle-id) BUNDLE="$2"; shift 2 ;;
--availability-zone) AZ="$2"; shift 2 ;;
--panel-port) PANEL_PORT="$2"; shift 2 ;;
--snapshot-name) SNAPSHOT_NAME="$2"; shift 2 ;;
--keep-instance) KEEP_INSTANCE=1; shift ;;
-h | --help) sed -n '2,40p' "$0"; exit 0 ;;
*) die "unknown option: $1" ;;
esac
done
[ -n "$AZ" ] || AZ="${REGION}a"
[ -n "$SNAPSHOT_NAME" ] || SNAPSHOT_NAME="3x-ui-ubuntu-24.04-${STAMP}"
for cmd in aws jq ssh; do
command -v "$cmd" > /dev/null 2>&1 || die "'$cmd' is required"
done
SSH_OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 -o LogLevel=ERROR)
cleanup() {
[ -n "$KEY_FILE" ] && rm -f "$KEY_FILE"
if [ "$KEEP_INSTANCE" -eq 0 ]; then
aws lightsail delete-instance --instance-name "$INSTANCE_NAME" --region "$REGION" > /dev/null 2>&1 || true
fi
}
trap cleanup EXIT
wait_state() {
local want="$1" tries="${2:-60}" st
for _ in $(seq 1 "$tries"); do
st=$(aws lightsail get-instance-state --instance-name "$INSTANCE_NAME" --region "$REGION" \
--query 'state.name' --output text 2> /dev/null || echo "")
[ "$st" = "$want" ] && return 0
sleep 5
done
return 1
}
log "creating build instance ${INSTANCE_NAME} (${BLUEPRINT}/${BUNDLE}) in ${REGION}..."
aws lightsail create-instances \
--instance-names "$INSTANCE_NAME" \
--availability-zone "$AZ" \
--blueprint-id "$BLUEPRINT" \
--bundle-id "$BUNDLE" \
--user-data "file://${SCRIPT_DIR}/snapshot-userdata.sh" \
--region "$REGION" > /dev/null
log "waiting for instance to run..."
wait_state running 60 || die "instance did not reach 'running'"
IP=$(aws lightsail get-instance --instance-name "$INSTANCE_NAME" --region "$REGION" \
--query 'instance.publicIpAddress' --output text)
if [ -z "$IP" ] || [ "$IP" = "None" ]; then die "no public IP"; fi
log "instance IP: ${IP}"
KEY_FILE="$(mktemp)"
# download-default-key-pair returns the key in 'privateKeyBase64'. Despite the
# name, the CLI historically emits the plaintext PEM (-----BEGIN...); the API
# docs describe it as base64. Handle both: write PEM as-is, else base64-decode.
KEY_RAW="$(aws lightsail download-default-key-pair --region "$REGION" \
--query 'privateKeyBase64' --output text)"
[ -n "$KEY_RAW" ] && [ "$KEY_RAW" != "None" ] || die "failed to download default key pair"
case "$KEY_RAW" in
*-----BEGIN*) printf '%s\n' "$KEY_RAW" > "$KEY_FILE" ;;
*) printf '%s' "$KEY_RAW" | base64 -d > "$KEY_FILE" 2> /dev/null \
|| die "private key is neither PEM nor valid base64" ;;
esac
grep -q -- "-----BEGIN" "$KEY_FILE" || die "downloaded key is not a valid PEM private key"
chmod 600 "$KEY_FILE"
log "waiting for provisioning to finish (this installs the panel)..."
ok=0
for _ in $(seq 1 72); do # ~12 min
if ssh "${SSH_OPTS[@]}" -i "$KEY_FILE" "ubuntu@${IP}" \
'test -f /var/lib/3xui-provision-done' 2> /dev/null; then
ok=1
break
fi
sleep 10
done
[ "$ok" -eq 1 ] || die "provisioning did not complete in time"
log "provisioning complete."
if [ -n "$PANEL_PORT" ]; then
log "pinning panel port ${PANEL_PORT} (username/password stay random)..."
ssh "${SSH_OPTS[@]}" -i "$KEY_FILE" "ubuntu@${IP}" \
"echo 'XUI_PANEL_PORT=${PANEL_PORT}' | sudo tee -a /etc/default/x-ui >/dev/null"
fi
log "stripping instance state (shared cleanup.sh)..."
ssh "${SSH_OPTS[@]}" -i "$KEY_FILE" "ubuntu@${IP}" \
'curl -fsSL https://raw.githubusercontent.com/MHSanaei/3x-ui/main/deploy/packer/scripts/cleanup.sh | sudo bash'
log "stopping instance..."
aws lightsail stop-instance --instance-name "$INSTANCE_NAME" --region "$REGION" > /dev/null
wait_state stopped 60 || die "instance did not stop"
log "creating snapshot ${SNAPSHOT_NAME}..."
aws lightsail create-instance-snapshot \
--instance-name "$INSTANCE_NAME" \
--instance-snapshot-name "$SNAPSHOT_NAME" \
--region "$REGION" > /dev/null
log "waiting for snapshot to become available..."
snap_ok=0
for _ in $(seq 1 120); do # ~20 min
state=$(aws lightsail get-instance-snapshot --instance-snapshot-name "$SNAPSHOT_NAME" \
--region "$REGION" --query 'instanceSnapshot.state' --output text 2> /dev/null || echo "")
[ "$state" = "available" ] && {
snap_ok=1
break
}
sleep 10
done
[ "$snap_ok" -eq 1 ] || die "snapshot did not become available"
log "DONE."
echo
echo "================================================================"
echo " Lightsail snapshot ready: ${SNAPSHOT_NAME} (region ${REGION})"
echo "================================================================"
echo " Launch an instance from it:"
echo " aws lightsail create-instances-from-snapshot \\"
echo " --instance-snapshot-name ${SNAPSHOT_NAME} \\"
echo " --instance-names my-3xui-1 --bundle-id ${BUNDLE} \\"
echo " --availability-zone ${AZ} --region ${REGION}"
if [ -n "$PANEL_PORT" ]; then
echo
echo " Then open the panel port (pinned to ${PANEL_PORT}):"
echo " aws lightsail open-instance-public-ports --region ${REGION} \\"
echo " --instance-name my-3xui-1 \\"
echo " --port-info fromPort=${PANEL_PORT},toPort=${PANEL_PORT},protocol=TCP"
else
echo
echo " Each instance picks a RANDOM panel port. After it boots, read it from"
echo " sudo cat /etc/x-ui/credentials.txt"
echo " and open that TCP port in the instance's Lightsail IPv4 firewall."
fi
echo "================================================================"
-51
View File
@@ -1,51 +0,0 @@
#!/bin/bash
#
# Amazon Lightsail launch script for 3x-ui (self-service, per-instance creds).
#
# Use it one of two ways when creating an Ubuntu 24.04 Lightsail instance:
# * Console: "Add launch script" -> paste this file.
# * CLI: aws lightsail create-instances --user-data file://launch-script.sh ...
#
# It installs the latest 3x-ui release non-interactively and generates unique
# random credentials for THIS instance. The full credentials land in
# /etc/x-ui/install-result.env (mode 600); /etc/motd shows only the URL + username.
#
# IMPORTANT (Lightsail firewall): Lightsail only opens 22/80/443 by default. The
# panel listens on a random high port, so after boot read the port from
# /etc/x-ui/install-result.env and open it under the instance's Networking tab
# (IPv4 Firewall), or pin a known port below and pre-open it.
set -e
export DEBIAN_FRONTEND=noninteractive
# --- Non-interactive install knobs ------------------------------------------
export XUI_NONINTERACTIVE=1
export XUI_SSL_MODE="${XUI_SSL_MODE:-none}"
# Pin a known panel port so you can pre-open it in the Lightsail firewall
# (otherwise a random high port is chosen). Username/password stay random:
# export XUI_PANEL_PORT="54321"
# Other optional pins (unset => secure random):
# export XUI_USERNAME="admin2"
# export XUI_PASSWORD="change-me"
# export XUI_WEB_BASE_PATH="panel"
# Domain TLS instead of plain HTTP:
# export XUI_SSL_MODE="domain" XUI_DOMAIN="panel.example.com" XUI_ACME_EMAIL="you@example.com"
# ----------------------------------------------------------------------------
curl -fsSL https://raw.githubusercontent.com/MHSanaei/3x-ui/main/install.sh | bash
# /etc/motd is world-readable, so it gets ONLY non-secret info (URL + username);
# the full credentials stay in the root-only /etc/x-ui/install-result.env
# (mode 600) — read them with `sudo cat` over SSH.
if [ -r /etc/x-ui/install-result.env ]; then
# shellcheck disable=SC1091
. /etc/x-ui/install-result.env
{
echo
echo "=== 3x-ui panel (generated on first boot) ==="
echo "URL: ${XUI_ACCESS_URL:-unknown}"
echo "Username: ${XUI_USERNAME:-unknown}"
echo "Password + API token: sudo cat /etc/x-ui/install-result.env"
echo "Open the panel port in the Lightsail IPv4 firewall, then log in."
echo "============================================="
} >> /etc/motd 2>/dev/null || true
fi
-59
View File
@@ -1,59 +0,0 @@
#!/bin/bash
#
# Lightsail snapshot provisioning user-data (used by build-snapshot.sh).
#
# Installs the 3x-ui panel into a build instance but creates NO database and
# NO credentials, and enables the first-boot unit. The instance is then snapshot
# so that every instance launched from the snapshot generates its own unique
# credentials on first boot (see deploy/firstboot/).
#
# This is the Lightsail equivalent of deploy/packer/scripts/provision.sh. It is
# NOT for end users — use deploy/lightsail/launch-script.sh for a direct install.
set -e
export DEBIAN_FRONTEND=noninteractive
REPO=MHSanaei/3x-ui
XUI_DIR=/usr/local/x-ui
RAW="https://raw.githubusercontent.com/${REPO}/main"
apt-get update
apt-get install -y --no-install-recommends \
ca-certificates curl tar tzdata socat openssl cron jq
ARCH=$(dpkg --print-architecture) # amd64 | arm64
VER=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | jq -r .tag_name)
if [ -z "$VER" ] || [ "$VER" = "null" ]; then
echo "failed to resolve 3x-ui version" >&2
exit 1
fi
tmp=$(mktemp -d)
curl -fL4 --retry 3 -o "${tmp}/x.tar.gz" \
"https://github.com/${REPO}/releases/download/${VER}/x-ui-linux-${ARCH}.tar.gz"
systemctl stop x-ui > /dev/null 2>&1 || true
rm -rf "$XUI_DIR"
tar -xzf "${tmp}/x.tar.gz" -C /usr/local/
chmod +x "${XUI_DIR}/x-ui" "${XUI_DIR}/x-ui.sh"
chmod +x "${XUI_DIR}"/bin/* 2> /dev/null || true
cp -f "${XUI_DIR}/x-ui.sh" /usr/bin/x-ui
chmod +x /usr/bin/x-ui
mkdir -p /var/log/x-ui
# Panel + first-boot systemd units.
install -m 644 "${XUI_DIR}/x-ui.service.debian" /etc/systemd/system/x-ui.service
curl -fL4 -o "${XUI_DIR}/x-ui-firstboot.sh" "${RAW}/deploy/firstboot/x-ui-firstboot.sh"
curl -fL4 -o /etc/systemd/system/x-ui-firstboot.service "${RAW}/deploy/firstboot/x-ui-firstboot.service"
chmod 755 "${XUI_DIR}/x-ui-firstboot.sh"
chmod 644 /etc/systemd/system/x-ui-firstboot.service
systemctl daemon-reload
systemctl enable x-ui-firstboot.service
systemctl enable x-ui.service
# No DB, no creds in the image — first boot generates them per-instance.
rm -f /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db-* /etc/x-ui/.firstboot-done 2> /dev/null || true
# Marker that build-snapshot.sh polls for over SSH.
touch /var/lib/3xui-provision-done
echo "[snapshot-userdata] provisioned 3x-ui ${VER} (${ARCH}); no DB created."
-92
View File
@@ -1,92 +0,0 @@
# Publishing 3x-ui to the AWS Marketplace (AMI)
This is the checklist for turning the Packer-built AMI into an AWS Marketplace
listing. It assumes you have already built an AMI with
[`../../packer/`](../../packer/) (locally or via `.github/workflows/image.yml`).
> Do **not** commit AMI IDs, AWS account numbers, or credentials. The AMI ID is
> printed to the workflow job summary at build time.
## 1. Seller registration (one-time)
1. Sign in to the [AWS Marketplace Management Portal](https://aws.amazon.com/marketplace/management/)
with the AWS account that will own the listing.
2. Complete **seller registration** (legal entity, bank, tax interview). Required
before any product can be submitted.
## 2. Build a compliant AMI
Build in the seller account (or share the AMI into it):
```bash
cd deploy/packer
packer init .
# amd64
packer build -only='amazon-ebs.x-ui' \
-var 'xui_version=vX.Y.Z' -var 'xui_arch=amd64' -var 'instance_type=t3.small' -var 'region=eu-central-1' .
# arm64 (Graviton)
packer build -only='amazon-ebs.x-ui' \
-var 'xui_version=vX.Y.Z' -var 'xui_arch=arm64' -var 'instance_type=t4g.small' -var 'region=eu-central-1' .
```
You can list both AMIs (amd64 + arm64) as architectures of a single Marketplace
product, or as separate products.
The image already satisfies the Marketplace AMI policies enforced by `harden.sh`
+ `cleanup.sh`:
- ✅ `PasswordAuthentication no`, `PermitRootLogin prohibit-password`
- ✅ no default OS account passwords (all locked)
- ✅ no baked `authorized_keys`, no SSH host keys (regenerated on boot)
- ✅ base OS = current Ubuntu 24.04 LTS, patched at build time
- ✅ no application default credentials — the panel admin is generated on first
boot on a random high port (no `admin/admin`, no shipped `x-ui.db`)
## 3. Run the self-service AMI scan
1. In the Management Portal: **Server products → AMIs → Upload/scan an AMI**.
2. Share the AMI with the AWS Marketplace scanning account when prompted
(the portal gives you the exact account id and the `modify-image-attribute`
command, or share it from the EC2 console).
3. Start the scan. It checks SSH config, default credentials, open ports, and
for malware. Fix any finding and re-scan.
Common scan findings and where they're handled:
| Finding | Fix (already in the build) |
| --- | --- |
| Password authentication enabled | `harden.sh` sshd drop-in |
| Root login with password | `harden.sh` `PermitRootLogin prohibit-password` |
| Default user password set | `harden.sh` `passwd -l` on all accounts |
| Authorized keys present | `cleanup.sh` removes them |
| Out-of-date packages | base image is the latest LTS; `provision.sh` runs `apt-get update` |
## 4. Create the product (limited / private first)
1. **Server products → Create new product → AMI** (or AMI + CloudFormation).
2. Add title, description, categories, pricing (free or paid), regions, the AMI
id, recommended instance types, and the **usage instructions** (tell buyers
to read `/etc/x-ui/credentials.txt` / MOTD after first boot for the generated
admin login, then change the password).
3. Submit as a **Limited** (private) listing first. AWS publishes it with
restricted visibility so only your account / allow-listed accounts see it.
## 5. Preview & launch test
1. From the limited listing, **subscribe and launch** a test instance.
2. SSH in, `sudo cat /etc/x-ui/credentials.txt`, open the panel URL, log in,
confirm the panel works and the credentials are unique to that instance.
3. Launch a second instance and confirm its credentials differ (no shared
secrets).
## 6. Go public
1. Once the scan passes and the preview looks correct, request **public
visibility** (move from Limited to Public) in the listing.
2. AWS does a final review before the listing goes live.
## References
- AWS Marketplace seller guide: <https://docs.aws.amazon.com/marketplace/latest/userguide/>
- AMI-based product requirements: <https://docs.aws.amazon.com/marketplace/latest/userguide/product-and-ami-policies.html>
- Self-service AMI scanning: <https://docs.aws.amazon.com/marketplace/latest/userguide/product-submission.html>
+3 -24
View File
@@ -1,9 +1,10 @@
# 3x-ui on Hetzner Cloud
Hetzner Cloud does **not** have a third-party image marketplace the way AWS does.
There are two practical ways to ship 3x-ui on Hetzner.
Ship 3x-ui via **cloud-init**: each instance installs non-interactively and
generates unique per-instance credentials (no `admin/admin`, no shared secret).
## Option A — cloud-init (recommended, no image build)
## cloud-init (no image build)
Use the generic user-data from [`../../cloud-init/`](../../cloud-init/). It installs
3x-ui non-interactively and generates unique per-instance credentials.
@@ -27,28 +28,6 @@ After boot, fetch the generated credentials:
ssh root@<server-ip> 'cat /etc/x-ui/install-result.env'
```
## Option B — snapshot from the qcow2 / a configured server
Hetzner lets you create a **snapshot** of a running server and launch new
servers from it. Two ways to get there:
1. **From the Packer qcow2:** Hetzner does not allow direct qcow2 upload via the
normal API, but you can boot a server, write the image to its disk in rescue
mode, then take a snapshot — or simply use Option A, which needs no image.
2. **From a configured server:** spin up a server, install via cloud-init
(Option A), verify, then **delete `/etc/x-ui/x-ui.db` and the first-boot
sentinel** before snapshotting so clones regenerate their own credentials:
```bash
systemctl stop x-ui
rm -f /etc/x-ui/x-ui.db /etc/x-ui/.firstboot-done /etc/x-ui/credentials.txt
# re-enable first-boot regeneration if you installed via Packer:
systemctl enable x-ui-firstboot 2>/dev/null || true
```
> ⚠️ If you snapshot a server **with** its `x-ui.db`, every clone shares the
> same admin credentials and session secret. Always remove the DB first.
## "App"-style listing
Hetzner's curated apps live in the community repo
-7
View File
@@ -1,7 +0,0 @@
# Packer build artifacts (never commit images or manifests)
output-qemu/
*.qcow2
*.raw
packer-manifest.json
packer_cache/
crash.log
-116
View File
@@ -1,116 +0,0 @@
# 3x-ui golden image (Packer)
Builds a cloud image with the 3x-ui panel pre-installed but **not configured**:
the image ships with **no database and no credentials**, and generates a unique
admin account on first boot. This is the **primary** path for AWS Marketplace
and any reusable image.
Two sources, one build:
| Source | Output | For |
| --- | --- | --- |
| `amazon-ebs` | AWS AMI | AWS / Marketplace |
| `qemu` | `qcow2` (+ `raw`) | Hetzner, DigitalOcean, Vultr, GCP, Azure, Oracle, bare metal |
Both sources build for **`amd64` and `arm64`** (select with `-var xui_arch=...`).
## Why no baked DB
3x-ui seeds a hardcoded `admin/admin` user and generates its session secret +
panel GUID the first time it starts. If an image shipped an initialized
`x-ui.db`, **every clone would share the same credentials and secret**. So the
build deliberately:
- installs the panel binary + systemd unit but **never starts it** and **never
creates a DB** (`scripts/provision.sh`);
- wipes any stray DB/credentials/host-keys at the end (`scripts/cleanup.sh`);
- enables `x-ui-firstboot.service`, which on first boot resets settings, sets a
random username/password on a random high port, regenerates the secret/GUID,
and writes the credentials to `/etc/x-ui/credentials.txt` + `/etc/motd`
(`deploy/firstboot/`).
## Prerequisites
- [Packer](https://developer.hashicorp.com/packer) ≥ 1.9
- For `qemu` amd64: `qemu-system-x86`, `qemu-utils` (and `/dev/kvm` for acceptable speed)
- For `qemu` arm64: `qemu-system-arm`, `qemu-efi-aarch64`, `qemu-utils` — best built on an
arm64 host (native KVM); cross-building from x86 works but uses slow TCG emulation
- For `amazon-ebs`: AWS credentials with EC2 build permissions (arm64 builds on a Graviton
instance such as `t4g.small`)
```bash
cd deploy/packer
packer init .
packer fmt -check . # formatting
packer validate . # both sources
```
## Build
Build a specific release (recommended) or `latest`:
```bash
# amd64 qcow2 (no cloud account needed)
packer build -only='qemu.x-ui' -var 'xui_version=v3.3.1' -var 'xui_arch=amd64' .
# arm64 qcow2 (run on an arm64 host for native KVM)
packer build -only='qemu.x-ui' -var 'xui_version=v3.3.1' -var 'xui_arch=arm64' .
# amd64 AWS AMI
packer build -only='amazon-ebs.x-ui' \
-var 'xui_version=v3.3.1' -var 'xui_arch=amd64' -var 'instance_type=t3.small' -var 'region=eu-central-1' .
# arm64 AWS AMI (Graviton)
packer build -only='amazon-ebs.x-ui' \
-var 'xui_version=v3.3.1' -var 'xui_arch=arm64' -var 'instance_type=t4g.small' -var 'region=eu-central-1' .
```
Outputs (per arch):
- `output-qemu/3x-ui-ubuntu-24.04-<arch>.qcow2` and `.raw`
- the AMI id (also recorded in `packer-manifest.json`)
If `/dev/kvm` is unavailable, add `-var 'qemu_accelerator=tcg'` (much slower).
## Key variables
See [`variables.pkr.hcl`](variables.pkr.hcl) for the full list.
| Variable | Default | Notes |
| --- | --- | --- |
| `xui_version` | `latest` | Release tag to install, e.g. `v3.3.1` |
| `xui_arch` | `amd64` | `amd64` or `arm64` (derives the base AMI / cloud image) |
| `region` | `eu-central-1` | AWS region (amazon-ebs) |
| `instance_type` | `t3.small` | EC2 build instance — must match the arch (`t4g.small` for arm64) |
| `qemu_accelerator` | `kvm` | `kvm` or `tcg` |
| `qemu_cpu` | `host` | arm64 `-cpu` model (`host` with KVM, `max` for TCG) |
| `ubuntu_version` | `24.04` | Base Ubuntu LTS (naming/tags) |
The CI workflow builds both arches automatically: amd64 qcow2 on a standard runner,
arm64 qcow2 on a native `ubuntu-24.04-arm` runner, and both AMIs from a single runner
(the build instance runs in AWS).
## First boot
On the first boot of any instance launched from the image:
1. `x-ui-firstboot.service` runs **before** `x-ui.service`.
2. It generates a unique admin username/password, a random panel port, a random
base path, and an API token.
3. Credentials are written to `/etc/x-ui/credentials.txt` (root-only) and shown
in `/etc/motd`. Retrieve them with `sudo cat /etc/x-ui/credentials.txt`.
4. The panel then starts on the random port. `admin/admin` never exists.
## CI
`.github/workflows/image.yml` runs this build on `release: published` (and via
`workflow_dispatch`), attaching the compressed `qcow2` to the release and
building the AMI when AWS credentials are configured.
## A note on host firewalls
`scripts/harden.sh` intentionally does **not** enable a restrictive host
firewall. 3x-ui opens Xray inbound ports on admin-chosen ports at runtime, which
a host firewall would block. Use your cloud provider's security groups/firewall
instead, and open the panel port + your inbound ports there. If you still want a
host firewall, add `ufw` rules in `harden.sh` allowing SSH, the panel port and
your inbound ports.
-59
View File
@@ -1,59 +0,0 @@
#!/usr/bin/env bash
#
# cleanup.sh — strip all instance-specific state and secrets from the image.
#
# Runs LAST. The output image must contain no panel database, no credentials,
# no SSH host keys, and no baked authorized_keys. Fails the build if any of
# those survive.
set -euo pipefail
echo "[cleanup] removing panel database, credentials and first-boot sentinel..."
rm -f /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db-* 2> /dev/null || true
rm -f /etc/x-ui/install-result.env /etc/x-ui/credentials.txt 2> /dev/null || true
rm -f /etc/x-ui/.firstboot-done 2> /dev/null || true
echo "[cleanup] removing SSH host keys (regenerated on first boot)..."
rm -f /etc/ssh/ssh_host_* 2> /dev/null || true
echo "[cleanup] removing any baked authorized_keys..."
rm -f /root/.ssh/authorized_keys 2> /dev/null || true
find /home -maxdepth 3 -name authorized_keys -type f -delete 2> /dev/null || true
echo "[cleanup] resetting machine-id..."
truncate -s 0 /etc/machine-id 2> /dev/null || true
rm -f /var/lib/dbus/machine-id 2> /dev/null || true
ln -sf /etc/machine-id /var/lib/dbus/machine-id 2> /dev/null || true
echo "[cleanup] resetting cloud-init so it re-runs on the real first boot..."
cloud-init clean --logs --seed > /dev/null 2>&1 || rm -rf /var/lib/cloud/* 2> /dev/null || true
echo "[cleanup] truncating logs, history and package caches..."
find /var/log -type f -exec truncate -s 0 {} + 2> /dev/null || true
rm -rf /var/lib/x-ui /var/log/x-ui/* 2> /dev/null || true
apt-get clean || true
rm -rf /var/lib/apt/lists/* 2> /dev/null || true
rm -f /root/.bash_history 2> /dev/null || true
find /home -maxdepth 3 -name .bash_history -type f -delete 2> /dev/null || true
rm -rf /tmp/firstboot 2> /dev/null || true
echo "[cleanup] verifying the image is clean..."
fail=0
for f in /etc/x-ui/x-ui.db /etc/x-ui/credentials.txt /etc/x-ui/install-result.env /etc/x-ui/.firstboot-done; do
if [ -e "$f" ]; then
echo "[cleanup] FATAL: $f is present in the image" >&2
fail=1
fi
done
if ls /etc/ssh/ssh_host_* > /dev/null 2>&1; then
echo "[cleanup] FATAL: SSH host keys present in the image" >&2
fail=1
fi
if [ -e /root/.ssh/authorized_keys ]; then
echo "[cleanup] FATAL: /root/.ssh/authorized_keys present in the image" >&2
fail=1
fi
if [ "$fail" -ne 0 ]; then
exit 1
fi
echo "[cleanup] OK — no DB, no credentials, no host keys, no authorized_keys."
-39
View File
@@ -1,39 +0,0 @@
#!/usr/bin/env bash
#
# harden.sh — baseline OS hardening for AWS Marketplace AMI scanner compliance.
#
# Focus: the controls the scanner actually checks — key-only SSH, no root
# password login, and no default OS account passwords. A restrictive host
# firewall is intentionally NOT enforced by default because 3x-ui opens Xray
# inbound ports on admin-chosen ports at runtime (see README for the rationale
# and how to add ufw rules if you want them).
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
echo "[harden] applying SSH hardening..."
install -d -m 755 /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/99-3xui-hardening.conf << 'EOF'
# 3x-ui golden image hardening (AWS Marketplace scanner compliance)
PasswordAuthentication no
PermitRootLogin prohibit-password
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
EOF
chmod 644 /etc/ssh/sshd_config.d/99-3xui-hardening.conf
echo "[harden] locking passwords on default OS accounts..."
# No account may ship with a usable password. Keys are provisioned per-instance
# by the cloud platform (EC2 metadata / cloud-init) on first boot.
# passwd -l locks the PASSWORD only; key-based login keeps working.
for u in root ubuntu admin; do
if id "$u" > /dev/null 2>&1; then
passwd -l "$u" > /dev/null 2>&1 || true
fi
done
echo "[harden] enabling automatic security updates..."
apt-get update
apt-get install -y --no-install-recommends unattended-upgrades
systemctl enable unattended-upgrades > /dev/null 2>&1 || true
echo "[harden] done."
-76
View File
@@ -1,76 +0,0 @@
#!/usr/bin/env bash
#
# provision.sh — install the 3x-ui panel into a golden image (Packer).
#
# Self-contained: mirrors install.sh's download/extract logic but DELIBERATELY
# does NOT run config_after_install and does NOT create a database. The image
# must ship without /etc/x-ui/x-ui.db so that deploy/firstboot generates unique
# per-instance credentials on first boot. Both x-ui.service and
# x-ui-firstboot.service are enabled but NOT started here.
#
# Inputs (from Packer environment_vars):
# XUI_VERSION release tag (e.g. v3.3.1) or 'latest'
# XUI_ARCH amd64 (default) or arm64
set -euo pipefail
XUI_VERSION="${XUI_VERSION:-latest}"
XUI_ARCH="${XUI_ARCH:-amd64}"
XUI_DIR="/usr/local/x-ui"
REPO="MHSanaei/3x-ui"
export DEBIAN_FRONTEND=noninteractive
echo "[provision] installing base packages..."
apt-get update
apt-get install -y --no-install-recommends \
ca-certificates curl tar tzdata socat openssl cron jq
echo "[provision] resolving 3x-ui version..."
if [ "$XUI_VERSION" = "latest" ]; then
XUI_VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | jq -r '.tag_name')
fi
if [ -z "$XUI_VERSION" ] || [ "$XUI_VERSION" = "null" ]; then
echo "[provision] ERROR: could not resolve 3x-ui release tag" >&2
exit 1
fi
echo "[provision] installing 3x-ui ${XUI_VERSION} (${XUI_ARCH})"
tarball="x-ui-linux-${XUI_ARCH}.tar.gz"
url="https://github.com/${REPO}/releases/download/${XUI_VERSION}/${tarball}"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
# Download the RELEASED binary tarball (no Go build inside the image).
curl -fL4 --retry 3 -o "${tmp}/${tarball}" "$url"
# Extract into /usr/local/ (the tarball contains an x-ui/ directory).
systemctl stop x-ui > /dev/null 2>&1 || true
rm -rf "$XUI_DIR"
tar -xzf "${tmp}/${tarball}" -C /usr/local/
chmod +x "${XUI_DIR}/x-ui" "${XUI_DIR}/x-ui.sh"
chmod +x "${XUI_DIR}"/bin/* 2> /dev/null || true
# Install the x-ui management CLI.
if [ -f "${XUI_DIR}/x-ui.sh" ]; then
cp -f "${XUI_DIR}/x-ui.sh" /usr/bin/x-ui
else
curl -fL4 -o /usr/bin/x-ui "https://raw.githubusercontent.com/${REPO}/main/x-ui.sh"
fi
chmod +x /usr/bin/x-ui
mkdir -p /var/log/x-ui
# Panel systemd unit (Ubuntu base => debian variant).
install -m 644 "${XUI_DIR}/x-ui.service.debian" /etc/systemd/system/x-ui.service
# First-boot per-instance credential unit + script (uploaded to /tmp/firstboot).
install -m 755 /tmp/firstboot/x-ui-firstboot.sh "${XUI_DIR}/x-ui-firstboot.sh"
install -m 644 /tmp/firstboot/x-ui-firstboot.service /etc/systemd/system/x-ui-firstboot.service
systemctl daemon-reload
# Enable (start on next boot) but do NOT start now — there is no DB yet.
systemctl enable x-ui-firstboot.service
systemctl enable x-ui.service
# Belt-and-braces: ensure no DB / sentinel was created during provisioning.
rm -f /etc/x-ui/x-ui.db /etc/x-ui/x-ui.db-* /etc/x-ui/.firstboot-done 2> /dev/null || true
echo "[provision] done — panel installed, services enabled, NO database initialized."
-109
View File
@@ -1,109 +0,0 @@
// Input variables for the 3x-ui golden-image build.
// See README.md for usage. Override with -var / -var-file or env (PKR_VAR_*).
variable "xui_version" {
type = string
description = "3x-ui release tag to install, e.g. v3.3.1. 'latest' resolves the newest GitHub release at build time."
default = "latest"
}
variable "xui_arch" {
type = string
description = "CPU architecture to build for: amd64 or arm64."
default = "amd64"
validation {
condition = contains(["amd64", "arm64"], var.xui_arch)
error_message = "The xui_arch value must be 'amd64' or 'arm64'."
}
}
variable "ubuntu_version" {
type = string
description = "Ubuntu LTS version label, used only for image naming/tags."
default = "24.04"
}
// --- amazon-ebs (AMI) ---------------------------------------------------------
variable "region" {
type = string
description = "AWS region the AMI is built in."
default = "eu-central-1"
}
variable "instance_type" {
type = string
description = "EC2 instance type used to build the AMI. Must match xui_arch (e.g. t3.small for amd64, t4g.small for arm64/Graviton)."
default = "t3.small"
}
variable "ami_name_prefix" {
type = string
description = "Prefix for the produced AMI name."
default = "3x-ui"
}
variable "source_ami_filter_name" {
type = string
description = "Override for the Canonical Ubuntu base AMI name filter. Empty ⇒ derived from xui_arch (latest patched 24.04 LTS for that arch)."
default = ""
}
variable "ssh_username" {
type = string
description = "Default SSH user on the base Ubuntu cloud image."
default = "ubuntu"
}
// --- qemu (qcow2 / raw) -------------------------------------------------------
variable "qemu_iso_url" {
type = string
description = "Override for the Ubuntu cloud image used as the qemu base disk. Empty ⇒ derived from xui_arch (amd64/arm64 cloud image)."
default = ""
}
variable "qemu_iso_checksum" {
type = string
description = "Checksum for the qemu base disk. 'file:<SHA256SUMS url>' auto-fetches; 'none' skips verification."
default = "file:https://cloud-images.ubuntu.com/releases/24.04/release/SHA256SUMS"
}
variable "qemu_accelerator" {
type = string
description = "QEMU accelerator: 'kvm' when /dev/kvm is available, else 'tcg' (slow software emulation)."
default = "kvm"
}
variable "qemu_headless" {
type = bool
description = "Run QEMU without a display (required on CI runners)."
default = true
}
variable "qemu_build_password" {
type = string
description = "Temporary password injected via cloud-init for Packer's build-time SSH. Locked/removed before the image is finalized."
default = "packer-build-temp-pw"
sensitive = true
}
# --- qemu arm64-only knobs (ignored for amd64) -------------------------------
variable "qemu_cpu" {
type = string
description = "QEMU -cpu model for arm64 builds: 'host' with KVM on an arm64 host, 'max' for TCG emulation."
default = "host"
}
variable "qemu_efi_code" {
type = string
description = "Path to the arm64 UEFI code firmware (AAVMF). Only used when xui_arch=arm64."
default = "/usr/share/AAVMF/AAVMF_CODE.fd"
}
variable "qemu_efi_vars" {
type = string
description = "Path to the arm64 UEFI vars firmware template (AAVMF). Only used when xui_arch=arm64."
default = "/usr/share/AAVMF/AAVMF_VARS.fd"
}
-160
View File
@@ -1,160 +0,0 @@
// 3x-ui golden image one build, two sources:
// * amazon-ebs : produces an AWS AMI (Marketplace-scannable)
// * qemu : produces a qcow2 (+ raw) for Hetzner/DO/Vultr/GCP/Azure/Oracle
//
// The image ships WITHOUT an initialized x-ui.db and WITHOUT any baked
// credentials. deploy/firstboot/x-ui-firstboot.{sh,service} generates unique
// per-instance credentials on first boot, before x-ui.service starts.
//
// Provisioner order is fixed: provision.sh -> harden.sh -> cleanup.sh.
packer {
required_plugins {
amazon = {
version = ">= 1.3.0"
source = "github.com/hashicorp/amazon"
}
qemu = {
version = ">= 1.1.0"
source = "github.com/hashicorp/qemu"
}
}
}
locals {
build_stamp = formatdate("YYYYMMDD-hhmmss", timestamp())
image_name = "${var.ami_name_prefix}-ubuntu-${var.ubuntu_version}-${var.xui_arch}"
is_arm = var.xui_arch == "arm64"
# Base images are derived from xui_arch unless explicitly overridden.
source_ami_name = var.source_ami_filter_name != "" ? var.source_ami_filter_name : "ubuntu/images/hvm-ssd-gp3/ubuntu-noble-24.04-${var.xui_arch}-server-*"
qemu_iso_url = var.qemu_iso_url != "" ? var.qemu_iso_url : "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-${var.xui_arch}.img"
}
source "amazon-ebs" "x-ui" {
region = var.region
instance_type = var.instance_type
ssh_username = var.ssh_username
ami_name = "${local.image_name}-${var.xui_version}-${local.build_stamp}"
ami_description = "3x-ui panel on Ubuntu ${var.ubuntu_version}. Per-instance credentials are generated on first boot."
source_ami_filter {
filters = {
name = local.source_ami_name
root-device-type = "ebs"
virtualization-type = "hvm"
}
owners = ["099720109477"] // Canonical
most_recent = true
}
launch_block_device_mappings {
device_name = "/dev/sda1"
volume_size = 8
volume_type = "gp3"
delete_on_termination = true
}
tags = {
Name = local.image_name
Project = "3x-ui"
XuiVersion = var.xui_version
BuildTool = "packer"
BaseOS = "ubuntu-${var.ubuntu_version}"
}
}
source "qemu" "x-ui" {
iso_url = local.qemu_iso_url
iso_checksum = var.qemu_iso_checksum
disk_image = true
disk_size = "10G"
format = "qcow2"
accelerator = var.qemu_accelerator
headless = var.qemu_headless
cpus = 2
memory = 2048
net_device = "virtio-net"
disk_interface = "virtio"
// Arch-specific QEMU machine. amd64 uses Packer defaults (BIOS boot, x86_64);
// arm64 needs the aarch64 binary, the 'virt' machine and UEFI (AAVMF) firmware.
qemu_binary = local.is_arm ? "qemu-system-aarch64" : null
machine_type = local.is_arm ? "virt" : null
efi_boot = local.is_arm
efi_firmware_code = local.is_arm ? var.qemu_efi_code : null
efi_firmware_vars = local.is_arm ? var.qemu_efi_vars : null
qemuargs = local.is_arm ? [["-cpu", var.qemu_cpu]] : []
output_directory = "output-qemu"
vm_name = "${local.image_name}.qcow2"
// Build-time access: a NoCloud seed sets a temporary password for the default
// user so Packer can SSH in. The seed is a separate CD-ROM (not part of the
// output disk); the password is locked by harden.sh and state wiped by cleanup.sh.
cd_label = "cidata"
cd_content = {
"meta-data" = ""
"user-data" = <<-EOT
#cloud-config
password: ${var.qemu_build_password}
chpasswd: { expire: false }
ssh_pwauth: true
EOT
}
ssh_username = var.ssh_username
ssh_password = var.qemu_build_password
ssh_timeout = "20m"
boot_wait = "45s"
shutdown_command = "sudo shutdown -P now"
}
build {
name = "3x-ui"
sources = ["source.amazon-ebs.x-ui", "source.qemu.x-ui"]
// Upload the first-boot unit + script so provision.sh can install them.
provisioner "shell" {
inline = ["mkdir -p /tmp/firstboot"]
}
provisioner "file" {
source = "${path.root}/../firstboot/x-ui-firstboot.sh"
destination = "/tmp/firstboot/x-ui-firstboot.sh"
}
provisioner "file" {
source = "${path.root}/../firstboot/x-ui-firstboot.service"
destination = "/tmp/firstboot/x-ui-firstboot.service"
}
provisioner "shell" {
environment_vars = [
"XUI_VERSION=${var.xui_version}",
"XUI_ARCH=${var.xui_arch}",
"DEBIAN_FRONTEND=noninteractive",
]
execute_command = "chmod +x {{ .Path }}; sudo -E bash {{ .Path }}"
scripts = [
"${path.root}/scripts/provision.sh",
"${path.root}/scripts/harden.sh",
"${path.root}/scripts/cleanup.sh",
]
// give cloud-init time to release apt locks on the very first boot
pause_before = "10s"
}
// Convert the qcow2 to raw for clouds that need it (qemu source only).
post-processor "shell-local" {
only = ["qemu.x-ui"]
inline = ["qemu-img convert -p -O raw output-qemu/${local.image_name}.qcow2 output-qemu/${local.image_name}.raw"]
}
// Record the AMI id / artifacts for CI to surface.
post-processor "manifest" {
output = "packer-manifest.json"
strip_path = true
}
}
-86
View File
@@ -1,86 +0,0 @@
#!/usr/bin/env bash
#
# smoke-firstboot.sh — verify the first-boot per-instance credential script.
#
# Installs the released x-ui binary into a container WITHOUT a database, runs
# x-ui-firstboot.sh, and asserts:
# * fresh random credentials are generated (no admin/admin)
# * /etc/x-ui/credentials.txt (600) and /etc/motd are written
# * the sentinel is created and a second run is a no-op (creds unchanged)
#
# Requires Docker and network access. Usage: bash deploy/test/smoke-firstboot.sh
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
IMAGE="${SMOKE_IMAGE:-ubuntu:24.04}"
if ! command -v docker > /dev/null 2>&1; then
echo "ERROR: docker is required for this smoke test." >&2
exit 1
fi
echo "== first-boot credential smoke test (image: $IMAGE) =="
docker run --rm \
-v "${REPO_ROOT}/deploy/firstboot/x-ui-firstboot.sh:/root/x-ui-firstboot.sh:ro" \
-e DEBIAN_FRONTEND=noninteractive \
"$IMAGE" bash -euo pipefail -c '
apt-get update -qq
apt-get install -y -qq curl tar openssl ca-certificates jq > /dev/null
echo "--- installing released x-ui binary (no DB, no systemd) ---"
REPO=MHSanaei/3x-ui
ARCH=$(dpkg --print-architecture) # amd64 | arm64
echo "container arch: $ARCH"
VER=$(curl --fail --location --silent --show-error \
--retry 5 --retry-all-errors --retry-delay 3 \
--connect-timeout 15 --max-time 60 \
"https://api.github.com/repos/${REPO}/releases/latest" | jq -r .tag_name)
[ -n "$VER" ] && [ "$VER" != "null" ] || { echo "FAIL: cannot resolve version"; exit 1; }
tmp=$(mktemp -d)
# 504s and other transient GitHub/CDN hiccups are retried; a real HTTP
# failure (e.g. missing arch asset) still aborts after the retries.
if ! curl -4 --fail --location --silent --show-error \
--retry 5 --retry-all-errors --retry-delay 3 \
--connect-timeout 15 --max-time 300 \
-o "${tmp}/x.tar.gz" \
"https://github.com/${REPO}/releases/download/${VER}/x-ui-linux-${ARCH}.tar.gz"; then
echo "FAIL: cannot download x-ui-linux-${ARCH}.tar.gz (${VER})" >&2; exit 1
fi
test -s "${tmp}/x.tar.gz" || { echo "FAIL: downloaded tarball is empty"; exit 1; }
tar -xzf "${tmp}/x.tar.gz" -C /usr/local/
chmod +x /usr/local/x-ui/x-ui
install -m 755 /root/x-ui-firstboot.sh /usr/local/x-ui/x-ui-firstboot.sh
# Guarantee a clean slate (the image must never ship a DB).
rm -f /etc/x-ui/x-ui.db /etc/x-ui/.firstboot-done
echo "--- run 1: generate per-instance credentials ---"
/usr/local/x-ui/x-ui-firstboot.sh
test -f /etc/x-ui/.firstboot-done || { echo "FAIL: sentinel not created"; exit 1; }
test -f /etc/x-ui/credentials.txt || { echo "FAIL: credentials.txt missing"; exit 1; }
perms=$(stat -c %a /etc/x-ui/credentials.txt)
[ "$perms" = "600" ] || { echo "FAIL: credentials.txt perms=$perms (want 600)"; exit 1; }
grep -q "3x-ui" /etc/motd || { echo "FAIL: motd not written"; exit 1; }
# shellcheck disable=SC1090
. /etc/x-ui/credentials.txt
[ -n "${XUI_USERNAME:-}" ] && [ "$XUI_USERNAME" != "admin" ] \
|| { echo "FAIL: username missing or still admin"; exit 1; }
first_user="$XUI_USERNAME"
/usr/local/x-ui/x-ui setting -show | grep -q "hasDefaultCredential: false" \
|| { echo "FAIL: hasDefaultCredential is not false"; exit 1; }
echo "--- run 2: must be a no-op (sentinel honored) ---"
/usr/local/x-ui/x-ui-firstboot.sh
# shellcheck disable=SC1090
. /etc/x-ui/credentials.txt
[ "$XUI_USERNAME" = "$first_user" ] \
|| { echo "FAIL: credentials changed on re-run"; exit 1; }
echo "SMOKE_PASS: firstboot user=$first_user (stable across re-run)"
'
echo "== first-boot smoke test PASSED =="
+8 -4
View File
@@ -5,8 +5,8 @@ services:
dockerfile: ./Dockerfile
container_name: 3xui_app
# hostname: yourhostname <- optional
# Optional hard memory cap. When set, the panel auto-derives its Go soft
# limit (GOMEMLIMIT, ~90%) from this so it GCs before the OOM killer fires.
# Optional hard memory cap. When set, the panel derives its Go soft limit
# (GOMEMLIMIT, ~90% of this cap) so it GCs before the OOM killer fires.
# mem_limit: 512m
# The bundled Fail2ban (XUI_ENABLE_FAIL2BAN below) enforces the IP limit
# with iptables, which needs NET_ADMIN. Without these caps a ban is logged
@@ -21,8 +21,12 @@ services:
environment:
XRAY_VMESS_AEAD_FORCED: "false"
XUI_ENABLE_FAIL2BAN: "true"
# Go memory soft limit. If neither is set, the panel auto-detects the
# cgroup/host limit and targets ~90%. Pin it explicitly with one of:
# Memory tuning. The panel keeps RAM low via GOGC + periodic release; it no
# longer sets a soft limit from total host RAM (no benefit, risks GC thrash).
# XUI_GOGC: "75" # lower = less RAM, slightly more CPU; GOGC env overrides
# XUI_MEMORY_RELEASE_INTERVAL: "10" # minutes between FreeOSMemory; 0 disables
# Go memory soft limit, only applied from an explicit budget below (or a
# real cgroup/mem_limit cap). Pin it with one of:
# XUI_MEMORY_LIMIT: "400" # in MiB
# GOMEMLIMIT: "400MiB" # Go syntax, takes precedence
# XUI_PPROF: "true" # expose pprof on 127.0.0.1:6060 for profiling
+60
View File
@@ -0,0 +1,60 @@
# frontend/CLAUDE.md
Frontend agent guide. Full detail: `frontend/README.md` and the root
`CONTRIBUTING.md` ("Working on the frontend"). This is the short version.
## What this is
React 19 + Ant Design 6 + Vite 8 + TypeScript. The Vite config is
`vite.config.js` (plain JS). Three bundles, each emitted into
`internal/web/dist/` and embedded into the Go binary:
- `index.html` — admin panel SPA (entry `src/main.tsx`; react-router under
`/panel`, lazy routes).
- `login.html` — login + 2FA (`src/entries/login.tsx`).
- `subpage.html` — public subscription viewer (`src/entries/subpage.tsx`).
The `@` import alias maps to `src/`.
## Data flow
- Server state via TanStack Query (`src/api/`, keys in `src/api/queryKeys.ts`);
invalidate on mutation. WebSocket pushes feed the cache
(`src/api/websocketBridge.ts`).
- Local UI state in the page (`useState`); shared concerns via `src/hooks/`.
Extend an existing hook before adding a global.
- Zod (`src/schemas/`) is the single source of truth for the xray config model.
Infer types with `z.infer`. Go-side types are mirrored into `src/generated/`
by `npm run gen:zod` (`go run ./tools/openapigen`) — do not hand-edit that
folder (every file is marked `DO NOT EDIT`).
- xray domain logic (links, defaults, form<->wire adapters) is pure functions in
`src/lib/xray/`. HTTP goes through `HttpUtil` in `src/utils/index.ts`.
## Rules
- Ant Design 6 only; no Tailwind/shadcn (a migration was rolled back).
- Function components + hooks only; no class components.
- No `//` line comments in committed TS/TSX. HTML comments are fine.
- TS strict; `no-explicit-any` is an error. Validate form fields with
`antdRule(Schema.shape.field, t)` from `@/utils/zodForm`, not inline
`z.string()`.
- New `g.POST`/`g.GET` route => add it to `src/pages/api-docs/endpoints.ts`,
then `npm run gen`.
- i18n strings live in `internal/web/translation/<locale>.json`, NOT under
`frontend/`, and are shared with the Go backend. A new English key must be
added to every locale. Interpolation here uses single braces `{var}`, not the
i18next default `{{var}}`.
- Persian/Arabic (RTL) users are first-class — isolate code identifiers on their
own line when writing Persian text in labels/toasts.
- Vite is pinned to an exact version (no `^`) — bump deliberately, then verify
`npm run dev` AND `npm run build`.
## Adding a panel route
1. `src/pages/<page>/<Page>.tsx` (kebab folder, PascalCase component).
2. Register in `src/routes.tsx` under `/panel` (lazy import).
3. Add a sidebar link in `src/layouts/AppSidebar.tsx` if it needs nav.
Only standalone bundles (login/subpage) need a new `.html` + `src/entries/*` +
`rollupOptions.input` (in `vite.config.js`) + a Go controller route.
## Commands
- `npm run dev` (HMR on :5173, proxies to the Go panel on :2053 — start Go first).
- `npm run typecheck` / `npm run lint` / `npm run test` / `npm run build`.
- `npm run gen` = `gen:zod` (Go → `src/generated/`) + `gen:api`
(`build-openapi.mjs``public/openapi.json`).
- After `npm run build`, RESTART `go run .` (see the XUI_DEBUG gotcha in root
CLAUDE.md) before checking the panel.
+1 -1
View File
@@ -100,7 +100,7 @@ frontend/
├── generated/ # Code-generated zod + ts types from Go
│ # (DO NOT hand-edit — regenerated by gen:zod)
├── models/ # Thin legacy types still in transit
│ # (DBInbound, Status, AllSetting, reality-targets)
│ # (DBInbound, Status, AllSetting)
├── styles/ # Shared CSS modules
├── test/ # Vitest specs + golden fixtures
│ ├── *.test.ts
+9
View File
@@ -1,6 +1,7 @@
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import reactHooks from 'eslint-plugin-react-hooks';
import jsxA11y from 'eslint-plugin-jsx-a11y';
import globals from 'globals';
export default [
@@ -44,4 +45,12 @@ export default [
'react-hooks/refs': 'off',
},
},
{
files: ['**/*.tsx'],
plugins: { 'jsx-a11y': jsxA11y },
rules: {
...jsxA11y.flatConfigs.recommended.rules,
'jsx-a11y/no-autofocus': 'off',
},
},
];
+1851 -482
View File
File diff suppressed because it is too large Load Diff
+12 -8
View File
@@ -1,7 +1,7 @@
{
"name": "3x-ui-frontend",
"private": true,
"version": "0.4.0",
"version": "0.4.1",
"type": "module",
"description": "3x-ui panel frontend (React 19 + Ant Design 6 + Vite 8).",
"engines": {
@@ -21,19 +21,19 @@
"gen:zod": "cd .. && go run ./tools/openapigen"
},
"dependencies": {
"@ant-design/icons": "^6.2.5",
"@ant-design/icons": "^6.3.2",
"@codemirror/lang-json": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.3",
"@tanstack/react-query": "^5.101.1",
"@tanstack/react-query-devtools": "^5.101.1",
"antd": "^6.4.5",
"@tanstack/react-query": "^5.101.2",
"@tanstack/react-query-devtools": "^5.101.2",
"antd": "^6.5.0",
"axios": "^1.18.1",
"codemirror": "^6.0.2",
"dayjs": "^1.11.21",
"i18next": "^26.3.1",
"i18next": "^26.3.3",
"otpauth": "^9.5.1",
"persian-calendar-suite": "^1.5.5",
"qs": "^6.15.2",
"qs": "^6.15.3",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-i18next": "^17.0.8",
@@ -51,7 +51,8 @@
"@types/swagger-ui-react": "^5.18.0",
"@vitejs/plugin-react": "^6.0.3",
"@vitest/coverage-v8": "^4.1.9",
"eslint": "^10.5.0",
"eslint": "^10.6.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react-hooks": "^7.1.1",
"globals": "^17.7.0",
"jsdom": "^29.1.1",
@@ -61,6 +62,9 @@
"vitest": "^4.1.9"
},
"overrides": {
"eslint-plugin-jsx-a11y": {
"eslint": "$eslint"
},
"dompurify": "^3.4.11",
"react-copy-to-clipboard": "^5.1.1",
"react-inspector": "^9.0.0",
+571 -11
View File
@@ -84,6 +84,9 @@
"ldapInboundTags": {
"type": "string"
},
"ldapInsecureSkipVerify": {
"type": "boolean"
},
"ldapInvertFlag": {
"type": "boolean"
},
@@ -232,6 +235,14 @@
"description": "Hide server settings in happ subscription (Only for Happ)",
"type": "boolean"
},
"subIncyEnableRouting": {
"description": "Enable routing injection for the Incy client",
"type": "boolean"
},
"subIncyRoutingRules": {
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
"type": "string"
},
"subJsonEnable": {
"description": "Enable JSON subscription endpoint",
"type": "boolean"
@@ -421,6 +432,7 @@
"ldapFlagField",
"ldapHost",
"ldapInboundTags",
"ldapInsecureSkipVerify",
"ldapInvertFlag",
"ldapPassword",
"ldapPort",
@@ -457,6 +469,8 @@
"subEnableRouting",
"subEncrypt",
"subHideSettings",
"subIncyEnableRouting",
"subIncyRoutingRules",
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
@@ -579,6 +593,9 @@
"ldapInboundTags": {
"type": "string"
},
"ldapInsecureSkipVerify": {
"type": "boolean"
},
"ldapInvertFlag": {
"type": "boolean"
},
@@ -727,6 +744,14 @@
"description": "Hide server settings in happ subscription (Only for Happ)",
"type": "boolean"
},
"subIncyEnableRouting": {
"description": "Enable routing injection for the Incy client",
"type": "boolean"
},
"subIncyRoutingRules": {
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
"type": "string"
},
"subJsonEnable": {
"description": "Enable JSON subscription endpoint",
"type": "boolean"
@@ -923,6 +948,7 @@
"ldapFlagField",
"ldapHost",
"ldapInboundTags",
"ldapInsecureSkipVerify",
"ldapInvertFlag",
"ldapPassword",
"ldapPort",
@@ -959,6 +985,8 @@
"subEnableRouting",
"subEncrypt",
"subHideSettings",
"subIncyEnableRouting",
"subIncyRoutingRules",
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
@@ -1064,6 +1092,12 @@
"Client": {
"description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.",
"properties": {
"allowedIPs": {
"items": {
"type": "string"
},
"type": "array"
},
"auth": {
"description": "Auth password (Hysteria)",
"type": "string"
@@ -1100,6 +1134,9 @@
"description": "Unique client identifier",
"type": "string"
},
"keepAlive": {
"type": "integer"
},
"limitIp": {
"description": "IP limit for this client",
"type": "integer"
@@ -1108,6 +1145,15 @@
"description": "Client password",
"type": "string"
},
"preSharedKey": {
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"reset": {
"description": "Reset period in days",
"type": "integer"
@@ -1181,6 +1227,9 @@
},
"ClientRecord": {
"properties": {
"allowedIPs": {
"type": "string"
},
"auth": {
"type": "string"
},
@@ -1208,12 +1257,24 @@
"id": {
"type": "integer"
},
"keepAlive": {
"type": "integer"
},
"limitIp": {
"type": "integer"
},
"password": {
"type": "string"
},
"preSharedKey": {
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"reset": {
"type": "integer"
},
@@ -1238,6 +1299,7 @@
}
},
"required": [
"allowedIPs",
"auth",
"comment",
"createdAt",
@@ -1247,8 +1309,12 @@
"flow",
"group",
"id",
"keepAlive",
"limitIp",
"password",
"preSharedKey",
"privateKey",
"publicKey",
"reset",
"reverse",
"security",
@@ -1505,7 +1571,8 @@
"type": "string"
},
"vlessRoute": {
"description": "VlessRoute is a free-form port/range routing spec (e.g. \"53,443,1000-2000\");\nstored verbatim, format-validated on the frontend.",
"description": "Single VLESS route value (0-65535) baked into the subscription UUID's 3rd\ngroup (bytes 6-7), which xray reads via net.PortFromBytes(id[6:8]). Empty = none.",
"example": "443",
"type": "string"
}
},
@@ -1788,6 +1855,15 @@
"tlsFlowCapable": {
"example": true,
"type": "boolean"
},
"wgDns": {
"type": "string"
},
"wgMtu": {
"type": "integer"
},
"wgPublicKey": {
"type": "string"
}
},
"required": [
@@ -2126,6 +2202,104 @@
],
"type": "object"
},
"RealityScanResult": {
"properties": {
"alpn": {
"example": "h2",
"type": "string"
},
"certIssuer": {
"example": "Google Trust Services",
"type": "string"
},
"certSubject": {
"example": "cloudflare.com",
"type": "string"
},
"certValid": {
"example": true,
"type": "boolean"
},
"curveID": {
"example": "X25519",
"type": "string"
},
"feasible": {
"example": true,
"type": "boolean"
},
"h2": {
"example": true,
"type": "boolean"
},
"host": {
"example": "www.cloudflare.com",
"type": "string"
},
"ip": {
"example": "104.16.124.96",
"type": "string"
},
"latencyMs": {
"example": 180,
"type": "integer"
},
"notAfter": {
"example": "2026-08-01T00:00:00Z",
"type": "string"
},
"port": {
"example": 443,
"type": "integer"
},
"reason": {
"type": "string"
},
"serverNames": {
"items": {
"type": "string"
},
"type": "array"
},
"target": {
"example": "www.cloudflare.com:443",
"type": "string"
},
"tls13": {
"example": true,
"type": "boolean"
},
"tlsVersion": {
"example": "1.3",
"type": "string"
},
"x25519": {
"example": true,
"type": "boolean"
}
},
"required": [
"alpn",
"certIssuer",
"certSubject",
"certValid",
"curveID",
"feasible",
"h2",
"host",
"ip",
"latencyMs",
"notAfter",
"port",
"reason",
"serverNames",
"target",
"tls13",
"tlsVersion",
"x25519"
],
"type": "object"
},
"Setting": {
"description": "Setting stores key-value configuration settings for the 3x-ui panel.",
"properties": {
@@ -2587,7 +2761,10 @@
"remark": "VLESS-443",
"ssMethod": "",
"tag": "in-443-tcp",
"tlsFlowCapable": true
"tlsFlowCapable": true,
"wgDns": "",
"wgMtu": 0,
"wgPublicKey": ""
}
]
}
@@ -2597,6 +2774,43 @@
}
}
},
"/panel/api/inbounds/allLinks": {
"get": {
"tags": [
"Inbounds"
],
"summary": "Return every protocol URL (vless://, vmess://, trojan://, ss://, hysteria://, mtproto) across all inbounds and all of their clients. Links are rendered through the subscription engine, so the configured remark template (name-only display part) is applied per client — the same output the client info/QR pages use. Protocols without a URL form (socks, http, mixed, wireguard, dokodemo, tunnel) contribute nothing. Used by the panels \"Export all inbound links\" action.",
"operationId": "get_panel_api_inbounds_allLinks",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": [
"vless://uuid@host:443?security=reality&...#Germany-alice",
"vmess://eyJ2IjoyLC..."
]
}
}
}
}
}
}
},
"/panel/api/inbounds/get/{id}": {
"get": {
"tags": [
@@ -4220,6 +4434,46 @@
}
}
},
"/panel/api/server/setUpdateChannel": {
"post": {
"tags": [
"Server"
],
"summary": "Toggle the panel update channel between stable and the rolling per-commit dev release. Only effective on dev builds.",
"operationId": "post_panel_api_server_setUpdateChannel",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/server/updateGeofile": {
"post": {
"tags": [
@@ -4577,6 +4831,145 @@
}
}
},
"/panel/api/server/scanRealityTarget": {
"post": {
"tags": [
"Server"
],
"summary": "Run a live TLS 1.3 probe against a candidate REALITY target and return a feasibility verdict (TLS 1.3 + h2 + X25519 + trusted certificate) plus the certificate SAN DNS names.",
"operationId": "post_panel_api_server_scanRealityTarget",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/RealityScanResult"
}
}
},
"example": {
"success": true,
"obj": {
"alpn": "h2",
"certIssuer": "Google Trust Services",
"certSubject": "cloudflare.com",
"certValid": true,
"curveID": "X25519",
"feasible": true,
"h2": true,
"host": "www.cloudflare.com",
"ip": "104.16.124.96",
"latencyMs": 180,
"notAfter": "2026-08-01T00:00:00Z",
"port": 443,
"reason": "",
"serverNames": [
""
],
"target": "www.cloudflare.com:443",
"tls13": true,
"tlsVersion": "1.3",
"x25519": true
}
}
}
}
}
}
}
},
"/panel/api/server/scanRealityTargets": {
"post": {
"tags": [
"Server"
],
"summary": "Probe/discover REALITY targets and return each verdict ranked by feasibility then latency. Each comma-separated token may be a domain (validated with SNI), a bare IP, or a CIDR range (discovered without SNI by reading the certificate domain). When empty, a built-in seed list is probed.",
"operationId": "post_panel_api_server_scanRealityTargets",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"type": "array",
"items": {
"$ref": "#/components/schemas/RealityScanResult"
}
}
}
},
"example": {
"success": true,
"obj": [
{
"alpn": "h2",
"certIssuer": "Google Trust Services",
"certSubject": "cloudflare.com",
"certValid": true,
"curveID": "X25519",
"feasible": true,
"h2": true,
"host": "www.cloudflare.com",
"ip": "104.16.124.96",
"latencyMs": 180,
"notAfter": "2026-08-01T00:00:00Z",
"port": 443,
"reason": "",
"serverNames": [
""
],
"target": "www.cloudflare.com:443",
"tls13": true,
"tlsVersion": "1.3",
"x25519": true
}
]
}
}
}
}
}
}
},
"/panel/api/server/clientIps": {
"get": {
"tags": [
@@ -5456,7 +5849,7 @@
"tags": [
"Clients"
],
"summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. Returns the adjusted count and per-email skip reasons.",
"summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). Returns the adjusted count and per-email skip reasons.",
"operationId": "post_panel_api_clients_bulkAdjust",
"requestBody": {
"required": true,
@@ -5471,7 +5864,8 @@
"bob"
],
"addDays": 30,
"addBytes": 53687091200
"addBytes": 53687091200,
"flow": "xtls-rprx-vision"
}
}
}
@@ -5511,6 +5905,122 @@
}
}
},
"/panel/api/clients/bulkEnable": {
"post": {
"tags": [
"Clients"
],
"summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.",
"operationId": "post_panel_api_clients_bulkEnable",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
},
"example": {
"emails": [
"alice",
"bob"
]
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": {
"changed": 2,
"skipped": [
{
"email": "carol",
"reason": "client not found"
}
]
}
}
}
}
}
}
}
},
"/panel/api/clients/bulkDisable": {
"post": {
"tags": [
"Clients"
],
"summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.",
"operationId": "post_panel_api_clients_bulkDisable",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
},
"example": {
"emails": [
"alice",
"bob"
]
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": {
"changed": 2,
"skipped": [
{
"email": "carol",
"reason": "client not found"
}
]
}
}
}
}
}
}
}
},
"/panel/api/clients/bulkDel": {
"post": {
"tags": [
@@ -6168,6 +6678,55 @@
}
}
},
"/panel/api/clients/groups/resetTraffic": {
"post": {
"tags": [
"Clients"
],
"summary": "Reset only the group-level traffic counter shown on the groups page. Snapshots the current up/down sum of the group's members as a baseline so the group total reads zero, while leaving each client's own counters (and their quotas) untouched. No Xray restart is triggered. Creates the client_groups row if the group exists only as a derived label.",
"operationId": "post_panel_api_clients_groups_resetTraffic",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
},
"example": {
"name": "customer-a"
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": {
"name": "customer-a"
}
}
}
}
}
}
}
},
"/panel/api/clients/resetTraffic/{email}": {
"post": {
"tags": [
@@ -7379,7 +7938,7 @@
"tags": [
"Nodes"
],
"summary": "Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Returns a per-node result list.",
"summary": "Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Set \"dev\": true to move the nodes to the rolling per-commit dev channel instead of the latest stable release. Returns a per-node result list.",
"operationId": "post_panel_api_nodes_updatePanel",
"requestBody": {
"required": true,
@@ -7393,7 +7952,8 @@
1,
2,
3
]
],
"dev": false
}
}
}
@@ -7571,7 +8131,7 @@
],
"updatedAt": 0,
"verifyPeerCertByName": "",
"vlessRoute": ""
"vlessRoute": "443"
}
]
}
@@ -7663,7 +8223,7 @@
],
"updatedAt": 0,
"verifyPeerCertByName": "",
"vlessRoute": ""
"vlessRoute": "443"
}
}
}
@@ -7758,7 +8318,7 @@
],
"updatedAt": 0,
"verifyPeerCertByName": "",
"vlessRoute": ""
"vlessRoute": "443"
}
]
}
@@ -7898,7 +8458,7 @@
],
"updatedAt": 0,
"verifyPeerCertByName": "",
"vlessRoute": ""
"vlessRoute": "443"
}
}
}
@@ -8010,7 +8570,7 @@
],
"updatedAt": 0,
"verifyPeerCertByName": "",
"vlessRoute": ""
"vlessRoute": "443"
}
}
}
+9 -4
View File
@@ -7,6 +7,8 @@ import { AllSetting } from '@/models/setting';
import { AllSettingSchema, type AllSettingInput } from '@/schemas/setting';
import { keys } from '@/api/queryKeys';
type SettingSavePayload = Partial<AllSetting> & Record<string, unknown>;
async function fetchAllSetting(): Promise<AllSettingInput | null> {
const msg = await HttpUtil.post('/panel/api/setting/all', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch settings');
@@ -42,19 +44,21 @@ export function useAllSettings() {
}, []);
const saveMut = useMutation({
mutationFn: async (next: AllSetting): Promise<Msg<unknown>> => {
const body = AllSettingSchema.partial().safeParse(next);
mutationFn: async (next: SettingSavePayload): Promise<Msg<unknown>> => {
const payload = { ...next };
const body = AllSettingSchema.partial().safeParse(payload);
if (!body.success) {
console.warn('[zod] setting/update body failed validation', body.error.issues);
}
return HttpUtil.post('/panel/api/setting/update', body.success ? body.data : next);
return HttpUtil.post('/panel/api/setting/update', body.success ? { ...payload, ...body.data } : payload);
},
onSuccess: (msg) => {
if (msg?.success) queryClient.invalidateQueries({ queryKey: keys.settings.all() });
},
});
const saveAll = useCallback(() => saveMut.mutateAsync(draft), [saveMut, draft]);
const saveAll = useCallback(() => saveMut.mutateAsync({ ...draft }), [saveMut, draft]);
const savePayload = useCallback((payload: SettingSavePayload) => saveMut.mutateAsync(payload), [saveMut]);
const saveDisabled = useMemo(() => server.equals(draft), [server, draft]);
return {
@@ -65,5 +69,6 @@ export function useAllSettings() {
setSpinning: setExtraSpinning,
saveDisabled,
saveAll,
savePayload,
};
}
+3 -3
View File
@@ -59,8 +59,8 @@ export function useNodeMutations() {
});
const updatePanelsMut = useMutation({
mutationFn: (ids: number[]) =>
HttpUtil.post<NodeUpdateResult[]>('/panel/api/nodes/updatePanel', { ids }, {
mutationFn: ({ ids, dev }: { ids: number[]; dev: boolean }) =>
HttpUtil.post<NodeUpdateResult[]>('/panel/api/nodes/updatePanel', { ids, dev }, {
headers: { 'Content-Type': 'application/json' },
}),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
@@ -72,7 +72,7 @@ export function useNodeMutations() {
remove: (id: number) => removeMut.mutateAsync(id),
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
probe: (id: number) => probeMut.mutateAsync(id),
updatePanels: (ids: number[]): Promise<Msg<NodeUpdateResult[]>> => updatePanelsMut.mutateAsync(ids),
updatePanels: (ids: number[], dev: boolean): Promise<Msg<NodeUpdateResult[]>> => updatePanelsMut.mutateAsync({ ids, dev }),
testConnection: async (payload: Partial<NodeRecord>): Promise<Msg<ProbeResult>> => {
const raw = await HttpUtil.post('/panel/api/nodes/test', payload);
return parseMsg(raw, ProbeResultSchema, 'nodes/test');
@@ -0,0 +1,40 @@
.config-block {
margin-bottom: 10px;
}
.config-block .ant-collapse-header {
align-items: center !important;
padding: 8px 12px !important;
}
.config-block .ant-collapse-header-text {
flex: 1;
min-width: 0;
}
.config-block .ant-collapse-extra {
display: flex;
align-items: center;
}
.config-block-actions {
display: flex;
align-items: center;
gap: 4px;
}
.config-block .ant-collapse-content-box {
padding: 8px !important;
}
.config-block-text {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 11px;
word-break: break-all;
white-space: pre-wrap;
padding: 6px 8px;
background: var(--ant-color-fill-tertiary);
border-radius: 4px;
user-select: all;
}
@@ -0,0 +1,81 @@
import type { MouseEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Collapse, Popover, Tag, Tooltip, message } from 'antd';
import { CopyOutlined, DownloadOutlined, QrcodeOutlined } from '@ant-design/icons';
import { ClipboardManager, FileManager } from '@/utils';
import { QrPanel } from '@/pages/inbounds/qr';
import './ConfigBlock.css';
interface ConfigBlockProps {
label: string;
text: string;
fileName: string;
qrRemark?: string;
showQr?: boolean;
tagColor?: string;
defaultOpen?: boolean;
}
export default function ConfigBlock({
label,
text,
fileName,
qrRemark = '',
showQr = true,
tagColor = 'gold',
defaultOpen = false,
}: ConfigBlockProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
async function copy() {
const ok = await ClipboardManager.copyText(text);
if (ok) messageApi.success(t('copied'));
}
const actions = (
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
<div className="config-block-actions" onClick={(e: MouseEvent) => e.stopPropagation()}>
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} aria-label={t('copy')} onClick={copy} />
</Tooltip>
<Tooltip title={t('download')}>
<Button
size="small"
icon={<DownloadOutlined />}
aria-label={t('download')}
onClick={() => FileManager.downloadTextFile(text, fileName)}
/>
</Tooltip>
{showQr && (
<Popover
trigger="click"
placement="left"
destroyOnHidden
content={<QrPanel value={text} remark={qrRemark || label} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} />
</Tooltip>
</Popover>
)}
</div>
);
return (
<>
{messageContextHolder}
<Collapse
className="config-block"
defaultActiveKey={defaultOpen ? ['cfg'] : []}
items={[{
key: 'cfg',
label: <Tag color={tagColor} style={{ margin: 0, fontWeight: 600, letterSpacing: '0.3px' }}>{label}</Tag>,
extra: actions,
children: <code className="config-block-text">{text}</code>,
}]}
/>
</>
);
}
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { CloseCircleFilled } from '@ant-design/icons';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';
@@ -53,6 +54,7 @@ export default function DateTimePicker({
placeholder = '',
disabled = false,
}: DateTimePickerProps) {
const { t } = useTranslation();
const { datepicker } = useDatepicker();
const { isDark, isUltra } = useTheme();
const jalaliRef = useRef<HTMLDivElement>(null);
@@ -100,7 +102,7 @@ export default function DateTimePicker({
<button
type="button"
className="jdp-clear"
aria-label="clear"
aria-label={t('clear')}
onMouseDown={(e) => e.preventDefault()}
onClick={(e) => {
e.stopPropagation();
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Input, Space } from 'antd';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons';
@@ -74,6 +75,7 @@ function rowsToMap(rows: HeaderRow[], mode: HeaderMapMode): Record<string, strin
}
export default function HeaderMapEditor({ mode, value, onChange }: HeaderMapEditorProps) {
const { t } = useTranslation();
// Local state holds rows including blanks. Without it, addRow() would
// append a {name:'', value:''} that rowsToMap immediately filters out
// before reaching the form, so the new row would never reach UI. The
@@ -130,7 +132,7 @@ export default function HeaderMapEditor({ mode, value, onChange }: HeaderMapEdit
placeholder="Value"
onChange={(e) => setRow(idx, { value: e.target.value })}
/>
<Button icon={<MinusOutlined />} onClick={() => removeRow(idx)} />
<Button aria-label={t('remove')} icon={<MinusOutlined />} onClick={() => removeRow(idx)} />
</Space.Compact>
))}
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={addRow}>
+3 -1
View File
@@ -1,4 +1,5 @@
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { EditorView, basicSetup } from 'codemirror';
import { EditorState, Compartment } from '@codemirror/state';
import { json, jsonParseLinter } from '@codemirror/lang-json';
@@ -92,6 +93,7 @@ const JsonEditor = forwardRef<JsonEditorHandle, JsonEditorProps>(function JsonEd
const onChangeRef = useRef(onChange);
const valueRef = useRef(value);
const { isDark, isUltra } = useTheme();
const { t } = useTranslation();
useEffect(() => {
onChangeRef.current = onChange;
@@ -173,7 +175,7 @@ const JsonEditor = forwardRef<JsonEditorHandle, JsonEditorProps>(function JsonEd
});
}, [readOnly]);
return <div ref={hostRef} className="json-editor-host" />;
return <div ref={hostRef} className="json-editor-host" aria-label={t('jsonEditor')} />;
});
export default JsonEditor;
@@ -47,7 +47,7 @@ export default function RemarkTemplateField({ value = '', onChange, maxLength, p
maxLength={maxLength}
placeholder={placeholder}
onChange={(e) => onChange?.(e.target.value)}
addonAfter={
suffix={
<Popover
content={<RemarkVarPicker onPick={insertToken} />}
trigger="click"
@@ -55,7 +55,7 @@ export default function RemarkTemplateField({ value = '', onChange, maxLength, p
title={t('pages.hosts.remarkVars.title')}
>
<Tooltip title={t('pages.hosts.remarkVars.title')}>
<Button type="text" size="small" icon={<CodeOutlined />} style={{ margin: '0 -7px' }} />
<Button type="text" size="small" icon={<CodeOutlined />} aria-label={t('pages.hosts.remarkVars.title')} style={{ marginInlineEnd: -7 }} />
</Tooltip>
</Popover>
}
@@ -2,6 +2,7 @@ import { Tag, Tooltip, Typography } from 'antd';
import { useTranslation } from 'react-i18next';
import { REMARK_VARIABLES, REMARK_VAR_GROUPS, wrapToken } from '@/lib/remark/remarkVariables';
import { activateOnKey } from '@/utils/a11y';
interface RemarkVarPickerProps {
/** Called with the bare token (e.g. "EMAIL") when a chip is clicked. */
@@ -28,7 +29,10 @@ export default function RemarkVarPicker({ onPick }: RemarkVarPickerProps) {
{REMARK_VARIABLES.filter((v) => v.group === group).map((v) => (
<Tooltip key={v.token} title={t(`pages.hosts.remarkVars.desc${v.token}`)}>
<Tag
role="button"
tabIndex={0}
onClick={() => onPick(v.token)}
onKeyDown={activateOnKey(() => onPick(v.token))}
style={{ cursor: 'pointer', margin: 0, fontFamily: 'monospace' }}
>
{wrapToken(v.token)}
+7 -1
View File
@@ -1,4 +1,5 @@
import type { CSSProperties, ReactNode } from 'react';
import { activateOnKey } from '@/utils/a11y';
import './InputAddon.css';
interface InputAddonProps {
@@ -6,14 +7,19 @@ interface InputAddonProps {
className?: string;
style?: CSSProperties;
onClick?: () => void;
ariaLabel?: string;
}
export default function InputAddon({ children, className = '', style, onClick }: InputAddonProps) {
export default function InputAddon({ children, className = '', style, onClick, ariaLabel }: InputAddonProps) {
return (
<span
className={`input-addon ${className}`.trim()}
style={style}
onClick={onClick}
role={onClick ? 'button' : undefined}
tabIndex={onClick ? 0 : undefined}
aria-label={onClick ? ariaLabel : undefined}
onKeyDown={onClick ? activateOnKey(onClick) : undefined}
>
{children}
</span>
@@ -1,4 +1,4 @@
import type { ReactNode } from 'react';
import { cloneElement, Fragment, isValidElement, useId, type ReactElement, type ReactNode } from 'react';
import { Col, Row } from 'antd';
import './SettingListItem.css';
@@ -18,17 +18,22 @@ export default function SettingListItem({
control,
}: SettingListItemProps) {
const padding = paddings === 'small' ? '10px 20px' : '20px';
const titleId = useId();
const node = control ?? children;
const labelledNode = title && isValidElement(node) && node.type !== Fragment
? cloneElement(node as ReactElement<{ 'aria-labelledby'?: string }>, { 'aria-labelledby': titleId })
: node;
return (
<div className="setting-list-item" style={{ padding }}>
<Row gutter={[8, 16]} style={{ width: '100%' }}>
<Col xs={24} lg={12}>
<div className="setting-list-meta">
{title && <div className="setting-list-title">{title}</div>}
{title && <div className="setting-list-title" id={titleId}>{title}</div>}
{description && <div className="setting-list-description">{description}</div>}
</div>
</Col>
<Col xs={24} lg={12}>
{control ?? children}
{labelledNode}
</Col>
</Row>
</div>
@@ -12,7 +12,7 @@ export function NotificationCard({ icon, title, extra, children }: Props) {
return (
<Card
size="small"
bordered
variant="outlined"
title={<span>{icon} {title}</span>}
extra={extra}
style={{ borderWidth: 1 }}
@@ -40,7 +40,7 @@ export function NotificationGroup({ config, selected, onToggle, onToggleAll, all
/>
}
>
<Space direction="vertical" size={8} style={{ width: '100%' }}>
<Space orientation="vertical" size={8} style={{ width: '100%' }}>
{config.events.map((event) => (
<NotificationEvent
key={event.key}
@@ -1,4 +1,5 @@
import { useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Tag } from 'antd';
interface Props {
@@ -10,11 +11,12 @@ interface Props {
}
function MasterCheckbox({ checked, indeterminate, onChange }: { checked: boolean; indeterminate: boolean; onChange: () => void }) {
const { t } = useTranslation();
const ref = useRef<HTMLInputElement>(null);
useEffect(() => {
if (ref.current) ref.current.indeterminate = indeterminate;
}, [indeterminate]);
return <input ref={ref} type="checkbox" checked={checked} onChange={onChange} style={{ cursor: 'pointer' }} />;
return <input ref={ref} type="checkbox" aria-label={t('pages.clients.selectAll')} checked={checked} onChange={onChange} style={{ cursor: 'pointer' }} />;
}
export function NotificationHeader({ count, total, allSelected, indeterminate, onToggleAll }: Props) {
+11 -1
View File
@@ -181,8 +181,18 @@ export default function Sparkline({
const minColor = extrema?.minColor ?? DEFAULT_MIN_COLOR;
const maxColor = extrema?.maxColor ?? DEFAULT_MAX_COLOR;
const ariaSummary = useMemo(() => {
if (points.length === 0) return name1 ?? '';
const last = points[points.length - 1];
const parts: string[] = [];
parts.push(name1 ? `${name1}: ${yFormatter(last.value)}` : yFormatter(last.value));
if (hasSeries2 && name2) parts.push(`${name2}: ${yFormatter(last.value2)}`);
if (hasSeries3 && name3) parts.push(`${name3}: ${yFormatter(last.value3)}`);
return parts.join(', ');
}, [points, name1, name2, name3, hasSeries2, hasSeries3, yFormatter]);
return (
<div className="sparkline-container">
<div className="sparkline-container" role={ariaSummary ? 'img' : undefined} aria-label={ariaSummary || undefined}>
{extremaPoints && (
<div className="sparkline-extrema" aria-hidden="true">
<span className="extrema-item" style={{ color: maxColor }}>
+45 -2
View File
@@ -16,6 +16,7 @@ export const EXAMPLES: Record<string, unknown> = {
"ldapFlagField": "",
"ldapHost": "",
"ldapInboundTags": "",
"ldapInsecureSkipVerify": false,
"ldapInvertFlag": false,
"ldapPassword": "",
"ldapPort": 0,
@@ -52,6 +53,8 @@ export const EXAMPLES: Record<string, unknown> = {
"subEnableRouting": false,
"subEncrypt": false,
"subHideSettings": false,
"subIncyEnableRouting": false,
"subIncyRoutingRules": "",
"subJsonEnable": false,
"subJsonFinalMask": "",
"subJsonMux": "",
@@ -116,6 +119,7 @@ export const EXAMPLES: Record<string, unknown> = {
"ldapFlagField": "",
"ldapHost": "",
"ldapInboundTags": "",
"ldapInsecureSkipVerify": false,
"ldapInvertFlag": false,
"ldapPassword": "",
"ldapPort": 0,
@@ -152,6 +156,8 @@ export const EXAMPLES: Record<string, unknown> = {
"subEnableRouting": false,
"subEncrypt": false,
"subHideSettings": false,
"subIncyEnableRouting": false,
"subIncyRoutingRules": "",
"subJsonEnable": false,
"subJsonFinalMask": "",
"subJsonMux": "",
@@ -208,6 +214,9 @@ export const EXAMPLES: Record<string, unknown> = {
"token": "new-token-string"
},
"Client": {
"allowedIPs": [
""
],
"auth": "",
"comment": "",
"created_at": 0,
@@ -217,8 +226,12 @@ export const EXAMPLES: Record<string, unknown> = {
"flow": "",
"group": "",
"id": "",
"keepAlive": 0,
"limitIp": 0,
"password": "",
"preSharedKey": "",
"privateKey": "",
"publicKey": "",
"reset": 0,
"reverse": null,
"security": "",
@@ -234,6 +247,7 @@ export const EXAMPLES: Record<string, unknown> = {
"inboundId": 0
},
"ClientRecord": {
"allowedIPs": "",
"auth": "",
"comment": "",
"createdAt": 0,
@@ -243,8 +257,12 @@ export const EXAMPLES: Record<string, unknown> = {
"flow": "",
"group": "",
"id": 0,
"keepAlive": 0,
"limitIp": 0,
"password": "",
"preSharedKey": "",
"privateKey": "",
"publicKey": "",
"reset": 0,
"reverse": null,
"security": "",
@@ -322,7 +340,7 @@ export const EXAMPLES: Record<string, unknown> = {
],
"updatedAt": 0,
"verifyPeerCertByName": "",
"vlessRoute": ""
"vlessRoute": "443"
},
"Inbound": {
"clientStats": [
@@ -388,7 +406,10 @@ export const EXAMPLES: Record<string, unknown> = {
"remark": "VLESS-443",
"ssMethod": "",
"tag": "in-443-tcp",
"tlsFlowCapable": true
"tlsFlowCapable": true,
"wgDns": "",
"wgMtu": 0,
"wgPublicKey": ""
},
"Msg": {
"msg": "",
@@ -459,6 +480,28 @@ export const EXAMPLES: Record<string, unknown> = {
"xrayState": "",
"xrayVersion": "25.10.31"
},
"RealityScanResult": {
"alpn": "h2",
"certIssuer": "Google Trust Services",
"certSubject": "cloudflare.com",
"certValid": true,
"curveID": "X25519",
"feasible": true,
"h2": true,
"host": "www.cloudflare.com",
"ip": "104.16.124.96",
"latencyMs": 180,
"notAfter": "2026-08-01T00:00:00Z",
"port": 443,
"reason": "",
"serverNames": [
""
],
"target": "www.cloudflare.com:443",
"tls13": true,
"tlsVersion": "1.3",
"x25519": true
},
"Setting": {
"id": 0,
"key": "",
+175 -1
View File
@@ -58,6 +58,9 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapInboundTags": {
"type": "string"
},
"ldapInsecureSkipVerify": {
"type": "boolean"
},
"ldapInvertFlag": {
"type": "boolean"
},
@@ -206,6 +209,14 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Hide server settings in happ subscription (Only for Happ)",
"type": "boolean"
},
"subIncyEnableRouting": {
"description": "Enable routing injection for the Incy client",
"type": "boolean"
},
"subIncyRoutingRules": {
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
"type": "string"
},
"subJsonEnable": {
"description": "Enable JSON subscription endpoint",
"type": "boolean"
@@ -395,6 +406,7 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapFlagField",
"ldapHost",
"ldapInboundTags",
"ldapInsecureSkipVerify",
"ldapInvertFlag",
"ldapPassword",
"ldapPort",
@@ -431,6 +443,8 @@ export const SCHEMAS: Record<string, unknown> = {
"subEnableRouting",
"subEncrypt",
"subHideSettings",
"subIncyEnableRouting",
"subIncyRoutingRules",
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
@@ -553,6 +567,9 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapInboundTags": {
"type": "string"
},
"ldapInsecureSkipVerify": {
"type": "boolean"
},
"ldapInvertFlag": {
"type": "boolean"
},
@@ -701,6 +718,14 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Hide server settings in happ subscription (Only for Happ)",
"type": "boolean"
},
"subIncyEnableRouting": {
"description": "Enable routing injection for the Incy client",
"type": "boolean"
},
"subIncyRoutingRules": {
"description": "Incy routing deep-link injected into the subscription body (Only for Incy)",
"type": "string"
},
"subJsonEnable": {
"description": "Enable JSON subscription endpoint",
"type": "boolean"
@@ -897,6 +922,7 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapFlagField",
"ldapHost",
"ldapInboundTags",
"ldapInsecureSkipVerify",
"ldapInvertFlag",
"ldapPassword",
"ldapPort",
@@ -933,6 +959,8 @@ export const SCHEMAS: Record<string, unknown> = {
"subEnableRouting",
"subEncrypt",
"subHideSettings",
"subIncyEnableRouting",
"subIncyRoutingRules",
"subJsonEnable",
"subJsonFinalMask",
"subJsonMux",
@@ -1038,6 +1066,12 @@ export const SCHEMAS: Record<string, unknown> = {
"Client": {
"description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.",
"properties": {
"allowedIPs": {
"items": {
"type": "string"
},
"type": "array"
},
"auth": {
"description": "Auth password (Hysteria)",
"type": "string"
@@ -1074,6 +1108,9 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Unique client identifier",
"type": "string"
},
"keepAlive": {
"type": "integer"
},
"limitIp": {
"description": "IP limit for this client",
"type": "integer"
@@ -1082,6 +1119,15 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Client password",
"type": "string"
},
"preSharedKey": {
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"reset": {
"description": "Reset period in days",
"type": "integer"
@@ -1155,6 +1201,9 @@ export const SCHEMAS: Record<string, unknown> = {
},
"ClientRecord": {
"properties": {
"allowedIPs": {
"type": "string"
},
"auth": {
"type": "string"
},
@@ -1182,12 +1231,24 @@ export const SCHEMAS: Record<string, unknown> = {
"id": {
"type": "integer"
},
"keepAlive": {
"type": "integer"
},
"limitIp": {
"type": "integer"
},
"password": {
"type": "string"
},
"preSharedKey": {
"type": "string"
},
"privateKey": {
"type": "string"
},
"publicKey": {
"type": "string"
},
"reset": {
"type": "integer"
},
@@ -1212,6 +1273,7 @@ export const SCHEMAS: Record<string, unknown> = {
}
},
"required": [
"allowedIPs",
"auth",
"comment",
"createdAt",
@@ -1221,8 +1283,12 @@ export const SCHEMAS: Record<string, unknown> = {
"flow",
"group",
"id",
"keepAlive",
"limitIp",
"password",
"preSharedKey",
"privateKey",
"publicKey",
"reset",
"reverse",
"security",
@@ -1479,7 +1545,8 @@ export const SCHEMAS: Record<string, unknown> = {
"type": "string"
},
"vlessRoute": {
"description": "VlessRoute is a free-form port/range routing spec (e.g. \"53,443,1000-2000\");\nstored verbatim, format-validated on the frontend.",
"description": "Single VLESS route value (0-65535) baked into the subscription UUID's 3rd\ngroup (bytes 6-7), which xray reads via net.PortFromBytes(id[6:8]). Empty = none.",
"example": "443",
"type": "string"
}
},
@@ -1762,6 +1829,15 @@ export const SCHEMAS: Record<string, unknown> = {
"tlsFlowCapable": {
"example": true,
"type": "boolean"
},
"wgDns": {
"type": "string"
},
"wgMtu": {
"type": "integer"
},
"wgPublicKey": {
"type": "string"
}
},
"required": [
@@ -2100,6 +2176,104 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"RealityScanResult": {
"properties": {
"alpn": {
"example": "h2",
"type": "string"
},
"certIssuer": {
"example": "Google Trust Services",
"type": "string"
},
"certSubject": {
"example": "cloudflare.com",
"type": "string"
},
"certValid": {
"example": true,
"type": "boolean"
},
"curveID": {
"example": "X25519",
"type": "string"
},
"feasible": {
"example": true,
"type": "boolean"
},
"h2": {
"example": true,
"type": "boolean"
},
"host": {
"example": "www.cloudflare.com",
"type": "string"
},
"ip": {
"example": "104.16.124.96",
"type": "string"
},
"latencyMs": {
"example": 180,
"type": "integer"
},
"notAfter": {
"example": "2026-08-01T00:00:00Z",
"type": "string"
},
"port": {
"example": 443,
"type": "integer"
},
"reason": {
"type": "string"
},
"serverNames": {
"items": {
"type": "string"
},
"type": "array"
},
"target": {
"example": "www.cloudflare.com:443",
"type": "string"
},
"tls13": {
"example": true,
"type": "boolean"
},
"tlsVersion": {
"example": "1.3",
"type": "string"
},
"x25519": {
"example": true,
"type": "boolean"
}
},
"required": [
"alpn",
"certIssuer",
"certSubject",
"certValid",
"curveID",
"feasible",
"h2",
"host",
"ip",
"latencyMs",
"notAfter",
"port",
"reason",
"serverNames",
"target",
"tls13",
"tlsVersion",
"x25519"
],
"type": "object"
},
"Setting": {
"description": "Setting stores key-value configuration settings for the 3x-ui panel.",
"properties": {
+40
View File
@@ -22,6 +22,7 @@ export interface AllSetting {
ldapFlagField: string;
ldapHost: string;
ldapInboundTags: string;
ldapInsecureSkipVerify: boolean;
ldapInvertFlag: boolean;
ldapPassword: string;
ldapPort: number;
@@ -58,6 +59,8 @@ export interface AllSetting {
subEnableRouting: boolean;
subEncrypt: boolean;
subHideSettings: boolean;
subIncyEnableRouting: boolean;
subIncyRoutingRules: string;
subJsonEnable: boolean;
subJsonFinalMask: string;
subJsonMux: string;
@@ -123,6 +126,7 @@ export interface AllSettingView {
ldapFlagField: string;
ldapHost: string;
ldapInboundTags: string;
ldapInsecureSkipVerify: boolean;
ldapInvertFlag: boolean;
ldapPassword: string;
ldapPort: number;
@@ -159,6 +163,8 @@ export interface AllSettingView {
subEnableRouting: boolean;
subEncrypt: boolean;
subHideSettings: boolean;
subIncyEnableRouting: boolean;
subIncyRoutingRules: string;
subJsonEnable: boolean;
subJsonFinalMask: string;
subJsonMux: string;
@@ -218,6 +224,7 @@ export interface ApiTokenView {
}
export interface Client {
allowedIPs?: string[];
auth?: string;
comment: string;
created_at?: number;
@@ -227,8 +234,12 @@ export interface Client {
flow?: string;
group?: string;
id?: string;
keepAlive?: number;
limitIp: number;
password?: string;
preSharedKey?: string;
privateKey?: string;
publicKey?: string;
reset: number;
reverse?: ClientReverse | null;
security: string;
@@ -246,6 +257,7 @@ export interface ClientInbound {
}
export interface ClientRecord {
allowedIPs: string;
auth: string;
comment: string;
createdAt: number;
@@ -255,8 +267,12 @@ export interface ClientRecord {
flow: string;
group: string;
id: number;
keepAlive: number;
limitIp: number;
password: string;
preSharedKey: string;
privateKey: string;
publicKey: string;
reset: number;
reverse: unknown;
security: string;
@@ -385,6 +401,9 @@ export interface InboundOption {
ssMethod: string;
tag: string;
tlsFlowCapable: boolean;
wgDns?: string;
wgMtu?: number;
wgPublicKey?: string;
}
export interface Msg {
@@ -458,6 +477,27 @@ export interface ProbeResultUI {
xrayVersion: string;
}
export interface RealityScanResult {
alpn: string;
certIssuer: string;
certSubject: string;
certValid: boolean;
curveID: string;
feasible: boolean;
h2: boolean;
host: string;
ip: string;
latencyMs: number;
notAfter: string;
port: number;
reason: string;
serverNames: string[];
target: string;
tls13: boolean;
tlsVersion: string;
x25519: boolean;
}
export interface Setting {
id: number;
key: string;
+41
View File
@@ -34,6 +34,7 @@ export const AllSettingSchema = z.object({
ldapFlagField: z.string(),
ldapHost: z.string(),
ldapInboundTags: z.string(),
ldapInsecureSkipVerify: z.boolean(),
ldapInvertFlag: z.boolean(),
ldapPassword: z.string(),
ldapPort: z.number().int().min(0).max(65535),
@@ -70,6 +71,8 @@ export const AllSettingSchema = z.object({
subEnableRouting: z.boolean(),
subEncrypt: z.boolean(),
subHideSettings: z.boolean(),
subIncyEnableRouting: z.boolean(),
subIncyRoutingRules: z.string(),
subJsonEnable: z.boolean(),
subJsonFinalMask: z.string(),
subJsonMux: z.string(),
@@ -136,6 +139,7 @@ export const AllSettingViewSchema = z.object({
ldapFlagField: z.string(),
ldapHost: z.string(),
ldapInboundTags: z.string(),
ldapInsecureSkipVerify: z.boolean(),
ldapInvertFlag: z.boolean(),
ldapPassword: z.string(),
ldapPort: z.number().int().min(0).max(65535),
@@ -172,6 +176,8 @@ export const AllSettingViewSchema = z.object({
subEnableRouting: z.boolean(),
subEncrypt: z.boolean(),
subHideSettings: z.boolean(),
subIncyEnableRouting: z.boolean(),
subIncyRoutingRules: z.string(),
subJsonEnable: z.boolean(),
subJsonFinalMask: z.string(),
subJsonMux: z.string(),
@@ -234,6 +240,7 @@ export const ApiTokenViewSchema = z.object({
export type ApiTokenView = z.infer<typeof ApiTokenViewSchema>;
export const ClientSchema = z.object({
allowedIPs: z.array(z.string()).optional(),
auth: z.string().optional(),
comment: z.string(),
created_at: z.number().int().optional(),
@@ -243,8 +250,12 @@ export const ClientSchema = z.object({
flow: z.string().optional(),
group: z.string().optional(),
id: z.string().optional(),
keepAlive: z.number().int().optional(),
limitIp: z.number().int(),
password: z.string().optional(),
preSharedKey: z.string().optional(),
privateKey: z.string().optional(),
publicKey: z.string().optional(),
reset: z.number().int(),
reverse: z.lazy(() => ClientReverseSchema).nullable().optional(),
security: z.string(),
@@ -264,6 +275,7 @@ export const ClientInboundSchema = z.object({
export type ClientInbound = z.infer<typeof ClientInboundSchema>;
export const ClientRecordSchema = z.object({
allowedIPs: z.string(),
auth: z.string(),
comment: z.string(),
createdAt: z.number().int(),
@@ -273,8 +285,12 @@ export const ClientRecordSchema = z.object({
flow: z.string(),
group: z.string(),
id: z.number().int(),
keepAlive: z.number().int(),
limitIp: z.number().int(),
password: z.string(),
preSharedKey: z.string(),
privateKey: z.string(),
publicKey: z.string(),
reset: z.number().int(),
reverse: z.unknown(),
security: z.string(),
@@ -412,6 +428,9 @@ export const InboundOptionSchema = z.object({
ssMethod: z.string(),
tag: z.string(),
tlsFlowCapable: z.boolean(),
wgDns: z.string().optional(),
wgMtu: z.number().int().optional(),
wgPublicKey: z.string().optional(),
});
export type InboundOption = z.infer<typeof InboundOptionSchema>;
@@ -490,6 +509,28 @@ export const ProbeResultUISchema = z.object({
});
export type ProbeResultUI = z.infer<typeof ProbeResultUISchema>;
export const RealityScanResultSchema = z.object({
alpn: z.string(),
certIssuer: z.string(),
certSubject: z.string(),
certValid: z.boolean(),
curveID: z.string(),
feasible: z.boolean(),
h2: z.boolean(),
host: z.string(),
ip: z.string(),
latencyMs: z.number().int(),
notAfter: z.string(),
port: z.number().int(),
reason: z.string(),
serverNames: z.array(z.string()),
target: z.string(),
tls13: z.boolean(),
tlsVersion: z.string(),
x25519: z.boolean(),
});
export type RealityScanResult = z.infer<typeof RealityScanResultSchema>;
export const SettingSchema = z.object({
id: z.number().int(),
key: z.string(),
+31 -6
View File
@@ -14,6 +14,7 @@ import {
BulkAttachResultSchema,
BulkCreateResultSchema,
BulkDeleteResultSchema,
BulkSetEnableResultSchema,
BulkDetachResultSchema,
DelDepletedResultSchema,
type ClientHydrate,
@@ -27,6 +28,7 @@ import {
type BulkAttachResult,
type BulkCreateResult,
type BulkDeleteResult,
type BulkSetEnableResult,
type BulkDetachResult,
} from '@/schemas/client';
import { DefaultsPayloadSchema } from '@/schemas/defaults';
@@ -45,6 +47,7 @@ interface SubSettings {
subJsonEnable: boolean;
subClashURI: string;
subClashEnable: boolean;
publicHost: string;
}
export interface ClientQueryParams {
@@ -238,6 +241,7 @@ export function useClients() {
subJsonEnable: !!defaults.subJsonEnable,
subClashURI: (defaults.subClashURI as string) || '',
subClashEnable: !!defaults.subClashEnable,
publicHost: (defaults.subDomain as string) || (defaults.webDomain as string) || '',
}), [
defaults.subEnable,
defaults.subURI,
@@ -245,6 +249,8 @@ export function useClients() {
defaults.subJsonEnable,
defaults.subClashURI,
defaults.subClashEnable,
defaults.subDomain,
defaults.webDomain,
]);
const ipLimitEnable = !!defaults.ipLimitEnable;
@@ -341,22 +347,31 @@ export function useClients() {
});
const bulkAdjustMut = useMutation({
mutationFn: async (payload: { emails: string[]; addDays: number; addBytes: number }): Promise<Msg<BulkAdjustResult>> => {
mutationFn: async (payload: { emails: string[]; addDays: number; addBytes: number; flow: string }): Promise<Msg<BulkAdjustResult>> => {
const raw = await HttpUtil.post('/panel/api/clients/bulkAdjust', payload, JSON_HEADERS);
return parseMsg(raw, BulkAdjustResultSchema, 'clients/bulkAdjust');
},
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
});
const bulkSetEnableMut = useMutation({
mutationFn: async (payload: { emails: string[]; enable: boolean }): Promise<Msg<BulkSetEnableResult>> => {
const path = payload.enable ? '/panel/api/clients/bulkEnable' : '/panel/api/clients/bulkDisable';
const raw = await HttpUtil.post(path, { emails: payload.emails }, JSON_HEADERS);
return parseMsg(raw, BulkSetEnableResultSchema, payload.enable ? 'clients/bulkEnable' : 'clients/bulkDisable');
},
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
});
const attachMut = useMutation({
mutationFn: ({ email, inboundIds }: { email: string; inboundIds: number[] }) =>
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/attach`, { inboundIds }, JSON_HEADERS),
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/attach`, { inboundIds }, { ...JSON_HEADERS, silentSuccess: true }),
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
});
const setExternalLinksMut = useMutation({
mutationFn: ({ email, externalLinks }: { email: string; externalLinks: ExternalLinkInput[] }) =>
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/externalLinks`, { externalLinks }, JSON_HEADERS),
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/externalLinks`, { externalLinks }, { ...JSON_HEADERS, silentSuccess: true }),
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
});
@@ -370,7 +385,7 @@ export function useClients() {
const detachMut = useMutation({
mutationFn: ({ email, inboundIds }: { email: string; inboundIds: number[] }) =>
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/detach`, { inboundIds }, JSON_HEADERS),
HttpUtil.post(`/panel/api/clients/${encodeURIComponent(email)}/detach`, { inboundIds }, { ...JSON_HEADERS, silentSuccess: true }),
onSuccess: (msg) => { if (msg?.success) invalidateAll(); },
});
@@ -435,10 +450,18 @@ export function useClients() {
if (!Array.isArray(payloads) || payloads.length === 0) return Promise.resolve(null as unknown as Msg<BulkCreateResult>);
return bulkCreateMut.mutateAsync(payloads);
}, [bulkCreateMut]);
const bulkAdjust = useCallback((emails: string[], addDays: number, addBytes: number) => {
const bulkAdjust = useCallback((emails: string[], addDays: number, addBytes: number, flow = '') => {
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
return bulkAdjustMut.mutateAsync({ emails, addDays, addBytes });
return bulkAdjustMut.mutateAsync({ emails, addDays, addBytes, flow });
}, [bulkAdjustMut]);
const bulkEnable = useCallback((emails: string[]) => {
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null as unknown as Msg<BulkSetEnableResult>);
return bulkSetEnableMut.mutateAsync({ emails, enable: true });
}, [bulkSetEnableMut]);
const bulkDisable = useCallback((emails: string[]) => {
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null as unknown as Msg<BulkSetEnableResult>);
return bulkSetEnableMut.mutateAsync({ emails, enable: false });
}, [bulkSetEnableMut]);
const bulkAddToGroup = useCallback((emails: string[], group: string) => {
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
return bulkAddToGroupMut.mutateAsync({ emails, group });
@@ -590,6 +613,8 @@ export function useClients() {
remove,
bulkDelete,
bulkAdjust,
bulkEnable,
bulkDisable,
bulkAddToGroup,
bulkRemoveFromGroup,
attach,
+1
View File
@@ -8,6 +8,7 @@ const TITLE_KEYS: Record<string, string> = {
'/clients': 'menu.clients',
'/groups': 'menu.groups',
'/nodes': 'menu.nodes',
'/hosts': 'menu.hosts',
'/settings': 'menu.settings',
'/xray': 'menu.xray',
'/outbound': 'menu.outbounds',
+27
View File
@@ -75,6 +75,33 @@
font-size: 16px;
}
.sidebar-docs {
background: transparent;
border: none;
width: 30px;
height: 30px;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--ant-color-text-secondary);
text-decoration: none;
flex-shrink: 0;
transition: background-color 0.2s, transform 0.15s, color 0.2s;
}
.sidebar-docs:hover,
.sidebar-docs:focus-visible {
background-color: color-mix(in srgb, var(--ant-color-primary) 12%, transparent);
color: var(--ant-color-primary);
transform: scale(1.08);
outline: none;
}
.sidebar-docs .anticon {
font-size: 16px;
}
.sidebar-theme-cycle {
background: transparent;
border: none;
+22 -2
View File
@@ -23,6 +23,7 @@ import {
MessageOutlined,
MoonFilled,
MoonOutlined,
ReadOutlined,
SafetyOutlined,
SettingOutlined,
SunOutlined,
@@ -33,12 +34,14 @@ import {
} from '@ant-design/icons';
import { HttpUtil } from '@/utils';
import { formatPanelVersion } from '@/lib/panel-version';
import { pauseAnimationsUntilLeave, useTheme } from '@/hooks/useTheme';
import { useAllSettings } from '@/api/queries/useAllSettings';
import './AppSidebar.css';
const SIDEBAR_COLLAPSED_KEY = 'isSidebarCollapsed';
const DONATE_URL = 'https://donate.sanaei.dev/';
const DOCS_URL = 'https://docs.sanaei.dev/';
const REPO_URL = 'https://github.com/MHSanaei/3x-ui';
const LOGOUT_KEY = '__logout__';
@@ -82,9 +85,24 @@ function DonateButton({ ariaLabel }: { ariaLabel: string }) {
);
}
function DocsButton({ ariaLabel }: { ariaLabel: string }) {
return (
<a
href={DOCS_URL}
target="_blank"
rel="noopener noreferrer"
className="sidebar-docs"
aria-label={ariaLabel}
title={ariaLabel}
>
<ReadOutlined />
</a>
);
}
function VersionBadge({ version, collapsed }: { version: string; collapsed?: boolean }) {
if (!version) return null;
const label = `v${version}`;
const label = formatPanelVersion(version);
return (
<a
href={REPO_URL}
@@ -253,6 +271,7 @@ export default function AppSidebar() {
</div>
{!collapsed && (
<div className="brand-actions">
<DocsButton ariaLabel={t('menu.docs') || 'Documentation'} />
<DonateButton ariaLabel={t('menu.donate') || 'Donate'} />
<ThemeCycleButton
id="theme-cycle"
@@ -305,6 +324,7 @@ export default function AppSidebar() {
<span className="drawer-brand">3X-UI</span>
</div>
<div className="drawer-header-actions">
<DocsButton ariaLabel={t('menu.docs') || 'Documentation'} />
<DonateButton ariaLabel={t('menu.donate') || 'Donate'} />
<ThemeCycleButton
id="theme-cycle-drawer"
@@ -350,7 +370,7 @@ export default function AppSidebar() {
<button
className="drawer-handle"
type="button"
aria-label={t('menu.dashboard')}
aria-label={t('menu.openMenu')}
onClick={() => setDrawerOpen(true)}
>
<MenuOutlined />
+2
View File
@@ -17,6 +17,7 @@ export type HostLinkInput = Pick<
| 'echConfigList'
| 'overrideSniFromAddress'
| 'keepSniBlank'
| 'vlessRoute'
>;
// hostToExternalProxyEntry projects a host onto the ExternalProxyEntry shape the
@@ -48,5 +49,6 @@ export function hostToExternalProxyEntry(host: HostLinkInput): ExternalProxyEntr
host.pinnedPeerCertSha256 && host.pinnedPeerCertSha256.length > 0 ? host.pinnedPeerCertSha256 : undefined,
verifyPeerCertByName: host.verifyPeerCertByName || undefined,
echConfigList: host.echConfigList || undefined,
vlessRoute: host.vlessRoute || undefined,
};
}
+12
View File
@@ -14,6 +14,18 @@ function parseVersionParts(version: string): [number, number, number] | null {
return [out[0], out[1], out[2]];
}
// Format a panel version for display. Dev builds report a "dev+<commit>"
// identity (see config.GetPanelVersion); show those — and any other
// non-numeric label — verbatim. Semantic versions get a single normalized "v"
// prefix, so a raw "v3.4.0" tag and a bare "3.4.0" both render as "v3.4.0"
// instead of doubling up to "vv3.4.0".
export function formatPanelVersion(version: string | undefined | null): string {
const v = (version || '').trim();
if (!v) return '';
const normalized = v.replace(/^v/i, '');
return /^\d/.test(normalized) ? `v${normalized}` : v;
}
export function isPanelUpdateAvailable(latest: string, current: string): boolean {
if (!latest || !current) return false;
const a = parseVersionParts(latest);
+10 -2
View File
@@ -3,7 +3,7 @@
// per client. This file is the single frontend source of truth for the picker
// UI and the live preview — keep the token list in sync with remark_vars.go.
export type RemarkVarGroup = 'client' | 'traffic' | 'time';
export type RemarkVarGroup = 'client' | 'traffic' | 'time' | 'connection';
export interface RemarkVar {
/** Bare token name, e.g. "TRAFFIC_LEFT" (rendered as {{TRAFFIC_LEFT}}). */
@@ -13,7 +13,7 @@ export interface RemarkVar {
sample: string;
}
export const REMARK_VAR_GROUPS: RemarkVarGroup[] = ['client', 'traffic', 'time'];
export const REMARK_VAR_GROUPS: RemarkVarGroup[] = ['client', 'traffic', 'time', 'connection'];
export const REMARK_VARIABLES: RemarkVar[] = [
// Client identity
@@ -36,11 +36,19 @@ export const REMARK_VARIABLES: RemarkVar[] = [
{ token: 'DOWN', group: 'traffic', sample: '3.20GB' },
// Time / status
{ token: 'STATUS', group: 'time', sample: 'active' },
{ token: 'STATUS_EMOJI', group: 'time', sample: '✅' },
{ token: 'DAYS_LEFT', group: 'time', sample: '12' },
{ token: 'TIME_LEFT', group: 'time', sample: '12d 4h 30m' },
{ token: 'USAGE_PERCENTAGE', group: 'time', sample: '52.3%' },
{ token: 'EXPIRE_DATE', group: 'time', sample: '2026-09-01' },
{ token: 'JALALI_EXPIRE_DATE', group: 'time', sample: '1405/06/10' },
{ token: 'EXPIRE_UNIX', group: 'time', sample: '1788300000' },
{ token: 'CREATED_UNIX', group: 'time', sample: '1700000000' },
{ token: 'RESET_DAYS', group: 'time', sample: '30' },
// Connection (inbound config descriptors)
{ token: 'PROTOCOL', group: 'connection', sample: 'VLESS' },
{ token: 'TRANSPORT', group: 'connection', sample: 'ws' },
{ token: 'SECURITY', group: 'connection', sample: 'TLS' },
];
const SAMPLE_BY_TOKEN: Record<string, string> = Object.fromEntries(
@@ -34,7 +34,12 @@ export default function SniffingFields({ name, form, enableLabel }: SniffingFiel
{enabled && (
<>
<Form.Item name={[...name, 'destOverride']} wrapperCol={{ md: { span: 14, offset: 8 } }}>
<Select mode="multiple" className="sniffing-options" options={DEST_OPTIONS} />
<Select
mode="multiple"
className="sniffing-options"
aria-label={t('pages.inbounds.sniffingDestOverride')}
options={DEST_OPTIONS}
/>
</Form.Item>
<Form.Item
label={t('pages.inbounds.sniffingMetadataOnly')}
@@ -3,6 +3,8 @@ import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { NamePath } from 'antd/es/form/interface';
import { activateOnKey } from '@/utils/a11y';
// Editor for sockopt.customSockopt — a list of raw setsockopt() options. Each
// entry is rendered as a titled group of labeled fields (system / level / opt /
// type / value) instead of one cramped inline row, so it reads like the rest of
@@ -49,7 +51,11 @@ export default function CustomSockoptList({
<DeleteOutlined
className="danger-icon"
style={{ marginInlineStart: 8 }}
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={() => remove(field.name)}
onKeyDown={activateOnKey(() => remove(field.name))}
/>
</Divider>
<Form.Item label="System" name={[field.name, 'system']}>
@@ -1,10 +1,12 @@
import { useEffect, useRef } from 'react';
import { AutoComplete, Button, Divider, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
import { DeleteOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { FormInstance } from 'antd/es/form';
import type { NamePath } from 'antd/es/form/interface';
import { RandomUtil } from '@/utils';
import { activateOnKey } from '@/utils/a11y';
import { OutboundProtocols, UTLS_FINGERPRINT } from '@/schemas/primitives';
const UTLS_FINGERPRINT_OPTIONS = Object.values(UTLS_FINGERPRINT).map((value) => ({ value, label: value }));
@@ -224,6 +226,7 @@ export default function FinalMaskForm({ name, network, protocol, form, showAll =
}
function TcpMasksList({ base, form }: { base: (string | number)[]; form: FormInstance }) {
const { t } = useTranslation();
return (
<Form.List name={[...base, 'tcp']}>
{(fields, { add, remove }) => (
@@ -233,6 +236,7 @@ function TcpMasksList({ base, form }: { base: (string | number)[]; form: FormIns
type="primary"
size="small"
icon={<PlusOutlined />}
aria-label={t('add')}
onClick={() => add({ type: 'fragment', settings: defaultTcpMaskSettings('fragment') })}
/>
</Form.Item>
@@ -265,12 +269,20 @@ function TcpMaskItem({
// type change). All Form.Item `name=` use RELATIVE paths within the
// outer Form.List context.
const absolutePath = [...listPath, fieldName];
const { t } = useTranslation();
return (
<div>
<Divider style={{ margin: 0 }}>
TCP Mask {displayIndex}
<DeleteOutlined className="danger-icon" onClick={onRemove} />
<DeleteOutlined
className="danger-icon"
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={onRemove}
onKeyDown={activateOnKey(onRemove)}
/>
</Divider>
<Form.Item label="Type" name={[fieldName, 'type']}>
@@ -415,12 +427,13 @@ function FragmentRangeList({
validator?: (rule: unknown, value: unknown) => Promise<void>;
minItems?: number;
}) {
const { t } = useTranslation();
return (
<Form.List name={listName}>
{(fields, { add, remove }) => (
<>
<Form.Item label={label}>
<Button type="primary" size="small" icon={<PlusOutlined />} onClick={() => add('')} />
<Button type="primary" size="small" icon={<PlusOutlined />} aria-label={t('add')} onClick={() => add('')} />
</Form.Item>
{fields.map((field, idx) => (
<Form.Item
@@ -431,8 +444,17 @@ function FragmentRangeList({
>
<Input
placeholder={placeholder}
addonAfter={fields.length > minItems
? <DeleteOutlined className="danger-icon" onClick={() => remove(field.name)} />
suffix={fields.length > minItems
? (
<DeleteOutlined
className="danger-icon"
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={() => remove(field.name)}
onKeyDown={activateOnKey(() => remove(field.name))}
/>
)
: null}
/>
</Form.Item>
@@ -475,6 +497,7 @@ function HeaderCustomGroups({
form: FormInstance;
absoluteSettingsPath: (string | number)[];
}) {
const { t } = useTranslation();
return (
<>
{(['clients', 'servers'] as const).map((groupKey) => (
@@ -486,6 +509,7 @@ function HeaderCustomGroups({
type="primary"
size="small"
icon={<PlusOutlined />}
aria-label={t('add')}
onClick={() => addGroup([defaultClientServerItem()])}
/>
</Form.Item>
@@ -493,7 +517,14 @@ function HeaderCustomGroups({
<div key={group.key}>
<Divider style={{ margin: 0 }}>
{groupKey === 'clients' ? 'Clients' : 'Servers'} Group {gi + 1}
<DeleteOutlined className="danger-icon" onClick={() => removeGroup(group.name)} />
<DeleteOutlined
className="danger-icon"
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={() => removeGroup(group.name)}
onKeyDown={activateOnKey(() => removeGroup(group.name))}
/>
</Divider>
<Form.List name={[group.name]}>
{(items, { add: addItem, remove: removeItem }) => (
@@ -502,6 +533,7 @@ function HeaderCustomGroups({
<Button
size="small"
icon={<PlusOutlined />}
aria-label={t('add')}
onClick={() => addItem(defaultClientServerItem())}
/>
</Form.Item>
@@ -531,6 +563,7 @@ function HeaderCustomGroups({
function UdpMasksList({
base, form, isHysteria, isWireguard, network,
}: { base: (string | number)[]; form: FormInstance; isHysteria: boolean; isWireguard: boolean; network: string }) {
const { t } = useTranslation();
return (
<Form.List name={[...base, 'udp']}>
{(fields, { add, remove }) => (
@@ -540,6 +573,7 @@ function UdpMasksList({
type="primary"
size="small"
icon={<PlusOutlined />}
aria-label={t('add')}
onClick={() => {
const def = isHysteria || isWireguard ? 'salamander' : 'mkcp-legacy';
add({ type: def, settings: defaultUdpMaskSettings(def) });
@@ -578,6 +612,7 @@ function UdpMaskItem({
onRemove: () => void;
}) {
const absolutePath = [...listPath, fieldName];
const { t } = useTranslation();
const onTypeChange = (v: string) => {
form.setFieldValue([...absolutePath, 'settings'], defaultUdpMaskSettings(v));
@@ -605,7 +640,14 @@ function UdpMaskItem({
<div>
<Divider style={{ margin: 0 }}>
UDP Mask {displayIndex}
<DeleteOutlined className="danger-icon" onClick={onRemove} />
<DeleteOutlined
className="danger-icon"
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={onRemove}
onKeyDown={activateOnKey(onRemove)}
/>
</Divider>
<Form.Item label="Type" name={[fieldName, 'type']}>
@@ -735,6 +777,7 @@ function SalamanderUdpMaskSettings({
form: FormInstance;
absolutePath: (string | number)[];
}) {
const { t } = useTranslation();
const packetSizePath = [...absolutePath, 'settings', 'packetSize'];
const packetSize = Form.useWatch(packetSizePath, { form, preserve: true });
const mode = typeof packetSize === 'string' && packetSize.trim() !== '' ? 'gecko' : 'salamander';
@@ -776,6 +819,7 @@ function SalamanderUdpMaskSettings({
</Form.Item>
<Button
icon={<ReloadOutlined />}
aria-label={t('regenerate')}
onClick={() => form.setFieldValue(
[...absolutePath, 'settings', 'password'],
RandomUtil.randomLowerAndNum(16),
@@ -810,7 +854,7 @@ function GeckoPacketSizeInput({
return (
<Space.Compact block>
<InputNumber
addonBefore="Min"
prefix="Min"
min={GECKO_MIN_PACKET_SIZE}
max={GECKO_MAX_PACKET_SIZE}
precision={0}
@@ -820,7 +864,7 @@ function GeckoPacketSizeInput({
style={{ width: '50%' }}
/>
<InputNumber
addonBefore="Max"
prefix="Max"
min={GECKO_MIN_PACKET_SIZE}
max={GECKO_MAX_PACKET_SIZE}
precision={0}
@@ -840,6 +884,7 @@ function UdpHeaderCustom({
form: FormInstance;
absoluteSettingsPath: (string | number)[];
}) {
const { t } = useTranslation();
return (
<>
{(['client', 'server'] as const).map((groupKey) => (
@@ -851,6 +896,7 @@ function UdpHeaderCustom({
type="primary"
size="small"
icon={<PlusOutlined />}
aria-label={t('add')}
onClick={() => add(defaultUdpClientServerItem())}
/>
</Form.Item>
@@ -858,7 +904,14 @@ function UdpHeaderCustom({
<div key={item.key}>
<Divider style={{ margin: 0 }}>
{groupKey === 'client' ? 'Client' : 'Server'} {ci + 1}
<DeleteOutlined className="danger-icon" onClick={() => remove(item.name)} />
<DeleteOutlined
className="danger-icon"
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={() => remove(item.name)}
onKeyDown={activateOnKey(() => remove(item.name))}
/>
</Divider>
<ItemEditor
fieldName={item.name}
@@ -883,6 +936,7 @@ function NoiseItems({
form: FormInstance;
absoluteSettingsPath: (string | number)[];
}) {
const { t } = useTranslation();
return (
<>
<Form.Item label="Reset" name={[udpFieldName, 'settings', 'reset']}>
@@ -896,6 +950,7 @@ function NoiseItems({
type="primary"
size="small"
icon={<PlusOutlined />}
aria-label={t('add')}
onClick={() => add(defaultNoiseItem())}
/>
</Form.Item>
@@ -903,7 +958,14 @@ function NoiseItems({
<div key={item.key}>
<Divider style={{ margin: 0 }}>
Noise {ni + 1}
<DeleteOutlined className="danger-icon" onClick={() => remove(item.name)} />
<DeleteOutlined
className="danger-icon"
role="button"
tabIndex={0}
aria-label={t('remove')}
onClick={() => remove(item.name)}
onKeyDown={activateOnKey(() => remove(item.name))}
/>
</Divider>
<ItemEditor
fieldName={item.name}
@@ -930,6 +992,7 @@ function ItemEditor({
delayMode?: 'number' | 'string';
onRemove?: () => void;
}) {
const { t } = useTranslation();
const onTypeChange = (v: string) => {
if (v === 'base64') {
form.setFieldValue([...absoluteItemPath, 'packet'], RandomUtil.randomBase64());
@@ -1005,6 +1068,7 @@ function ItemEditor({
</Form.Item>
<Button
icon={<ReloadOutlined />}
aria-label={t('regenerate')}
onClick={() => form.setFieldValue([...absoluteItemPath, 'packet'], RandomUtil.randomBase64())}
/>
</Space.Compact>
+6 -10
View File
@@ -263,24 +263,20 @@ export interface WireguardInboundSeed {
mtu?: number;
secretKey?: string;
noKernelTun?: boolean;
peerPrivateKey?: string;
}
// WireGuard is multi-client now: a new inbound holds only the server identity
// (secretKey/mtu) and starts with no clients. Clients (peers) are added later
// through the client modal, which generates each one's keypair and a unique
// tunnel address. peers stays empty for backward-compatible parsing.
export function createDefaultWireguardInboundSettings(
seed: WireguardInboundSeed = {},
): WireguardInboundSettings {
const peerKp = seed.peerPrivateKey
? { privateKey: seed.peerPrivateKey, publicKey: Wireguard.generateKeypair(seed.peerPrivateKey).publicKey }
: Wireguard.generateKeypair();
return {
mtu: seed.mtu ?? 1420,
secretKey: seed.secretKey ?? Wireguard.generateKeypair().privateKey,
peers: [{
privateKey: peerKp.privateKey,
publicKey: peerKp.publicKey,
allowedIPs: ['10.0.0.2/32'],
keepAlive: 0,
}],
peers: [],
clients: [],
noKernelTun: seed.noKernelTun ?? false,
};
}
@@ -6,6 +6,7 @@ import {
TrojanClientSchema,
VlessClientSchema,
VmessClientSchema,
WireguardClientSchema,
} from '@/schemas/protocols/inbound';
import type { StreamSettings } from '@/schemas/api/inbound';
import type { Sniffing } from '@/schemas/primitives';
@@ -234,6 +235,7 @@ function clientSchemaForProtocol(protocol: string): z.ZodType | null {
case 'trojan': return TrojanClientSchema;
case 'shadowsocks': return ShadowsocksClientSchema;
case 'hysteria': return HysteriaClientSchema;
case 'wireguard': return WireguardClientSchema;
default: return null;
}
}
+97 -6
View File
@@ -326,6 +326,18 @@ export interface GenVlessLinkInput {
externalProxy?: ExternalProxyEntry | null;
}
// Mirror of the Go applyVlessRoute: bake a single 0-65535 value into the UUID's
// 3rd group (bytes 6-7), which xray reads as the vless route. Empty/invalid/non-
// UUID input is returned unchanged.
export function applyVlessRoute(id: string, route: string | undefined): string {
const r = (route ?? '').trim();
if (r === '' || !/^\d{1,5}$/.test(r)) return id;
const n = Number(r);
if (n > 65535) return id;
if (!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) return id;
return id.slice(0, 14) + n.toString(16).padStart(4, '0') + id.slice(18);
}
// VLESS share link: vless://<uuid>@<host>:<port>?<query>#<remark>. The
// query carries network type, encryption, network-specific knobs, and
// security-specific knobs (TLS fingerprint/alpn/sni or Reality
@@ -437,7 +449,7 @@ export function genVlessLink(input: GenVlessLinkInput): string {
params.set('flow', flow);
}
const url = new URL(`vless://${clientId}@${formatUrlHost(address)}:${port}`);
const url = new URL(`vless://${applyVlessRoute(clientId, externalProxy?.vlessRoute)}@${formatUrlHost(address)}:${port}`);
for (const [key, value] of params) url.searchParams.set(key, value);
url.hash = encodeURIComponent(remark);
return url.toString();
@@ -828,7 +840,7 @@ export function genWireguardConfig(input: GenWireguardLinkInput): string {
let txt = `[Interface]\n`;
txt += `PrivateKey = ${peer.privateKey ?? ''}\n`;
txt += `Address = ${peer.allowedIPs[0] ?? ''}\n`;
txt += `DNS = 1.1.1.1, 1.0.0.1\n`;
txt += `DNS = ${settings.dns || '1.1.1.1, 1.0.0.1'}\n`;
if (typeof settings.mtu === 'number' && settings.mtu > 0) {
txt += `MTU = ${settings.mtu}\n`;
}
@@ -846,6 +858,66 @@ export function genWireguardConfig(input: GenWireguardLinkInput): string {
return txt;
}
export function wireguardConfigFromLink(link: string, fallbackRemark = ''): string {
let url: URL;
try {
url = new URL(link);
} catch {
return '';
}
const scheme = url.protocol.replace(/:$/, '');
if (scheme !== 'wireguard' && scheme !== 'wg') return '';
const params = url.searchParams;
const pick = (...keys: string[]): string => {
for (const k of keys) {
const v = params.get(k);
if (v) return v;
}
return '';
};
let privateKey: string;
try {
privateKey = decodeURIComponent(url.username);
} catch {
privateKey = url.username;
}
const host = url.hostname;
const endpoint = host ? (url.port ? `${host}:${url.port}` : host) : '';
const address = pick('address', 'ip') || '10.0.0.2/32';
const publicKey = pick('publickey', 'publicKey', 'public_key', 'peerPublicKey');
const dns = pick('dns') || '1.1.1.1, 1.0.0.1';
const mtu = pick('mtu');
const psk = pick('presharedkey', 'preshared_key', 'pre-shared-key', 'psk');
const keepAlive = pick('keepalive', 'persistentkeepalive', 'persistent_keepalive');
const allowedIPs = pick('allowedips', 'allowed_ips') || '0.0.0.0/0, ::/0';
let remark = fallbackRemark;
try {
const decoded = decodeURIComponent(url.hash.replace(/^#/, ''));
if (decoded) remark = decoded;
} catch {
const raw = url.hash.replace(/^#/, '');
if (raw) remark = raw;
}
const lines = [
'[Interface]',
`PrivateKey = ${privateKey}`,
`Address = ${address}`,
`DNS = ${dns}`,
];
if (mtu && Number(mtu) > 0) lines.push(`MTU = ${mtu}`);
lines.push('');
if (remark) lines.push(`# ${remark}`);
lines.push('[Peer]', `PublicKey = ${publicKey}`);
if (psk) lines.push(`PresharedKey = ${psk}`);
lines.push(`AllowedIPs = ${allowedIPs}`, `Endpoint = ${endpoint}`);
if (keepAlive && Number(keepAlive) > 0) lines.push(`PersistentKeepalive = ${keepAlive}`);
return lines.join('\n');
}
export type { WireguardInboundPeer };
function isUnixSocketListen(listen: string): boolean {
@@ -1126,14 +1198,30 @@ export interface GenWireguardFanoutInput {
fallbackHostname: string;
}
// WireGuard is multi-client: each client is one accepted peer. The canonical
// store is settings.clients; legacy single-config inbounds (pre-migration) are
// still rendered from settings.peers. Both carry the privateKey/allowedIPs/
// preSharedKey/keepAlive the link and .conf need, so they project to the same
// peer shape and reuse genWireguardLink/genWireguardConfig unchanged.
function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer[] {
const clients = settings.clients ?? [];
if (clients.length > 0) {
return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
}
return settings.peers;
}
export function genWireguardLinks(input: GenWireguardFanoutInput): string {
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
if (inbound.protocol !== 'wireguard') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = '-';
return inbound.settings.peers
const baseSettings = inbound.settings as WireguardInboundSettings;
const peers = wgRenderPeers(baseSettings);
const settings: WireguardInboundSettings = { ...baseSettings, peers };
return peers
.map((p, i) => genWireguardLink({
settings: inbound.settings as WireguardInboundSettings,
settings,
address: addr,
port: inbound.port,
remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
@@ -1147,9 +1235,12 @@ export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
if (inbound.protocol !== 'wireguard') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = '-';
return inbound.settings.peers
const baseSettings = inbound.settings as WireguardInboundSettings;
const peers = wgRenderPeers(baseSettings);
const settings: WireguardInboundSettings = { ...baseSettings, peers };
return peers
.map((p, i) => genWireguardConfig({
settings: inbound.settings as WireguardInboundSettings,
settings,
address: addr,
port: inbound.port,
remark: `${remark}${sep}${i + 1}${wgPeerCommentSuffix(p)}`,
+31 -2
View File
@@ -8,6 +8,7 @@ import type {
DnsRuleForm,
FreedomFinalRuleForm,
FreedomOutboundFormSettings,
HttpOutboundFormSettings,
HysteriaOutboundFormSettings,
LoopbackOutboundFormSettings,
MuxForm,
@@ -178,6 +179,26 @@ function simpleAuthFromWire(raw: Raw, defaultPort: number): SimpleAuthFormSettin
};
}
function stringRecordFromWire(raw: unknown): Record<string, string> {
const obj = asObject(raw);
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(obj)) {
if (typeof v === 'string') out[k] = v;
}
return out;
}
// HTTP outbound reuses the SOCKS server/user shape but also carries xray's
// top-level `settings.headers` (HTTPClientConfig.Headers), the CONNECT
// headers sent to the upstream proxy. xray ignores per-server `headers`,
// so only the settings-level map round-trips (issue #5519).
function httpFromWire(raw: Raw): HttpOutboundFormSettings {
return {
...simpleAuthFromWire(raw, 8080),
headers: stringRecordFromWire(raw.headers),
};
}
function wireguardFromWire(raw: Raw): WireguardOutboundFormSettings {
const secretKey = asString(raw.secretKey);
const pubKey = secretKey.length > 0
@@ -395,7 +416,7 @@ export function rawOutboundToFormValues(raw: RawOutboundRow): OutboundFormValues
case 'trojan': typed = { protocol: 'trojan', settings: trojanFromWire(settings) }; break;
case 'shadowsocks': typed = { protocol: 'shadowsocks', settings: shadowsocksFromWire(settings) }; break;
case 'socks': typed = { protocol: 'socks', settings: simpleAuthFromWire(settings, 1080) }; break;
case 'http': typed = { protocol: 'http', settings: simpleAuthFromWire(settings, 8080) }; break;
case 'http': typed = { protocol: 'http', settings: httpFromWire(settings) }; break;
case 'wireguard': typed = { protocol: 'wireguard', settings: wireguardFromWire(settings) }; break;
case 'hysteria': typed = { protocol: 'hysteria', settings: hysteriaFromWire(settings) }; break;
case 'freedom': typed = { protocol: 'freedom', settings: freedomFromWire(settings) }; break;
@@ -489,6 +510,14 @@ function simpleAuthToWire(s: SimpleAuthFormSettings) {
};
}
function httpToWire(s: HttpOutboundFormSettings): Raw {
const wire: Raw = simpleAuthToWire(s);
if (s.headers && Object.keys(s.headers).length > 0) {
wire.headers = s.headers;
}
return wire;
}
function wireguardToWire(s: WireguardOutboundFormSettings) {
return {
mtu: s.mtu || undefined,
@@ -629,7 +658,7 @@ export function formValuesToWirePayload(values: OutboundFormValues): WireOutboun
case 'trojan': settings = trojanToWire(values.settings); break;
case 'shadowsocks': settings = shadowsocksToWire(values.settings); break;
case 'socks': settings = simpleAuthToWire(values.settings); break;
case 'http': settings = simpleAuthToWire(values.settings); break;
case 'http': settings = httpToWire(values.settings); break;
case 'wireguard': settings = wireguardToWire(values.settings); break;
case 'hysteria': settings = hysteriaToWire(values.settings); break;
case 'freedom': settings = freedomToWire(values.settings); break;
-23
View File
@@ -1,23 +0,0 @@
export interface RealityTarget {
target: string;
sni: string;
}
export const REALITY_TARGETS: readonly RealityTarget[] = [
{ target: 'www.amazon.com:443', sni: 'www.amazon.com' },
{ target: 'aws.amazon.com:443', sni: 'aws.amazon.com' },
{ target: 'www.oracle.com:443', sni: 'www.oracle.com' },
{ target: 'www.nvidia.com:443', sni: 'www.nvidia.com' },
{ target: 'www.amd.com:443', sni: 'www.amd.com' },
{ target: 'www.intel.com:443', sni: 'www.intel.com' },
{ target: 'www.sony.com:443', sni: 'www.sony.com' },
];
export function getRandomRealityTarget(): RealityTarget {
const randomIndex = Math.floor(Math.random() * REALITY_TARGETS.length);
const selected = REALITY_TARGETS[randomIndex];
return {
target: selected.target,
sni: selected.sni,
};
}
+4 -1
View File
@@ -13,7 +13,7 @@ export class AllSetting {
pageSize = 25;
expireDiff = 0;
trafficDiff = 0;
remarkTemplate = '{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D';
remarkTemplate = '{{INBOUND}}-{{EMAIL}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D';
datepicker: 'gregorian' | 'jalalian' = 'gregorian';
tgBotEnable = false;
tgBotToken = '';
@@ -35,6 +35,8 @@ export class AllSetting {
subAnnounce = '';
subEnableRouting = false;
subRoutingRules = '';
subIncyEnableRouting = false;
subIncyRoutingRules = '';
subListen = '';
subPort = 2096;
subPath = '/sub/';
@@ -66,6 +68,7 @@ export class AllSetting {
ldapHost = '';
ldapPort = 389;
ldapUseTLS = false;
ldapInsecureSkipVerify = false;
ldapBindDN = '';
ldapPassword = '';
ldapBaseDN = '';
+3 -1
View File
@@ -1,4 +1,5 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { ConfigProvider, Layout } from 'antd';
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
@@ -12,6 +13,7 @@ const openApiUrl = `${basePath}panel/api/openapi.json`;
export default function ApiDocsPage() {
const { isDark, isUltra, antdThemeConfig } = useTheme();
const { t } = useTranslation();
const pageClass = useMemo(() => {
const classes = ['api-docs-page'];
@@ -27,7 +29,7 @@ export default function ApiDocsPage() {
<Layout className="content-shell">
<Layout.Content className="content-area">
<div className="docs-wrapper">
<div className="docs-wrapper" role="region" aria-label={t('menu.apiDocs')}>
<SwaggerUI
url={openApiUrl}
docExpansion="list"
+63 -4
View File
@@ -126,6 +126,14 @@ export const sections: readonly Section[] = [
responseSchema: 'InboundOption',
responseSchemaArray: true,
},
{
method: 'GET',
path: '/panel/api/inbounds/allLinks',
summary:
'Return every protocol URL (vless://, vmess://, trojan://, ss://, hysteria://, mtproto) across all inbounds and all of their clients. Links are rendered through the subscription engine, so the configured remark template (name-only display part) is applied per client — the same output the client info/QR pages use. Protocols without a URL form (socks, http, mixed, wireguard, dokodemo, tunnel) contribute nothing. Used by the panels "Export all inbound links" action.',
response:
'{\n "success": true,\n "obj": [\n "vless://uuid@host:443?security=reality&...#Germany-alice",\n "vmess://eyJ2IjoyLC..."\n ]\n}',
},
{
method: 'GET',
path: '/panel/api/inbounds/get/:id',
@@ -400,6 +408,15 @@ export const sections: readonly Section[] = [
path: '/panel/api/server/updatePanel',
summary: 'Self-update the panel to the latest version. The server restarts on success.',
},
{
method: 'POST',
path: '/panel/api/server/setUpdateChannel',
summary: 'Toggle the panel update channel between stable and the rolling per-commit dev release. Only effective on dev builds.',
params: [
{ name: 'dev', in: 'body (form)', type: 'boolean', desc: 'true = dev channel, false = stable.' },
],
body: 'dev=true',
},
{
method: 'POST',
path: '/panel/api/server/updateGeofile',
@@ -480,6 +497,27 @@ export const sections: readonly Section[] = [
body: 'server=cloudflare-dns.com',
response: '{\n "success": true,\n "obj": [\n "e8e2d3..."\n ]\n}',
},
{
method: 'POST',
path: '/panel/api/server/scanRealityTarget',
summary: 'Run a live TLS 1.3 probe against a candidate REALITY target and return a feasibility verdict (TLS 1.3 + h2 + X25519 + trusted certificate) plus the certificate SAN DNS names.',
params: [
{ name: 'target', in: 'body (form)', type: 'string', desc: 'Candidate target as host or host:port (default port 443), e.g. www.cloudflare.com:443.' },
],
body: 'target=www.cloudflare.com:443',
responseSchema: 'RealityScanResult',
},
{
method: 'POST',
path: '/panel/api/server/scanRealityTargets',
summary: 'Probe/discover REALITY targets and return each verdict ranked by feasibility then latency. Each comma-separated token may be a domain (validated with SNI), a bare IP, or a CIDR range (discovered without SNI by reading the certificate domain). When empty, a built-in seed list is probed.',
params: [
{ name: 'targets', in: 'body (form)', type: 'string', optional: true, desc: 'Optional comma-separated tokens: domain[:port], IP[:port], or CIDR (e.g. 104.16.0.0/24). When omitted, a built-in seed list is probed.' },
],
body: 'targets=104.16.0.0/24,www.apple.com:443',
responseSchema: 'RealityScanResult',
responseSchemaArray: true,
},
{
method: 'GET',
path: '/panel/api/server/clientIps',
@@ -635,10 +673,24 @@ export const sections: readonly Section[] = [
{
method: 'POST',
path: '/panel/api/clients/bulkAdjust',
summary: 'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. Returns the adjusted count and per-email skip reasons.',
body: '{\n "emails": ["alice", "bob"],\n "addDays": 30,\n "addBytes": 53687091200\n}',
summary: 'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: "none" clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound supports it (omit or "" to leave it unchanged). Returns the adjusted count and per-email skip reasons.',
body: '{\n "emails": ["alice", "bob"],\n "addDays": 30,\n "addBytes": 53687091200,\n "flow": "xtls-rprx-vision"\n}',
response: '{\n "success": true,\n "obj": {\n "adjusted": 2,\n "skipped": [\n { "email": "carol", "reason": "unlimited expiry" }\n ]\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/bulkEnable',
summary: 'Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.',
body: '{\n "emails": ["alice", "bob"]\n}',
response: '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/bulkDisable',
summary: 'Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.',
body: '{\n "emails": ["alice", "bob"]\n}',
response: '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/bulkDel',
@@ -732,6 +784,13 @@ export const sections: readonly Section[] = [
body: '{\n "name": "customer-a"\n}',
response: '{\n "success": true,\n "obj": {\n "affected": 5\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/groups/resetTraffic',
summary: 'Reset only the group-level traffic counter shown on the groups page. Snapshots the current up/down sum of the group\'s members as a baseline so the group total reads zero, while leaving each client\'s own counters (and their quotas) untouched. No Xray restart is triggered. Creates the client_groups row if the group exists only as a derived label.',
body: '{\n "name": "customer-a"\n}',
response: '{\n "success": true,\n "obj": {\n "name": "customer-a"\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/resetTraffic/:email',
@@ -936,8 +995,8 @@ export const sections: readonly Section[] = [
{
method: 'POST',
path: '/panel/api/nodes/updatePanel',
summary: 'Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Returns a per-node result list.',
body: '{\n "ids": [1, 2, 3]\n}',
summary: 'Trigger the official panel self-updater on each given node (downloads the latest release and restarts). Only enabled, online nodes are updated; offline/disabled ones are reported as skipped. Set "dev": true to move the nodes to the rolling per-commit dev channel instead of the latest stable release. Returns a per-node result list.',
body: '{\n "ids": [1, 2, 3],\n "dev": false\n}',
response: '{\n "success": true,\n "obj": [\n { "id": 1, "name": "de-1", "ok": true },\n { "id": 2, "name": "fr-1", "ok": false, "error": "node is offline" }\n ]\n}',
},
{
@@ -81,7 +81,7 @@ export default function BulkAttachInboundsModal({
{t('pages.clients.attachToInboundsDesc', { count })}
</Typography.Paragraph>
{targetOptions.length === 0 ? (
<Alert type="info" showIcon message={t('pages.clients.attachToInboundsNoTargets')} />
<Alert type="info" showIcon title={t('pages.clients.attachToInboundsNoTargets')} />
) : (
<>
<SelectAllClearButtons
@@ -81,7 +81,7 @@ export default function BulkDetachInboundsModal({
{t('pages.clients.detachFromInboundsDesc', { count })}
</Typography.Paragraph>
{targetOptions.length === 0 ? (
<Alert type="info" showIcon message={t('pages.clients.detachFromInboundsNoTargets')} />
<Alert type="info" showIcon title={t('pages.clients.detachFromInboundsNoTargets')} />
) : (
<>
<SelectAllClearButtons
@@ -16,7 +16,7 @@ import { ClientBulkAddFormSchema, type ClientBulkAddFormValues } from '@/schemas
const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
const MULTI_CLIENT_PROTOCOLS = new Set([
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria',
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria', 'wireguard',
]);
interface ClientBulkAddModalProps {
@@ -280,6 +280,7 @@ export default function ClientBulkAddModal({
style={{ flex: 1 }}
/>
<Button
aria-label={t('regenerate')}
icon={<ReloadOutlined />}
onClick={() => update('subId', RandomUtil.randomLowerAndNum(16))}
/>
@@ -1,16 +1,19 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Form, InputNumber, Modal, message } from 'antd';
import { Alert, Form, InputNumber, Modal, Select, message } from 'antd';
import { ClientBulkAdjustFormSchema } from '@/schemas/client';
import { TLS_FLOW_CONTROL } from '@/schemas/primitives/flow';
const GB = 1024 * 1024 * 1024;
const FLOW_CLEAR = 'none';
interface ClientBulkAdjustModalProps {
open: boolean;
count: number;
onOpenChange: (open: boolean) => void;
onSubmit: (addDays: number, addBytes: number) => Promise<{ adjusted: number; skipped?: { email: string; reason: string }[] } | null>;
onSubmit: (addDays: number, addBytes: number, flow: string) => Promise<{ adjusted: number; skipped?: { email: string; reason: string }[] } | null>;
}
export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSubmit }: ClientBulkAdjustModalProps) {
@@ -18,12 +21,14 @@ export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSub
const [messageApi, messageContextHolder] = message.useMessage();
const [addDays, setAddDays] = useState<number>(0);
const [addGB, setAddGB] = useState<number>(0);
const [flow, setFlow] = useState<string>('');
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (open) {
setAddDays(0);
setAddGB(0);
setFlow('');
}
}, [open]);
@@ -31,16 +36,17 @@ export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSub
const validated = ClientBulkAdjustFormSchema.safeParse({
addDays: Math.trunc(Number(addDays) || 0),
addGB: Number(addGB) || 0,
flow,
});
if (!validated.success) {
messageApi.warning(t(validated.error.issues[0]?.message ?? 'somethingWentWrong'));
return;
}
const { addDays: days, addGB: gb } = validated.data;
const { addDays: days, addGB: gb, flow: flowValue } = validated.data;
setSubmitting(true);
try {
const bytes = Math.trunc(gb * GB);
const result = await onSubmit(days, bytes);
const result = await onSubmit(days, bytes, flowValue);
if (!result) return;
const ok = result.adjusted ?? 0;
const skipped = result.skipped?.length ?? 0;
@@ -95,6 +101,18 @@ export default function ClientBulkAdjustModal({ open, count, onOpenChange, onSub
step={1}
/>
</Form.Item>
<Form.Item label={t('pages.clients.bulkFlow')}>
<Select
value={flow}
onChange={setFlow}
style={{ width: '100%' }}
options={[
{ value: '', label: t('pages.clients.bulkFlowNoChange') },
{ value: FLOW_CLEAR, label: t('pages.clients.bulkFlowDisable') },
...Object.values(TLS_FLOW_CONTROL).map((k) => ({ value: k, label: k })),
]}
/>
</Form.Item>
</Form>
</Modal>
</>
+86 -11
View File
@@ -22,7 +22,7 @@ import {
import { DeleteOutlined, EyeOutlined, PlusOutlined, ReloadOutlined, RetweetOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { HttpUtil, RandomUtil } from '@/utils';
import { HttpUtil, RandomUtil, Wireguard } from '@/utils';
import { formatInboundLabel } from '@/lib/inbounds/label';
import { normalizeClientIps, type ClientIpInfo } from '@/lib/clients/ip-log';
import { DateTimePicker, SelectAllClearButtons } from '@/components/form';
@@ -35,7 +35,7 @@ const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
const VMESS_SECURITY_OPTIONS = ['auto', 'aes-128-gcm', 'chacha20-poly1305', 'none', 'zero'] as const;
const MULTI_CLIENT_PROTOCOLS = new Set([
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria',
'shadowsocks', 'vless', 'vmess', 'trojan', 'hysteria', 'wireguard',
]);
const CLIENT_FORM_MODAL_Z_INDEX = 1000;
@@ -113,6 +113,10 @@ interface FormState {
enable: boolean;
inboundIds: number[];
externalLinks: ExternalLinkRow[];
wgPrivateKey: string;
wgPublicKey: string;
wgPreSharedKey: string;
wgAllowedIPs: string;
}
function emptyForm(): FormState {
@@ -137,6 +141,10 @@ function emptyForm(): FormState {
enable: true,
inboundIds: [],
externalLinks: [],
wgPrivateKey: '',
wgPublicKey: '',
wgPreSharedKey: '',
wgAllowedIPs: '',
};
}
@@ -237,6 +245,10 @@ export default function ClientFormModal({
enable: !!client.enable,
inboundIds: Array.isArray(attachedIds) ? [...attachedIds] : [],
externalLinks: toExternalLinkRows(attachedExternalLinks),
wgPrivateKey: client.privateKey || '',
wgPublicKey: client.publicKey || '',
wgPreSharedKey: client.preSharedKey || '',
wgAllowedIPs: client.allowedIPs || '',
};
if (et < 0) {
next.delayedStart = true;
@@ -250,6 +262,7 @@ export default function ClientFormModal({
setForm(next);
void loadIps();
} else {
const wgKeypair = Wireguard.generateKeypair();
setForm({
...emptyForm(),
email: RandomUtil.randomLowerAndNum(10),
@@ -257,6 +270,8 @@ export default function ClientFormModal({
subId: RandomUtil.randomLowerAndNum(16),
password: RandomUtil.randomLowerAndNum(16),
auth: RandomUtil.randomLowerAndNum(16),
wgPrivateKey: wgKeypair.privateKey,
wgPublicKey: wgKeypair.publicKey,
});
}
@@ -287,6 +302,14 @@ export default function ClientFormModal({
return ids;
}, [inbounds]);
const wireguardIds = useMemo(() => {
const ids = new Set<number>();
for (const row of inbounds || []) {
if (row && row.protocol === 'wireguard') ids.add(row.id);
}
return ids;
}, [inbounds]);
const ss2022Method = useMemo(() => {
for (const id of form.inboundIds || []) {
const ib = (inbounds || []).find((row) => row.id === id);
@@ -317,6 +340,16 @@ export default function ClientFormModal({
[form.inboundIds, vmessIds],
);
const showWireguard = useMemo(
() => (form.inboundIds || []).some((id) => wireguardIds.has(id)),
[form.inboundIds, wireguardIds],
);
function regenerateWireguardKeys() {
const kp = Wireguard.generateKeypair();
setForm((prev) => ({ ...prev, wgPrivateKey: kp.privateKey, wgPublicKey: kp.publicKey }));
}
useEffect(() => {
if (!showFlow && form.flow) {
@@ -453,6 +486,14 @@ export default function ClientFormModal({
clientPayload.reverse = { tag: reverseTag };
}
if (showWireguard) {
clientPayload.privateKey = form.wgPrivateKey;
clientPayload.publicKey = form.wgPublicKey;
if (form.wgPreSharedKey) {
clientPayload.preSharedKey = form.wgPreSharedKey;
}
}
const externalLinks: ExternalLinkInput[] = form.externalLinks
.map((r) => ({ kind: r.kind, value: r.value.trim(), remark: '' }))
.filter((r) => r.value !== '');
@@ -541,7 +582,7 @@ export default function ClientFormModal({
onChange={(e) => update('email', e.target.value)}
/>
{!isEdit && (
<Button icon={<ReloadOutlined />} onClick={() => update('email', RandomUtil.randomLowerAndNum(12))} />
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={() => update('email', RandomUtil.randomLowerAndNum(12))} />
)}
</Space.Compact>
</Form.Item>
@@ -562,7 +603,7 @@ export default function ClientFormModal({
onChange={(v) => update('limitIp', Number(v) || 0)} />
{isEdit && (
<Tooltip title={t('pages.clients.ipLog')}>
<Button icon={<EyeOutlined />} loading={ipsLoading} onClick={openIpsModal}>
<Button aria-label={t('pages.clients.ipLog')} icon={<EyeOutlined />} loading={ipsLoading} onClick={openIpsModal}>
{clientIps.length > 0 ? clientIps.length : ''}
</Button>
</Tooltip>
@@ -676,7 +717,7 @@ export default function ClientFormModal({
</Form.Item>
<Form.Item>
<Switch checked={form.enable} onChange={(v) => update('enable', v)} />
<Switch aria-label={t('enable')} checked={form.enable} onChange={(v) => update('enable', v)} />
<span style={{ marginLeft: 8 }}>{t('enable')}</span>
</Form.Item>
</>
@@ -690,28 +731,28 @@ export default function ClientFormModal({
<Form.Item label={t('pages.clients.uuid')}>
<Space.Compact style={{ display: 'flex' }}>
<Input value={form.uuid} style={{ flex: 1 }} onChange={(e) => update('uuid', e.target.value)} />
<Button icon={<ReloadOutlined />} onClick={() => update('uuid', RandomUtil.randomUUID())} />
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={() => update('uuid', RandomUtil.randomUUID())} />
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.password')}>
<Space.Compact style={{ display: 'flex' }}>
<Input value={form.password} style={{ flex: 1 }} onChange={(e) => update('password', e.target.value)} />
<Button icon={<ReloadOutlined />} onClick={regeneratePassword} />
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={regeneratePassword} />
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.subId')}>
<Space.Compact style={{ display: 'flex' }}>
<Input value={form.subId} style={{ flex: 1 }} onChange={(e) => update('subId', e.target.value)} />
<Button icon={<ReloadOutlined />} onClick={() => update('subId', RandomUtil.randomLowerAndNum(16))} />
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={() => update('subId', RandomUtil.randomLowerAndNum(16))} />
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.hysteriaAuth')}>
<Space.Compact style={{ display: 'flex' }}>
<Input value={form.auth} style={{ flex: 1 }} onChange={(e) => update('auth', e.target.value)} />
<Button icon={<ReloadOutlined />} onClick={() => update('auth', RandomUtil.randomLowerAndNum(16))} />
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={() => update('auth', RandomUtil.randomLowerAndNum(16))} />
</Space.Compact>
</Form.Item>
@@ -736,6 +777,38 @@ export default function ClientFormModal({
/>
</Form.Item>
)}
{showWireguard && (
<>
<Form.Item label={t('pages.clients.wireguardPrivateKey')}>
<Space.Compact style={{ display: 'flex' }}>
<Input
value={form.wgPrivateKey}
style={{ flex: 1 }}
onChange={(e) => {
const priv = e.target.value;
update('wgPrivateKey', priv);
update('wgPublicKey', priv ? Wireguard.generateKeypair(priv).publicKey : '');
}}
/>
<Button aria-label={t('regenerate')} icon={<ReloadOutlined />} onClick={regenerateWireguardKeys} />
</Space.Compact>
</Form.Item>
<Form.Item label={t('pages.clients.wireguardPublicKey')}>
<Input value={form.wgPublicKey} disabled />
</Form.Item>
<Form.Item label={t('pages.clients.wireguardPreSharedKey')}>
<Input
value={form.wgPreSharedKey}
onChange={(e) => update('wgPreSharedKey', e.target.value)}
/>
</Form.Item>
{isEdit && form.wgAllowedIPs && (
<Form.Item label={t('pages.clients.wireguardAllowedIPs')}>
<Input value={form.wgAllowedIPs} disabled />
</Form.Item>
)}
</>
)}
</>
),
},
@@ -758,11 +831,12 @@ export default function ClientFormModal({
<div key={row.key} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<Input
value={row.value}
aria-label="vless:// · vmess:// · trojan:// · ss:// · hysteria2:// · wireguard://"
onChange={(e) => updateExternalLinkRow(row.key, e.target.value)}
placeholder="vless:// · vmess:// · trojan:// · ss:// · hysteria2:// · wireguard://"
/>
<Tooltip title={t('delete')}>
<Button danger icon={<DeleteOutlined />} onClick={() => removeExternalLinkRow(row.key)} />
<Button aria-label={t('delete')} danger icon={<DeleteOutlined />} onClick={() => removeExternalLinkRow(row.key)} />
</Tooltip>
</div>
))}
@@ -778,11 +852,12 @@ export default function ClientFormModal({
<div key={row.key} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<Input
value={row.value}
aria-label="https://provider.example/sub/…"
onChange={(e) => updateExternalLinkRow(row.key, e.target.value)}
placeholder="https://provider.example/sub/…"
/>
<Tooltip title={t('delete')}>
<Button danger icon={<DeleteOutlined />} onClick={() => removeExternalLinkRow(row.key)} />
<Button aria-label={t('delete')} danger icon={<DeleteOutlined />} onClick={() => removeExternalLinkRow(row.key)} />
</Tooltip>
</div>
))}
+70 -49
View File
@@ -11,6 +11,8 @@ import type { ClientRecord, InboundOption } from '@/hooks/useClients';
import { isPostQuantumLink } from '@/lib/xray/inbound-link';
import { LinkTags, linkMetaText, parseLinkParts } from '@/lib/xray/link-label';
import { QrPanel } from '@/pages/inbounds/qr';
import ConfigBlock from '@/components/clients/ConfigBlock';
import { buildWireguardClientConfig, findWireguardInbound, isWireguardClient } from './wireguardConfig';
import './ClientInfoModal.css';
const INBOUND_PROTOCOL_COLORS: Record<string, string> = {
@@ -35,6 +37,7 @@ interface SubSettings {
subJsonEnable: boolean;
subClashURI: string;
subClashEnable: boolean;
publicHost?: string;
}
interface ClientInfoModalProps {
@@ -58,6 +61,7 @@ const DEFAULT_SUB: SubSettings = {
subJsonEnable: false,
subClashURI: '',
subClashEnable: false,
publicHost: '',
};
export default function ClientInfoModal({
@@ -132,6 +136,11 @@ export default function ClientInfoModal({
}, [client?.subId, subSettings?.subClashEnable, subSettings?.subClashURI]);
const showSubscription = !!(subSettings?.enable && client?.subId);
const wgInbound = useMemo(() => findWireguardInbound(client, inboundsById), [client, inboundsById]);
const wgConfigText = useMemo(() => {
if (!client || !wgInbound || !isWireguardClient(client)) return '';
return buildWireguardClientConfig(client, wgInbound, window.location.hostname, subSettings?.publicHost ?? '');
}, [client, wgInbound, subSettings?.publicHost]);
async function copyValue(text: string) {
if (!text) return;
@@ -211,7 +220,7 @@ export default function ClientInfoModal({
<td>
<Tag className="info-large-tag">{client.subId || '-'}</Tag>
{client.subId && (
<Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.subId!)} />
<Button size="small" type="text" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(client.subId!)} />
)}
</td>
</tr>
@@ -220,7 +229,7 @@ export default function ClientInfoModal({
<td>{t('pages.clients.uuid')}</td>
<td>
<Tag className="info-large-tag">{client.uuid}</Tag>
<Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.uuid!)} />
<Button size="small" type="text" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(client.uuid!)} />
</td>
</tr>
)}
@@ -229,7 +238,7 @@ export default function ClientInfoModal({
<td>{t('password')}</td>
<td>
<Tag className="info-large-tag">{client.password}</Tag>
<Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.password!)} />
<Button size="small" type="text" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(client.password!)} />
</td>
</tr>
)}
@@ -238,7 +247,7 @@ export default function ClientInfoModal({
<td>{t('pages.clients.auth')}</td>
<td>
<Tag className="info-large-tag">{client.auth}</Tag>
<Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copyValue(client.auth!)} />
<Button size="small" type="text" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(client.auth!)} />
</td>
</tr>
)}
@@ -286,7 +295,7 @@ export default function ClientInfoModal({
<tr>
<td>{t('pages.inbounds.IPLimitlog')}</td>
<td>
<Button size="small" icon={<EyeOutlined />} loading={ipsLoading} onClick={openIpsModal}>
<Button size="small" icon={<EyeOutlined />} aria-label={t('pages.clients.ipLog')} loading={ipsLoading} onClick={openIpsModal}>
{clientIps.length > 0 ? clientIps.length : ''}
</Button>
</td>
@@ -350,44 +359,6 @@ export default function ClientInfoModal({
</tbody>
</table>
{links.length > 0 && (
<>
<Divider>{t('pages.inbounds.copyLink')}</Divider>
{links.map((link, idx) => {
const parts = parseLinkParts(link);
const fallback = `${t('pages.clients.link')} ${idx + 1}`;
const rowTitle = (parts && linkMetaText(parts)) || fallback;
const qrRemark = [parts?.remark, client.email].filter(Boolean).join('-') || rowTitle;
const canQr = !isPostQuantumLink(link);
return (
<div key={idx} className="link-row">
{parts
? <LinkTags parts={parts} />
: <Tag className="link-row-tag">LINK</Tag>}
<span className="link-row-title" title={rowTitle}>{rowTitle}</span>
<div className="link-row-actions">
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(link)} />
</Tooltip>
{canQr && (
<Popover
trigger="click"
placement="left"
destroyOnHidden
content={<QrPanel value={link} remark={qrRemark} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" icon={<QrcodeOutlined />} />
</Tooltip>
</Popover>
)}
</div>
</div>
);
})}
</>
)}
{showSubscription && subLink && (
<>
<Divider>{t('subscription.title')}</Divider>
@@ -404,7 +375,7 @@ export default function ClientInfoModal({
</a>
<div className="link-row-actions">
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(subLink)} />
<Button size="small" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(subLink)} />
</Tooltip>
<Popover
trigger="click"
@@ -413,7 +384,7 @@ export default function ClientInfoModal({
content={<QrPanel value={subLink} remark={`${client.email}${t('subscription.title')}`} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" icon={<QrcodeOutlined />} />
<Button size="small" icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} />
</Tooltip>
</Popover>
</div>
@@ -432,7 +403,7 @@ export default function ClientInfoModal({
</a>
<div className="link-row-actions">
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(subJsonLink)} />
<Button size="small" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(subJsonLink)} />
</Tooltip>
<Popover
trigger="click"
@@ -441,7 +412,7 @@ export default function ClientInfoModal({
content={<QrPanel value={subJsonLink} remark={`${client.email} — JSON`} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" icon={<QrcodeOutlined />} />
<Button size="small" icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} />
</Tooltip>
</Popover>
</div>
@@ -463,7 +434,7 @@ export default function ClientInfoModal({
</a>
<div className="link-row-actions">
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} onClick={() => copyValue(subClashLink)} />
<Button size="small" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(subClashLink)} />
</Tooltip>
<Popover
trigger="click"
@@ -472,7 +443,7 @@ export default function ClientInfoModal({
content={<QrPanel value={subClashLink} remark={`${client.email} — Clash / Mihomo`} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" icon={<QrcodeOutlined />} />
<Button size="small" icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} />
</Tooltip>
</Popover>
</div>
@@ -480,6 +451,56 @@ export default function ClientInfoModal({
)}
</>
)}
{links.length > 0 && (
<>
<Divider>{t('pages.inbounds.copyLink')}</Divider>
{links.map((link, idx) => {
const parts = parseLinkParts(link);
const fallback = `${t('pages.clients.link')} ${idx + 1}`;
const rowTitle = (parts && linkMetaText(parts)) || fallback;
const qrRemark = parts?.remark || rowTitle;
const canQr = !isPostQuantumLink(link);
return (
<div key={idx} className="link-row">
{parts
? <LinkTags parts={parts} />
: <Tag className="link-row-tag">LINK</Tag>}
<span className="link-row-title" title={rowTitle}>{rowTitle}</span>
<div className="link-row-actions">
<Tooltip title={t('copy')}>
<Button size="small" icon={<CopyOutlined />} aria-label={t('copy')} onClick={() => copyValue(link)} />
</Tooltip>
{canQr && (
<Popover
trigger="click"
placement="left"
destroyOnHidden
content={<QrPanel value={link} remark={qrRemark} size={220} />}
>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} />
</Tooltip>
</Popover>
)}
</div>
</div>
);
})}
</>
)}
{wgConfigText && client && (
<>
<Divider>{t('pages.clients.wireguardConfig')}</Divider>
<ConfigBlock
label={t('pages.clients.config')}
text={wgConfigText}
fileName={`${client.email}.conf`}
qrRemark={client.email || 'peer'}
/>
</>
)}
</>
)}
</Modal>
+29 -6
View File
@@ -1,22 +1,25 @@
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Collapse, Modal, Spin } from 'antd';
import { Collapse, Modal, Spin, Tag } from 'antd';
import { HttpUtil } from '@/utils';
import { isPostQuantumLink } from '@/lib/xray/inbound-link';
import { LinkTags, linkMetaText, parseLinkParts } from '@/lib/xray/link-label';
import { QrPanel } from '@/pages/inbounds/qr';
import type { ClientRecord } from '@/hooks/useClients';
import type { ClientRecord, InboundOption } from '@/hooks/useClients';
import { buildWireguardClientConfig, findWireguardInbound, isWireguardClient } from './wireguardConfig';
interface SubSettings {
enable: boolean;
subURI: string;
subJsonURI: string;
subJsonEnable: boolean;
publicHost?: string;
}
interface ClientQrModalProps {
open: boolean;
client: ClientRecord | null;
inboundsById: Record<number, InboundOption>;
subSettings?: SubSettings;
onOpenChange: (open: boolean) => void;
}
@@ -26,11 +29,12 @@ interface ApiMsg<T = unknown> {
obj?: T;
}
const DEFAULT_SUB: SubSettings = { enable: false, subURI: '', subJsonURI: '', subJsonEnable: false };
const DEFAULT_SUB: SubSettings = { enable: false, subURI: '', subJsonURI: '', subJsonEnable: false, publicHost: '' };
export default function ClientQrModal({
open,
client,
inboundsById,
subSettings = DEFAULT_SUB,
onOpenChange,
}: ClientQrModalProps) {
@@ -49,7 +53,13 @@ export default function ClientQrModal({
return subSettings.subJsonURI + client.subId;
}, [client?.subId, subSettings?.enable, subSettings?.subJsonEnable, subSettings?.subJsonURI]);
const hasAnything = !!subLink || !!subJsonLink || links.length > 0;
const wgInbound = useMemo(() => findWireguardInbound(client, inboundsById), [client, inboundsById]);
const wgConfigText = useMemo(() => {
if (!client || !wgInbound || !isWireguardClient(client)) return '';
return buildWireguardClientConfig(client, wgInbound, window.location.hostname, subSettings?.publicHost ?? '');
}, [client, wgInbound, subSettings?.publicHost]);
const hasAnything = !!subLink || !!subJsonLink || !!wgConfigText || links.length > 0;
useEffect(() => {
if (!open || !client?.subId) {
@@ -106,14 +116,27 @@ export default function ClientQrModal({
children: (
<QrPanel
value={link}
remark={`${client?.email || ''} #${idx + 1}`}
remark={parts?.remark || `${client?.email || ''} #${idx + 1}`}
showQr={!isPostQuantumLink(link)}
/>
),
});
});
if (wgConfigText) {
out.push({
key: 'wg-config',
label: <Tag color="cyan" style={{ margin: 0 }}>{t('pages.clients.wireguardConfig')}</Tag>,
children: (
<QrPanel
value={wgConfigText}
remark={client?.email || 'peer'}
downloadName={`${client?.email || 'peer'}.conf`}
/>
),
});
}
return out;
}, [subLink, subJsonLink, links, client?.email, t]);
}, [subLink, subJsonLink, wgConfigText, links, client?.email, t]);
useEffect(() => {
if (!open) {
+110 -38
View File
@@ -27,6 +27,7 @@ import {
} from 'antd';
import type { ColumnsType, TableProps } from 'antd/es/table';
import {
CheckCircleOutlined,
ClockCircleOutlined,
DeleteOutlined,
DisconnectOutlined,
@@ -42,12 +43,14 @@ import {
RetweetOutlined,
SearchOutlined,
SortAscendingOutlined,
StopOutlined,
TagsOutlined,
TeamOutlined,
UploadOutlined,
UsergroupAddOutlined,
UsergroupDeleteOutlined,
} from '@ant-design/icons';
import { activateOnKey } from '@/utils/a11y';
import { useTheme } from '@/hooks/useTheme';
import { formatInboundLabel } from '@/lib/inbounds/label';
@@ -204,7 +207,7 @@ export default function ClientsPage() {
setQuery,
inbounds, onlines, loading, transitioning, fetched, fetchError, subSettings,
tgBotEnable, expireDiff, trafficDiff, pageSize,
create, update, remove, bulkDelete, bulkAdjust, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach,
create, update, remove, bulkDelete, bulkAdjust, bulkEnable, bulkDisable, bulkAddToGroup, bulkRemoveFromGroup, attach, setExternalLinks, bulkAttach, detach, bulkDetach,
resetTraffic, resetAllTraffics, delDepleted, delOrphans, exportClients, importClients, setEnable,
applyTrafficEvent, applyClientStatsEvent,
refresh,
@@ -641,6 +644,35 @@ export default function ClientsPage() {
});
}
function onBulkSetEnable(enable: boolean) {
const emails = [...selectedRowKeys];
if (emails.length === 0) return;
modal.confirm({
title: t(enable ? 'pages.clients.bulkEnableConfirmTitle' : 'pages.clients.bulkDisableConfirmTitle', { count: emails.length }),
content: t(enable ? 'pages.clients.bulkEnableConfirmContent' : 'pages.clients.bulkDisableConfirmContent'),
okText: t('confirm'),
okType: enable ? 'primary' : 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = enable ? await bulkEnable(emails) : await bulkDisable(emails);
setSelectedRowKeys([]);
const changed = msg?.obj?.changed ?? 0;
const skipped = msg?.obj?.skipped ?? [];
const failed = skipped.length;
const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
const okKey = enable ? 'pages.clients.toasts.bulkEnabled' : 'pages.clients.toasts.bulkDisabled';
const mixedKey = enable ? 'pages.clients.toasts.bulkEnabledMixed' : 'pages.clients.toasts.bulkDisabledMixed';
if (failed === 0 && msg?.success) {
messageApi.success(t(okKey, { count: changed }));
} else {
messageApi.warning(firstError
? `${t(mixedKey, { ok: changed, failed })} — ${firstError}`
: t(mixedKey, { ok: changed, failed }));
}
},
});
}
function onBulkDelete() {
const emails = [...selectedRowKeys];
if (emails.length === 0) return;
@@ -685,16 +717,18 @@ export default function ClientsPage() {
}
const updateMsg = await update(meta.email, payload);
if (!updateMsg?.success) return updateMsg;
const rawEmail = (payload as { email?: unknown }).email;
const emailKey = typeof rawEmail === 'string' && rawEmail.trim() ? rawEmail.trim() : meta.email;
if (Array.isArray(meta.attach) && meta.attach.length > 0) {
const r = await attach(meta.email, meta.attach);
const r = await attach(emailKey, meta.attach);
if (!r?.success) return r;
}
if (Array.isArray(meta.detach) && meta.detach.length > 0) {
const r = await detach(meta.email, meta.detach);
const r = await detach(emailKey, meta.detach);
if (!r?.success) return r;
}
// Always replace the client's external links (an empty set clears them).
const r = await setExternalLinks(meta.email, meta.externalLinks);
const r = await setExternalLinks(emailKey, meta.externalLinks);
if (!r?.success) return r;
return updateMsg;
}, [create, update, attach, detach, setExternalLinks]);
@@ -719,19 +753,19 @@ export default function ClientsPage() {
render: (_v, record) => (
<Space size={4}>
<Tooltip title={t('pages.clients.qrCode')}>
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<QrcodeOutlined />} onClick={() => onShowQr(record)} />
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<QrcodeOutlined />} aria-label={t('pages.clients.qrCode')} onClick={() => onShowQr(record)} />
</Tooltip>
<Tooltip title={t('pages.clients.clientInfo')}>
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<InfoCircleOutlined />} onClick={() => onShowInfo(record)} />
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<InfoCircleOutlined />} aria-label={t('pages.clients.clientInfo')} onClick={() => onShowInfo(record)} />
</Tooltip>
<Tooltip title={t('pages.inbounds.resetTraffic')}>
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<RetweetOutlined />} onClick={() => onResetTraffic(record)} />
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<RetweetOutlined />} aria-label={t('pages.inbounds.resetTraffic')} onClick={() => onResetTraffic(record)} />
</Tooltip>
<Tooltip title={t('edit')}>
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<EditOutlined />} onClick={() => onEdit(record)} />
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<EditOutlined />} aria-label={t('edit')} onClick={() => onEdit(record)} />
</Tooltip>
<Tooltip title={t('delete')}>
<Button size="small" type="text" danger style={{ fontSize: 16 }} icon={<DeleteOutlined />} onClick={() => onDelete(record)} />
<Button size="small" type="text" danger style={{ fontSize: 16 }} icon={<DeleteOutlined />} aria-label={t('delete')} onClick={() => onDelete(record)} />
</Tooltip>
</Space>
),
@@ -1006,32 +1040,18 @@ export default function ClientsPage() {
title={
<div className="card-toolbar">
{selectedRowKeys.length === 0 ? (
<Button type="primary" icon={<PlusOutlined />} onClick={onAdd}>
<Button type="primary" icon={<PlusOutlined />} onClick={onAdd} aria-label={t('pages.clients.addClients')}>
{!isMobile && t('pages.clients.addClients')}
</Button>
) : (
<>
<Tag
color="blue"
closable
onClose={() => setSelectedRowKeys([])}
style={{ marginInlineEnd: 0, padding: '4px 8px', fontSize: 13 }}
>
{t('pages.clients.selectedCount', { count: selectedRowKeys.length })}
</Tag>
<Button icon={<UsergroupAddOutlined />} onClick={() => setBulkAttachOpen(true)}>
{!isMobile && t('pages.clients.attach')}
</Button>
<Button danger icon={<UsergroupDeleteOutlined />} onClick={() => setBulkDetachOpen(true)}>
{!isMobile && t('pages.clients.detach')}
</Button>
<Button icon={<TagsOutlined />} onClick={() => setBulkGroupOpen(true)}>
{!isMobile && t('pages.clients.addToGroup')}
</Button>
<Button danger icon={<UngroupIcon />} onClick={onBulkUngroup}>
{!isMobile && t('pages.clients.ungroup')}
</Button>
</>
<Tag
color="blue"
closable
onClose={() => setSelectedRowKeys([])}
style={{ marginInlineEnd: 0, padding: '4px 8px', fontSize: 13 }}
>
{t('pages.clients.selectedCount', { count: selectedRowKeys.length })}
</Tag>
)}
<Dropdown
trigger={['click']}
@@ -1039,6 +1059,46 @@ export default function ClientsPage() {
menu={{
items: selectedRowKeys.length > 0
? [
{
key: 'attach',
icon: <UsergroupAddOutlined />,
label: t('pages.clients.attach'),
onClick: () => setBulkAttachOpen(true),
},
{
key: 'detach',
icon: <UsergroupDeleteOutlined />,
label: t('pages.clients.detach'),
danger: true,
onClick: () => setBulkDetachOpen(true),
},
{
key: 'addToGroup',
icon: <TagsOutlined />,
label: t('pages.clients.addToGroup'),
onClick: () => setBulkGroupOpen(true),
},
{
key: 'ungroup',
icon: <UngroupIcon />,
label: t('pages.clients.ungroup'),
danger: true,
onClick: onBulkUngroup,
},
{ type: 'divider' as const },
{
key: 'enable',
icon: <CheckCircleOutlined />,
label: t('pages.clients.enable'),
onClick: () => onBulkSetEnable(true),
},
{
key: 'disable',
icon: <StopOutlined />,
label: t('pages.clients.disable'),
danger: true,
onClick: () => onBulkSetEnable(false),
},
{
key: 'adjust',
icon: <ClockCircleOutlined />,
@@ -1095,7 +1155,7 @@ export default function ClientsPage() {
],
}}
>
<Button icon={<MoreOutlined />}>
<Button icon={<MoreOutlined />} aria-label={t('more')}>
{!isMobile && t('more')}
</Button>
</Dropdown>
@@ -1105,6 +1165,7 @@ export default function ClientsPage() {
icon={<DeleteOutlined />}
onClick={onBulkDelete}
style={{ marginInlineStart: 'auto' }}
aria-label={t('delete')}
>
{!isMobile && t('delete')}
</Button>
@@ -1121,6 +1182,7 @@ export default function ClientsPage() {
prefix={<SearchOutlined />}
size={isMobile ? 'small' : 'middle'}
style={{ maxWidth: 320 }}
aria-label={t('search')}
/>
<Badge count={activeCount} size="small" offset={[-4, 4]}>
<Button
@@ -1128,12 +1190,14 @@ export default function ClientsPage() {
size={isMobile ? 'small' : 'middle'}
onClick={() => setFilterDrawerOpen(true)}
type={activeCount > 0 ? 'primary' : 'default'}
aria-label={t('filter')}
>
{!isMobile && t('filter')}
</Button>
</Badge>
<Select
value={sortValueFor(sortColumn, sortOrder)}
aria-label={t('sort')}
size={isMobile ? 'small' : 'middle'}
suffixIcon={<SortAscendingOutlined />}
style={{ minWidth: isMobile ? 130 : 200 }}
@@ -1306,9 +1370,16 @@ export default function ClientsPage() {
<span className="tag-name">{row.email}</span>
{bucket === 'depleted' && <Tag color="red" className="status-tag">{t('depleted')}</Tag>}
{bucket === 'expiring' && <Tag color="orange" className="status-tag">{t('depletingSoon')}</Tag>}
<div className="card-actions" onClick={(e) => e.stopPropagation()}>
<div className="card-actions">
<Tooltip title={t('pages.clients.clientInfo')}>
<InfoCircleOutlined className="row-action-trigger" onClick={() => onShowInfo(row)} />
<InfoCircleOutlined
className="row-action-trigger"
role="button"
tabIndex={0}
aria-label={t('pages.clients.clientInfo')}
onClick={() => onShowInfo(row)}
onKeyDown={activateOnKey(() => onShowInfo(row))}
/>
</Tooltip>
<Switch
checked={!!row.enable}
@@ -1345,7 +1416,7 @@ export default function ClientsPage() {
],
}}
>
<MoreOutlined className="row-action-trigger" />
<Button type="text" size="small" className="row-action-trigger" icon={<MoreOutlined />} aria-label={t('more')} />
</Dropdown>
</div>
</div>
@@ -1400,6 +1471,7 @@ export default function ClientsPage() {
<ClientQrModal
open={qrOpen}
client={qrClient}
inboundsById={inboundsById}
subSettings={subSettings}
onOpenChange={setQrOpen}
/>
@@ -1418,8 +1490,8 @@ export default function ClientsPage() {
open={bulkAdjustOpen}
count={selectedRowKeys.length}
onOpenChange={setBulkAdjustOpen}
onSubmit={async (addDays, addBytes) => {
const msg = await bulkAdjust([...selectedRowKeys], addDays, addBytes);
onSubmit={async (addDays, addBytes, flow) => {
const msg = await bulkAdjust([...selectedRowKeys], addDays, addBytes, flow);
if (msg?.success) {
setSelectedRowKeys([]);
return msg.obj ?? { adjusted: 0 };
+1 -1
View File
@@ -111,7 +111,7 @@ export default function SubLinksModal({
key: 'actions',
width: 64,
render: (_v, row) => (
<Button size="small" type="text" icon={<CopyOutlined />} onClick={() => copy(row.link, t('copied'))} />
<Button size="small" type="text" aria-label={t('copy')} icon={<CopyOutlined />} onClick={() => copy(row.link, t('copied'))} />
),
},
];
@@ -0,0 +1,44 @@
import { formatInboundLabel } from '@/lib/inbounds/label';
import { preferPublicHost } from '@/lib/xray/inbound-link';
import type { ClientRecord, InboundOption } from '@/hooks/useClients';
export function isWireguardClient(client: ClientRecord | null | undefined): boolean {
if (!client) return false;
return !!(client.privateKey || client.publicKey || client.allowedIPs || client.preSharedKey || client.keepAlive);
}
export function findWireguardInbound(
client: ClientRecord | null | undefined,
inboundsById: Record<number, InboundOption>,
): InboundOption | undefined {
return (client?.inboundIds || [])
.map((id) => inboundsById[id])
.find((ib) => ib?.protocol === 'wireguard');
}
export function buildWireguardClientConfig(
client: ClientRecord,
inbound: InboundOption | undefined,
host = window.location.hostname,
publicHost = '',
): string {
const endpointHost = preferPublicHost(host, publicHost);
const address = client.allowedIPs || '10.0.0.2/32';
const endpoint = `${endpointHost}:${inbound?.port || ''}`;
const inboundName = inbound ? formatInboundLabel(inbound.tag, inbound.remark) : '';
const remark = [inboundName, client.email, client.comment].filter(Boolean).join(' - ');
const lines = [
'[Interface]',
`PrivateKey = ${client.privateKey || client.password || ''}`,
`Address = ${address}`,
`DNS = ${inbound?.wgDns || '1.1.1.1, 1.0.0.1'}`,
];
if (inbound?.wgMtu && inbound.wgMtu > 0) lines.push(`MTU = ${inbound.wgMtu}`);
lines.push('');
if (remark) lines.push(`# ${remark}`);
lines.push('[Peer]', `PublicKey = ${inbound?.wgPublicKey || ''}`);
if (client.preSharedKey) lines.push(`PresharedKey = ${client.preSharedKey}`);
lines.push('AllowedIPs = 0.0.0.0/0, ::/0', `Endpoint = ${endpoint}`);
if (client.keepAlive && client.keepAlive > 0) lines.push(`PersistentKeepalive = ${client.keepAlive}`);
return lines.join('\n');
}
@@ -139,7 +139,7 @@ export default function GroupAddClientsModal({
</Typography.Text>
</Space>
{rows.length === 0 ? (
<Alert type="info" showIcon message={t('pages.groups.addToGroupEmpty')} />
<Alert type="info" showIcon title={t('pages.groups.addToGroupEmpty')} />
) : (
<Table<ClientRow>
size="small"
+9 -12
View File
@@ -126,9 +126,9 @@ export default function GroupsPage() {
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const bulkResetMut = useMutation({
mutationFn: (body: { emails: string[] }) =>
HttpUtil.post('/panel/api/clients/bulkResetTraffic', body, JSON_HEADERS),
const groupResetMut = useMutation({
mutationFn: (body: { name: string }) =>
HttpUtil.post('/panel/api/clients/groups/resetTraffic', body, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
@@ -321,17 +321,14 @@ export default function GroupsPage() {
}
modal.confirm({
title: t('pages.groups.resetConfirmTitle', { name: g.name }),
content: t('pages.groups.resetConfirmContent', { count: g.clientCount }),
content: t('pages.groups.resetConfirmContent'),
okText: t('reset'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const emails = await fetchEmailsForGroup(g.name);
if (emails.length === 0) return;
const msg = await bulkResetMut.mutateAsync({ emails });
const msg = await groupResetMut.mutateAsync({ name: g.name });
if (msg?.success) {
const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? emails.length;
messageApi.success(t('pages.groups.resetSuccess', { count: affected }));
messageApi.success(t('pages.groups.resetSuccess', { name: g.name }));
}
},
});
@@ -407,10 +404,10 @@ export default function GroupsPage() {
render: (_v, row) => (
<Space size={4}>
<Dropdown trigger={['click']} menu={{ items: rowActions(row) }}>
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<MoreOutlined />} />
<Button aria-label={t('more')} size="small" type="text" style={{ fontSize: 16 }} icon={<MoreOutlined />} />
</Dropdown>
<Tooltip title={t('pages.groups.rename')}>
<Button size="small" type="text" style={{ fontSize: 16 }} icon={<EditOutlined />} onClick={() => openRename(row)} />
<Button aria-label={t('pages.groups.rename')} size="small" type="text" style={{ fontSize: 16 }} icon={<EditOutlined />} onClick={() => openRename(row)} />
</Tooltip>
</Space>
),
@@ -525,7 +522,7 @@ export default function GroupsPage() {
hoverable
title={
<div className="card-toolbar">
<Button type="primary" icon={<PlusOutlined />} onClick={openCreate}>
<Button aria-label={t('pages.groups.addGroup')} type="primary" icon={<PlusOutlined />} onClick={openCreate}>
{!isMobile && t('pages.groups.addGroup')}
</Button>
</div>
+1 -1
View File
@@ -260,7 +260,7 @@ export default function HostFormModal({ open, mode, host, inboundOptions, save,
<Input />
</Form.Item>
<Form.Item name="vlessRoute" label={t('pages.hosts.fields.vlessRoute')} tooltip={t('pages.hosts.hints.vlessRoute')}>
<Input placeholder="53,443,1000-2000" />
<Input placeholder="443" />
</Form.Item>
<Form.Item name="excludeFromSubTypes" label={t('pages.hosts.fields.excludeFromSubTypes')}>
<Select
+4 -4
View File
@@ -84,16 +84,16 @@ export default function HostList(props: HostListProps) {
return (
<Space size={2}>
<Tooltip title={t('pages.hosts.moveUp')}>
<Button size="small" type="text" icon={<ArrowUpOutlined />} disabled={idx === 0} onClick={() => onMove(h, 'up')} />
<Button size="small" type="text" icon={<ArrowUpOutlined />} aria-label={t('pages.hosts.moveUp')} disabled={idx === 0} onClick={() => onMove(h, 'up')} />
</Tooltip>
<Tooltip title={t('pages.hosts.moveDown')}>
<Button size="small" type="text" icon={<ArrowDownOutlined />} disabled={idx >= count - 1} onClick={() => onMove(h, 'down')} />
<Button size="small" type="text" icon={<ArrowDownOutlined />} aria-label={t('pages.hosts.moveDown')} disabled={idx >= count - 1} onClick={() => onMove(h, 'down')} />
</Tooltip>
<Tooltip title={t('edit')}>
<Button size="small" type="text" icon={<EditOutlined />} onClick={() => onEdit(h)} />
<Button size="small" type="text" icon={<EditOutlined />} aria-label={t('edit')} onClick={() => onEdit(h)} />
</Tooltip>
<Tooltip title={t('delete')}>
<Button size="small" type="text" danger icon={<DeleteOutlined />} onClick={() => onDelete(h)} />
<Button size="small" type="text" danger icon={<DeleteOutlined />} aria-label={t('delete')} onClick={() => onDelete(h)} />
</Tooltip>
</Space>
);
+4 -15
View File
@@ -292,21 +292,10 @@ export default function InboundsPage() {
}, [subSettings, openText, t]);
const exportAllLinks = useCallback(async () => {
const hydrated = await Promise.all(
dbInbounds.map((ib) => hydrateInbound(ib.id).then((r) => r ?? ib)),
);
const out: string[] = [];
for (const ib of hydrated) {
const projected = checkFallback(ib);
out.push(genInboundLinks({
inbound: inboundFromDb(projected),
remark: projected.remark,
hostOverride: hostOverrideFor(ib),
fallbackHostname: preferPublicHost(window.location.hostname, subSettings.publicHost),
}));
}
openText({ title: t('pages.inbounds.exportAllLinksTitle'), content: out.join('\r\n'), fileName: t('pages.inbounds.exportAllLinksFileName') });
}, [dbInbounds, hydrateInbound, checkFallback, hostOverrideFor, subSettings.publicHost, openText, t]);
const msg = await HttpUtil.get('/panel/api/inbounds/allLinks');
const links = msg?.success && Array.isArray(msg.obj) ? (msg.obj as string[]) : [];
openText({ title: t('pages.inbounds.exportAllLinksTitle'), content: links.join('\r\n'), fileName: t('pages.inbounds.exportAllLinksFileName') });
}, [openText, t]);
const exportAllSubs = useCallback(async () => {
const hydrated = await Promise.all(
@@ -164,6 +164,7 @@ export default function AttachClientsModal({
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
@@ -192,10 +193,11 @@ export default function AttachClientsModal({
</Space>
{targetOptions.length === 0 ? (
<Alert type="info" showIcon message={t('pages.inbounds.attachClientsNoTargets')} />
<Alert type="info" showIcon title={t('pages.inbounds.attachClientsNoTargets')} />
) : (
<Select
mode="multiple"
aria-label={t('pages.inbounds.attachClientsTargets')}
style={{ width: '100%' }}
value={targetIds}
onChange={setTargetIds}
@@ -180,7 +180,7 @@ export default function AttachExistingClientsModal({
</Typography.Paragraph>
{noClients ? (
<Alert type="info" showIcon message={t('pages.inbounds.attachExistingNoClients')} />
<Alert type="info" showIcon title={t('pages.inbounds.attachExistingNoClients')} />
) : (
<Spin spinning={loading}>
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
@@ -188,6 +188,7 @@ export default function AttachExistingClientsModal({
<Space wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
@@ -196,6 +197,7 @@ export default function AttachExistingClientsModal({
{groupOptions.length > 0 && (
<Select
allowClear
aria-label={t('pages.clients.group')}
value={groupFilter}
onChange={(v) => setGroupFilter(v)}
options={groupOptions}
@@ -152,6 +152,7 @@ export default function DetachClientsModal({
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
@@ -66,6 +66,7 @@ export default function FallbacksCard({
>
<Space.Compact block style={{ marginBottom: 8 }}>
<Select
aria-label={t('pages.inbounds.fallbacks.pickInbound')}
value={record.childId}
options={fallbackChildOptions}
placeholder={t('pages.inbounds.fallbacks.pickInbound') || 'Pick an inbound'}
@@ -78,23 +79,25 @@ export default function FallbacksCard({
onChange={(v) => updateFallback(record.rowKey, { childId: v ?? null })}
/>
<Button
aria-label={t('pages.inbounds.form.moveUp')}
disabled={idx === 0}
onClick={() => moveFallback(idx, -1)}
title={t('pages.inbounds.form.moveUp')}
icon={<ArrowUpOutlined />}
/>
<Button
aria-label={t('pages.inbounds.form.moveDown')}
disabled={idx === fallbacks.length - 1}
onClick={() => moveFallback(idx, 1)}
title={t('pages.inbounds.form.moveDown')}
icon={<ArrowDownOutlined />}
/>
<Button danger onClick={() => removeFallback(idx)} icon={<DeleteOutlined />} />
<Button aria-label={t('delete')} danger onClick={() => removeFallback(idx)} icon={<DeleteOutlined />} />
</Space.Compact>
<Row gutter={[8, 8]}>
<Col xs={24} sm={12}>
<Input
addonBefore="SNI"
prefix="SNI"
placeholder={t('pages.inbounds.fallbacks.matchAny') || 'any'}
value={record.name}
onChange={(e) => updateFallback(record.rowKey, { name: e.target.value })}
@@ -102,7 +105,7 @@ export default function FallbacksCard({
</Col>
<Col xs={24} sm={12}>
<Input
addonBefore="ALPN"
prefix="ALPN"
placeholder={t('pages.inbounds.fallbacks.matchAny') || 'any'}
value={record.alpn}
onChange={(e) => updateFallback(record.rowKey, { alpn: e.target.value })}
@@ -110,7 +113,7 @@ export default function FallbacksCard({
</Col>
<Col xs={24} sm={12}>
<Input
addonBefore="Path"
prefix="Path"
placeholder="/"
value={record.path}
onChange={(e) => updateFallback(record.rowKey, { path: e.target.value })}
@@ -118,7 +121,7 @@ export default function FallbacksCard({
</Col>
<Col xs={24} sm={12}>
<Input
addonBefore="Dest"
prefix="Dest"
placeholder={t('pages.inbounds.fallbacks.destPlaceholder') || 'auto'}
value={record.dest}
onChange={(e) => updateFallback(record.rowKey, { dest: e.target.value })}
@@ -126,7 +129,7 @@ export default function FallbacksCard({
</Col>
<Col xs={24} sm={12}>
<InputNumber
addonBefore="xver"
prefix="xver"
min={0}
max={2}
style={{ width: '100%' }}
@@ -17,6 +17,7 @@ import {
} from 'antd';
import { HttpUtil, NumberFormatter, RandomUtil, SizeFormatter, Wireguard } from '@/utils';
import type { RealityScanResult } from '@/generated/types';
import {
rawInboundToFormValues,
formValuesToWirePayload,
@@ -174,6 +175,8 @@ export default function InboundFormModal({
const [messageApi, messageContextHolder] = message.useMessage();
const [form] = Form.useForm<InboundFormValues>();
const [saving, setSaving] = useState(false);
const [scanning, setScanning] = useState(false);
const [scanResult, setScanResult] = useState<RealityScanResult | null>(null);
const {
fallbacks,
fallbackChildOptions,
@@ -241,7 +244,9 @@ export default function InboundFormModal({
clearRealityKeypair,
genMldsa65,
clearMldsa65,
randomizeRealityTarget,
scanRealityTarget,
scanRealityCandidates,
applyRealityScanResult,
randomizeShortIds,
getNewEchCert,
clearEchCert,
@@ -250,7 +255,7 @@ export default function InboundFormModal({
setCertFromPanel,
clearCertFiles,
onSecurityChange,
} = useSecurityActions({ form, setSaving, messageApi, nodeId: typeof wNodeId === 'number' ? wNodeId : null });
} = useSecurityActions({ form, setSaving, messageApi, nodeId: typeof wNodeId === 'number' ? wNodeId : null, setScanResult, setScanning });
const toggleSockopt = (on: boolean) => {
@@ -273,20 +278,18 @@ export default function InboundFormModal({
form.setFieldValue(['settings', 'secretKey'], kp.privateKey);
};
const regenWgPeerKeypair = (peerName: number) => {
const kp = Wireguard.generateKeypair();
form.setFieldValue(['settings', 'peers', peerName, 'privateKey'], kp.privateKey);
form.setFieldValue(['settings', 'peers', peerName, 'publicKey'], kp.publicKey);
};
const matchesVlessAuth = (
block: { id?: string; label?: string } | undefined | null,
authId: string,
) => {
if (block?.id === authId) return true;
const label = (block?.label || '').toLowerCase().replace(/[-_\s]/g, '');
if (authId === 'mlkem768') return label.includes('mlkem768');
if (authId === 'x25519') return label.includes('x25519');
if (authId === 'mlkem768') return label.includes('mlkem768') && !label.includes('xorpub') && !label.includes('random');
if (authId === 'x25519') return label.includes('x25519') && !label.includes('xorpub') && !label.includes('random');
if (authId === 'mlkem768_xorpub') return label.includes('mlkem768') && label.includes('xorpub');
if (authId === 'mlkem768_random') return label.includes('mlkem768') && label.includes('random');
if (authId === 'x25519_xorpub') return label.includes('x25519') && label.includes('xorpub');
if (authId === 'x25519_random') return label.includes('x25519') && label.includes('random');
return false;
};
@@ -319,7 +322,19 @@ export default function InboundFormModal({
const parts = enc.split('.').filter(Boolean);
const authKey = parts[parts.length - 1] || '';
if (!authKey) return t('pages.inbounds.vlessAuthCustom');
return authKey.length > 300
const mode = parts[1] || 'native';
const keyType = authKey.length > 300 ? 'mlkem768' : 'x25519';
if (mode === 'xorpub') {
return keyType === 'mlkem768'
? t('pages.inbounds.vlessAuthMlkem768Xorpub')
: t('pages.inbounds.vlessAuthX25519Xorpub');
}
if (mode === 'random') {
return keyType === 'mlkem768'
? t('pages.inbounds.vlessAuthMlkem768Random')
: t('pages.inbounds.vlessAuthX25519Random');
}
return keyType === 'mlkem768'
? t('pages.inbounds.vlessAuthMlkem768')
: t('pages.inbounds.vlessAuthX25519');
})();
@@ -331,6 +346,7 @@ export default function InboundFormModal({
: buildAddModeValues();
form.resetFields();
form.setFieldsValue(initial);
setScanResult(null);
const initialTag = (initial.tag ?? '') as string;
autoTagRef.current = isAutoInboundTag(initialTag, {
port: initial.port ?? 0,
@@ -673,7 +689,7 @@ export default function InboundFormModal({
const protocolTab = (
<>
{protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} regenWgPeerKeypair={regenWgPeerKeypair} />}
{protocol === Protocols.WIREGUARD && <WireguardFields wgPubKey={wgPubKey} regenInboundWg={regenInboundWg} />}
{protocol === Protocols.TUN && <TunFields />}
@@ -874,7 +890,11 @@ export default function InboundFormModal({
{security === 'reality' && (
<RealityForm
saving={saving}
randomizeRealityTarget={randomizeRealityTarget}
scanning={scanning}
scanResult={scanResult}
scanRealityTarget={scanRealityTarget}
scanRealityCandidates={scanRealityCandidates}
applyRealityScanResult={applyRealityScanResult}
randomizeShortIds={randomizeShortIds}
genRealityKeypair={genRealityKeypair}
clearRealityKeypair={clearRealityKeypair}

Some files were not shown because too many files have changed in this diff Show More