feat(hosts): managed Hosts for per-host subscription link overrides (#5409)

* test(sub): characterize current link output (externalProxy + single-link baselines)

Phase 0 of the Hosts feature. Locks current subscription-link output for the
externalProxy paths (vless/vmess/trojan/ss exact, reality/hysteria by Contains)
so the upcoming ShareEndpoint refactor can be proven behavior-preserving. These
must stay green and unedited through every later phase.

* refactor(sub): unify external-proxy link building behind ShareEndpoint (TDD, snapshot-locked)

Phase 1 of the Hosts feature. Collapse the duplicated externalProxy link
builders (param-form for vless/trojan/ss, object-form for vmess) onto a single
ShareEndpoint abstraction so Phase 4 can add Host-driven links with ~zero new
branching.

Design: an externalProxy-derived endpoint carries the original entry map and
applies it through the UNCHANGED applyExternalProxyTLS{Params,Obj} helpers, so
output is provably byte-identical. buildExternalProxyURLLinks /
buildVmessExternalProxyLinks become thin adapters; the genVless/Trojan/SS/Vmess
call sites are untouched. genHysteriaLink is deliberately left on its own path
(hex pinSHA256, not pcs). The no-externalProxy default tails are unchanged.

TDD: N1-N4 (externalProxyToEndpoint, inboundDefaultEndpoint, buildEndpointLinks,
buildEndpointVmessLinks) written failing-first against stubs, then implemented.

Mutation sanity (performed + reverted): dropping the ep-carry in
externalProxyToEndpoint makes the Phase-0 C1/C2 characterization snapshots go
red (TLS overrides vanish), proving the snapshots guard the emitted output.

Gate: go test ./internal/sub/... and go test ./... green with ZERO edits to the
Phase-0 snapshots; go build ./... green on linux and windows; go vet clean.

* feat(model): Host entity + automigrate + openapi codegen (TDD)

Phase 2 of the Hosts feature. Adds the Host GORM model: an override endpoint
attached to an inbound (address/port + TLS/transport/clash overrides + sub
scoping), superseding the legacy externalProxy array functionally while leaving
it intact.

- model.Host with snake_case column tags, json serializer for slices, text for
  free-JSON (mux/sockopt/xhttp), validate tags (remark 1-40, port 0-65535,
  security + mihomoIpVersion enums); TableName "hosts". NodeGuids column is added
  now but unused (host->node scoping deferred to v2).
- Registered in BOTH initModels() (db.go) and migrationModels() (migrate_data.go);
  the latter is required for cross-DB migration and is easy to miss. PG sequence
  resync iterates the initModels slice, so it is covered automatically.
- pruneOrphanedHosts() deletes hosts whose inbound_id has no inbound, called
  alongside pruneOrphanedClientInbounds().
- openapigen manifest: Host added to StructAllow with MuxParams/SockoptParams/
  XhttpExtraParams -> KindAny; regenerated frontend/src/generated/* + openapi.json.

TDD: TestHostTableName, TestHostValidation, TestHostAutoMigrateCreatesColumns
(+ _Postgres), TestPruneOrphanedHosts written failing-first against a wrong-name,
untagged, unregistered stub, then implemented.

Gate: go test ./... green on SQLite AND a real Postgres DSN (local container);
go build/vet/gofmt clean; npm run gen succeeds with the new Host type/schema/
example/zod; npm run typecheck + npm run test (542) green.

* feat(api): Host CRUD service + controller + routes (TDD)

Phase 3 of the Hosts feature.

- service/host.go (HostService, empty struct + database.GetDB() like
  ClientService): GetHosts, GetHostsByInbound, GetHost, AddHost (verifies the
  inbound exists — no hard FK), UpdateHost (inbound + sort order immutable here),
  DeleteHost, SetHostEnable, SetHostsEnable, DeleteHosts, ReorderHosts (single
  driver-safe transaction), GetAllTags.
- controller/host.go mirrors NodeController: routes under /panel/api/hosts
  (list/get/byInbound/tags + add/update/del/setEnable/reorder + bulk/setEnable,
  bulk/del), binds via middleware.BindAndValidate so the model validate tags are
  enforced, {success,msg,obj} envelopes.
- Wired the hosts group into api.go after nodes (inherits checkAPIAuth + CSRF).
- DelInbound now cascades: deleting an inbound deletes its hosts.
- Documented all 11 routes in api-docs endpoints.ts (referencing the generated
  Host schema) and regenerated openapi.json; extended TestAPIRoutesDocumented's
  controller->basePath switch for host.go. Backend en toast keys added.

TDD: service tests (Add/GetByInbound, RejectsUnknownInbound, Reorder, Set/Bulk
enable, DeleteHosts, DeleteInboundCascadesHosts, GetAllTags) written failing-
first against a nil-returning stub; controller test (AddListGetDelete envelope
round-trip + AuthInherited 401) added.

Gate: go test ./internal/web/... + go test ./... green; npm run gen + typecheck
+ lint + test (542) + build green.

* feat(sub): render subscription links from hosts; legacy fallback when none (TDD, mutation-checked)

Phase 4 of the Hosts feature. Inserts host resolution between inbound and link
across all three subscription formats.

Mechanism: hostEndpoints(inbound, format) loads the inbound's enabled hosts
(filtered by ExcludeFromSubTypes, ordered by sort_order then id) and projects
each onto the externalProxy entry shape the raw/json/clash renderers already
consume. So a host fans out one link/proxy reusing the exact existing rendering
(address/port/security/sni/fp/alpn/pins/ech) with zero new TLS code. Host header
and path overrides are applied additively in the raw builders (no-op for legacy
externalProxy, which never carries those keys — characterization snapshots stay
green). Clash ip-version (MihomoIpVersion) is set last on the proxy.

Integration points:
- getSubs (raw): per inbound, hostEndpoints AFTER projectThroughFallbackMaster;
  len>0 -> linkFromHosts (renders only the hosts), else legacy GetLink.
- GetJson/GetClash: inject the host endpoints into the inbound's externalProxy
  before the existing getConfig/getProxies loop.
- Precedence: hosts win over any legacy externalProxy (injection replaces it).

Backward compat: a zero-host inbound takes the legacy path -> byte-identical
output (all Phase-0 characterization snapshots unchanged).

TDD: 9 cycles (zero-hosts identical, N-links-ordered with host/path override,
disabled skipped, host-vs-externalProxy precedence, no-dedup, sort composes with
SubSortIndex, host-over-fallback, resolve-via-client-inbounds, ExcludeFromSubTypes
per format) written failing-first against unwired helpers, then wired green.

Mutation sanity (performed + reverted, documented here):
- zero-hosts fallback: flipping the len(hostEps)>0 guard to >=0 makes
  TestSub_ZeroHosts_IdenticalOutput go red (host path yields "" for no hosts).
- no-dedup: adding a remark-dedup in hostEndpoints makes TestSub_NHosts_NoDedup
  go red (two distinct hosts collapse to one link).

Gate: go test ./internal/sub/... + go test ./... green with ZERO edits to the
Phase-0 snapshots; go build green on linux and windows; go vet + gofmt clean.

* feat(migration): seed hosts from inbound externalProxy (TDD, idempotent, dual-driver)

Phase 5 of the Hosts feature. One-time migration so existing installs surface
their legacy externalProxy entries as first-class Host rows.

- seedHostsFromExternalProxy() is self-gated on a HistoryOfSeeders
  "HostsFromExternalProxy" row (run-once) and wired into runSeeders. For each
  inbound it parses StreamSettings, reads externalProxy[], and creates one Host
  per entry: forceTls->Security (unknown->same), dest->Address, port->Port,
  remark->Remark (generated when blank, capped at 40), sni/fingerprint/alpn/
  pinnedPeerCertSha256/echConfigList copied; SortOrder=index; InboundId set.
- Additive: externalProxy is left intact in StreamSettings (rollback-safe; the
  sub layer prefers hosts when present, §Phase 4).
- Postgres: GORM db.Create advances hosts_id_seq via the sequence, so no extra
  resync is needed beyond the existing startup resync.

TDD: field-mapping, idempotency (second run no-op), no-externalProxy->no-hosts,
externalProxy-kept-intact written failing-first against a stub; plus a
Postgres counterpart that skips without XUI_DB_DSN.

Gate: go test ./internal/web/service/... ./internal/database/... green on SQLite;
the *_Postgres tests green against a real Postgres container; go build green on
linux and windows; go vet + gofmt clean. (Running the whole database package
under XUI_DB_TYPE=postgres is not supported — the SQLite-path tests share the one
DSN — so only the t.Skip-gated *_Postgres tests run with the env set.)

* feat(ui): Hosts page + schema + query hooks + link preview helper (TDD on schema/helpers)

Phase 6 of the Hosts feature — the admin UI.

- schemas/api/host.ts: HostFormSchema (validation: remark 1-40, tags ^[A-Z0-9_:]+$
  ≤10×≤36, port 0-65535, security/mihomoIpVersion enums, alpn/fingerprint reused
  from the shared primitives) + a loose HostRecordSchema/HostListSchema for reads.
- lib/hosts/host-link.ts: hostToExternalProxyEntry — the frontend mirror of the
  backend hostToExternalProxyMap (security->forceTls, sni override rules, port
  inherit), for share-link previews.
- api/queries/useHostsQuery.ts + useHostMutations.ts (mirror the node hooks):
  list/get + add/update/del/setEnable/reorder/bulk; queryKeys.hosts.* added;
  mutations invalidate keys.hosts.root().
- pages/hosts/{HostsPage,HostList,HostFormModal}.tsx (+CSS) mirroring pages/nodes:
  list with remark · address:port · inbound · security · tags · enable Switch ·
  per-inbound move up/down (reorder) · bulk enable/disable/delete; form grouped
  into Basic / Advanced / Clash / Subscription-scope sections.
- Route '/hosts' + sidebar item (Global icon); menu.hosts + pages.hosts.* added to
  the en-US bundle (other locales fall back to English until translated).

TDD: HostFormSchema (10 cases) and hostToExternalProxyEntry (6 cases) written
failing-first, then implemented. UI verified by lint/typecheck/test/build.

Deferred (documented enhancement): the live in-form share-link preview (needs
inbound+client context) and a per-host host/path override in JSON/Clash output
(raw already overrides; JSON/Clash inherit the inbound's host/path).

Gate: cd frontend && npm run lint && npm run typecheck && npm run test (557) &&
npm run build all green; go build ./... + go test ./... still green.

* refactor(ui): remove the External Proxy form from the inbound stream settings

Hosts supersede the legacy externalProxy: the subscription renders from hosts
(hosts win when both exist) and the migration converts existing externalProxy
entries to hosts. externalProxy's only real consumers were the subscription
(now covered) and this form's preview — the backend per-client copy-link never
used it — so removing the editor has no functional regression.

- Drop ExternalProxyForm + toggleExternalProxy from InboundFormModal and delete
  the orphaned form component + its export; remove its block test + snapshot.
- KEEP the externalProxy schema field and backend parsing/link-generation: an
  existing inbound's externalProxy still round-trips through the form (not
  silently destroyed on edit) and still renders if a host was removed.

Gate: cd frontend && npm run typecheck + lint + test (556) + build green.

* fix(ui): use Alert `title` instead of deprecated `message` (antd 6)

Ant Design 6 deprecated <Alert message=> in favor of <Alert title=>; the panel
was mid-migration (21 Alerts already on title). Renamed the 7 remaining stragglers
across 5 files (SubLinksModal, InboundFormModal, sockopt, EmailTab, TelegramTab),
silencing the runtime deprecation warning. description= is unchanged.

Pre-existing warning, surfaced while testing Hosts — not introduced by it.

Gate: npm run typecheck + lint + test (556) + build green.

* style(ui): align Hosts page with Clients/Inbounds cards + reorder columns

- page-shell.css never listed .hosts-page, so the Hosts page got no content
  padding / transparent-layout / summary-card spacing. Add a .hosts-page shell
  block (background, dark/ultra vars, content-area + summary-card padding). This
  is the actual "card spacing" bug.
- HostList: match the Clients/Inbounds list card — hoverable + the toolbar moved
  into the card title as a .card-toolbar (Add when nothing selected; selected
  count + bulk enable/disable/delete on selection). Re-declare .card-toolbar in
  HostList.css since the shared rule lives in a lazily-loaded page stylesheet.
- Reorder table columns as requested: Actions, Enable, then Remark, Endpoint,
  Inbound, Security, Tags. Added scroll x for narrow screens.
- HostsPage: add a summary card (Total / Enabled / Disabled) like the other
  pages. New i18n keys: pages.hosts.selectedCount + pages.hosts.summary.*.

Gate: npm run typecheck + lint + test (556) + build green.

* style(ui): use Tabs instead of Collapse in the Add/Edit Host form

The Basic / Advanced / Clash / Subscription-scope sections are now tabs. Each
pane sets forceRender so all fields stay mounted — required because the form
uses preserve=false, so an unmounted tab's values would otherwise be dropped on
submit (and a required field on a hidden tab still blocks submit).

Gate: npm run typecheck + lint + test (556) + build green.

* style(ui): split Host form into Security + Advanced tabs; drop unused JSON fields

- Remove the Mux/Sockopt/XHTTP raw-JSON fields from the Host form: they were not
  wired into link generation and the inbound's structured editors are inbound-
  specific (not reusable). The DB columns + read schema + generated type stay, so
  they can get proper editors later. (HostFormSchema drops them; HostRecordSchema
  keeps them.)
- Reorganize tabs to Basic / Security / Advanced / Clash / Subscription scope:
  Security holds the TLS/cert fields (security, sni, sni-overrides, alpn,
  fingerprint, pins, verify-by-name, ech); Advanced now holds the transport
  overrides (host header, path).
- i18n: add pages.hosts.sections.security; drop the 3 unused field labels.

Gate: npm run typecheck + lint + test (556) + build green.

* style(ui): restore Mux/Sockopt/XHTTP fields in the Host Advanced tab

Put the three free-JSON override fields back, in the Advanced tab next to host
header / path (as JSON inputs — the inbound's structured editors aren't reusable
here). Re-added to HostFormSchema + defaults + the i18n labels.

Gate: npm run typecheck + lint + test (556) + build green.

* feat(hosts): add allowInsecure (rendered) + serverDescription/mihomoX25519/vlessRouteId fields

Closes most of the Remnawave-host gap analysis.

- model.Host: + allowInsecure, serverDescription (≤64), vlessRouteId (0-65535),
  mihomoX25519. Auto-migrated (SQLite + Postgres verified); openapi regenerated.
- allowInsecure is fully RENDERED into subscription output (TDD):
  - raw link: allowInsecure=1 (TLS/Reality, skipped for none) via the endpoint
    builder;
  - JSON/Clash: applyExternalProxyTLSToStream writes tlsSettings.settings.
    allowInsecure, and clash applySecurity now emits skip-cert-verify for the tls
    case (it previously only did so for Hysteria — a pre-existing gap, so inbound
    allowInsecure now renders for vless/trojan/ss clash too).
- Frontend: the four fields added to the Host form (allowInsecure → Security,
  serverDescription → Basic, vlessRouteId → Advanced, mihomoX25519 → Clash);
  serverDescription shown under the remark in the list. Schema + i18n updated.

serverDescription / vlessRouteId / mihomoX25519 are stored + editable; their
deeper rendering (and per-host mux/sockopt/xhttp into JSON/Clash, plus a per-host
xray JSON template) are tracked as follow-ups.

Gate: go test ./... green (SQLite + Postgres for the host schema/migration);
go build linux+windows; go vet + gofmt clean; npm run gen + typecheck + lint +
test (556) + build green; generated files in sync.

* feat(sub): render host sockopt + xhttp-extra params into JSON/Clash output (TDD)

A host's sockoptParams and xhttpExtraParams (free-JSON) now take effect:
applyHostStreamOverrides injects sockopt into the per-host stream (re-added since
the base stream strips it) and merges xhttpExtraParams into xhttpSettings, called
in both getConfig (JSON) and getProxies (Clash) right after the per-host TLS
apply. No-op for legacy externalProxy entries (keys absent) — characterization
snapshots unchanged.

mux rendering is outbound-level (overrides outbound.Mux) and needs a genVless/
genVnext/genServer signature change — deferred, along with the per-host xray
JSON template.

Gate: go test ./internal/sub/... + go test ./... green (snapshots unchanged);
go build + vet + gofmt clean.

* feat(sub): render host muxParams as a per-host JSON outbound mux override (TDD)

genVnext/genVless/genServer take a muxOverride: a host's muxParams (when valid
JSON) overrides the global mux on its JSON outbound; empty falls back to the
panel mux (behavior unchanged for non-host configs). Completes the host
mux/sockopt/xhttp trio. Test call sites updated for the new signature.

Gate: go test ./internal/sub/... + go test ./... green (snapshots unchanged);
go build + gofmt clean.

* style(ui): show Host security fields conditionally per security (like externalProxy)

* feat(sub): apply host SNI + fingerprint override for reality (TDD)

A reality host now overrides SNI and fingerprint while inheriting publicKey/
shortId from the inbound (reality keys can't be host-supplied). Previously the
reality link kept the inbound's serverName because the TLS appliers are gated to
security=="tls".

- raw: applyEndpointRealityParams sets sni/fp on the params for reality;
- JSON/Clash: applyHostStreamOverrides sets realitySettings.serverName +
  serverNames from the host SNI.

Gated to host endpoints via an isHost marker on the synthesized ep, so the legacy
externalProxy path stays byte-identical (characterization snapshots unchanged).
The marker is internal and never emitted.

Gate: go test ./internal/sub/... + go test ./... green; go build + vet + gofmt clean.

* fix(ui): start the Host inbound select unselected instead of showing 0

A new host left inboundId defaulting to 0, so the Select rendered "0". inboundId
is now optional in the form (undefined until chosen), so it shows its
placeholder ("Select an inbound"); the required rule still enforces a choice on
save. Port keeps 0 (means "inherit the inbound's port").

Gate: npm run typecheck + lint + build green.

* fix(ui): drop redundant :port suffix from the Host inbound select label

The inbound tag (e.g. in-59303-tcp) already carries the port, so the appended
":59303" was duplicated. Show just the remark/tag.

Gate: npm run typecheck + lint + build green.

* style(ui): apply the shared card hover shadows to the Hosts page

page-cards.css scoped its card styling + hover shadows to each page class but
not .hosts-page, so Hosts fell back to antd's default hoverable (a larger/blurry
shadow + pointer cursor). Add a .hosts-page block matching the other pages.

Gate: npm run build green.

* feat(hosts): move Tags to Basic tab, add Nodes field, accept VLESS route ranges

- Move the Tags field into the Host form's Basic tab and add a Nodes
  multi-select (visual-only assignment, backed by the existing node_guids
  column) so the Basic tab matches the reference layout.
- Replace the single-port vlessRouteId integer with a free-form vlessRoute
  string that accepts comma-separated ports/ranges (e.g. 53,443,1000-2000);
  format-validated on the frontend, stored verbatim on the backend.
- Regenerated frontend types/openapi from the changed model.

* feat(hosts): structured editors for Mux/Sockopt/XHTTP + new Final Mask

Replace the raw JSON textareas in the Host form's Advanced tab with the same
structured editors used elsewhere, under a nested tabbed layout (General / Mux /
Sockopt / XHTTP / Final Mask), mirroring the Sub-JSON settings tab:

- Mux: the Sub-JSON mux editor (enable + concurrency/xudpConcurrency/xudp443).
- Sockopt + XHTTP: reuse the outbound SockoptForm / XhttpForm, wrapped in an
  isolated form that serializes the edited subtree back to the host's JSON
  string (pruned so the override stays sparse).
- Final Mask: new host field (model + column + JSON-render wiring that merges
  the masks into the host's JSON-subscription stream), edited via the shared
  FinalMaskForm like the Sub-JSON Final Mask editor.

Each editor stays a controlled value/onChange component bound to its existing
host JSON string field; backend rendering of mux/sockopt/xhttp is unchanged.

* feat(hosts): drop XHTTP + Xray-JSON-template overrides; fix mobile form layout

Remove the host's XHTTP extra-params and Xray-JSON-template overrides entirely
(model fields + columns, JSON-subscription render paths incl. hostTemplateOutbound,
schema, form tab/field, i18n, openapi codegen, and their tests) — they did not
fit the host model. Mux, Sockopt and Final Mask stay as structured editors.

Mobile fixes for the Edit Host modal:
- responsive width (95vw on mobile, was a fixed 760px that overflowed the
  viewport and clipped the tabs/labels) + a scrollable body so the footer stays
  on screen;
- Mux fields use responsive Row/Col (stack on mobile) instead of a fixed-width
  label grid.

* fix(hosts): hide the spurious horizontal scrollbar in the Edit Host modal

Setting overflowY:auto on the modal body forced overflow-x to auto too (CSS
rule), so antd Row's negative gutter margins triggered a horizontal scrollbar.
Pin overflowX:hidden.

* feat(hosts): inbound-style responsive field layout + icon empty state

- Host form (main form + Mux/Sockopt/Final Mask editors) now use the inbound
  form's label layout: label beside the input on desktop (labelCol sm span 8 /
  wrapperCol sm span 14, right-aligned), stacked label-above-input on mobile.
  Rewrote HostMuxForm onto an internal antd Form so it follows the same layout
  instead of a manual grid.
- Empty hosts table now shows the host icon + the shared 'Nothing here yet'
  (noData) text, matching Nodes/Inbounds/Clients, replacing the bespoke
  'No hosts yet…' string.

* fix(hosts): avoid nested <form> in the Edit Host modal

The Mux/Sockopt/Final Mask editors each render their own antd Form inside the
host's main Form, producing an invalid nested <form> DOM node (hydration
warning). Render those inner forms with component={false} so they keep the form
instance/context but emit no <form> element.

* fix(hosts): make the Mux enable toggle work

The Switch's checked state came from Form.useWatch('mux'), but the mux object
field had no registered Form.Item while disabled, so setFieldValue never
notified the watcher and the toggle stayed off. Bind the Switch to a real
name='enabled' field (antd drives its checked state directly) and keep the
sub-fields registered via hidden={!enabled}, serialized to the flat mux JSON.

* refactor(hosts): reuse the outbound MuxForm instead of a bespoke Mux editor

The Mux fields duplicated the outbound MuxForm. Reuse it through the same
wrapper as Sockopt: generalize OutboundSubtreeJsonForm with defaultSubtree
(pre-fill on enable) and a serialize hook, and have HostMuxForm render MuxForm
at the ['mux'] path. The host keeps its inherit-when-off semantics by storing ''
unless mux.enabled. Also drops the now-unused enableSwitch path from the
wrapper (only the removed XHTTP editor used it).

* style(hosts): use default-width Port input like the inbound form

The host Port used width:100% (full width); the inbound's numeric inputs use
antd's default width. Drop the override so Port matches. The Mux number inputs
already use the default width via the reused MuxForm.

* refactor(sockopt): readable customSockopt editor as a shared component

The customSockopt rows were a single cramped Space.Compact line and duplicated
verbatim in the inbound and outbound sockopt forms. Extract a shared
CustomSockoptList that renders each entry as a titled group of labeled fields
(System / Level / Opt / Type / Value), matching the rest of the form, and use it
in both (and thus the host Sockopt editor).

* fix(finalmask): drop the empty Custom Tables tag on a new sudoku mask

The sudoku TCP-mask default seeded customTables: [''] (one empty string), which
rendered as a blank removable tag. Seed [] instead.

* fix(sockopt): make the outbound (and host) Sockopt client-only

Per the XTLS sockopt docs, tproxy / acceptProxyProtocol / V6Only /
trustedXForwardedFor only apply to an inbound (listening socket); they are
meaningless on an outbound/dialer. Drop them from the outbound SockoptForm
(which the host reuses). The Sockopt default object still seeds those keys, so
the host also strips them on serialize, keeping its override honest to the
server/client split. The inbound SockoptForm is left unchanged.

* fix(sockopt): make the inbound Sockopt server-only

Complete the server/client split: drop the outbound/dialer-only fields from the
inbound SockoptForm — dialerProxy, domainStrategy, interface, addressPortStrategy,
happyEyeballs, tcpMptcp (client-only since Go 1.24 auto-enables MPTCP on listen).
mark stays (xray applies SO_MARK on inbound sockets too). Update the form-blocks
snapshot to the server-side field set (intentional spec change).

* feat(hosts): populate Sockopt dialerProxy with the panel's outbound tags

The host Sockopt editor reused the outbound SockoptForm with outboundTags=[],
so the dialerProxy dropdown was empty. Feed it the panel's outbound tags via
the existing useOutboundTags hook (shares the cached xray-config query;
blackhole excluded), so a host can chain through a subscription outbound by tag.

* fix(hosts): empty-state styling on direct load + exclude balancers from dialerProxy

- .card-empty was only defined in lazily-loaded Clients/Inbounds/Nodes
  stylesheets, so a direct /hosts refresh rendered the empty table state
  unstyled (faint + uncentered) until another page was visited. Re-declare it
  in HostList.css so it's correct on first load.
- The Sockopt dialerProxy dropdown listed balancer tags (useOutboundTags merges
  them in for mtproto egress). dialerProxy chains a single outbound, so balancers
  aren't valid — switch to useOutboundTagGroups and use only the outbound group.

* fix(outbounds): icon + 'Nothing here yet' empty state; stop fading other pages

The Outbounds empty state was a faint '—', and OutboundsTab.css set the global
.card-empty to opacity:0.4 — which leaked onto whichever page's empty state was
shown after the Outbounds CSS had loaded (e.g. Hosts went faint after visiting
Outbounds). Render the icon + noData ('Nothing here yet') like the other lists,
and align .card-empty to the shared centered/secondary style (no opacity).

* fix(outbounds): custom empty state on the desktop table too

The desktop Outbounds Table had no locale.emptyText, so it showed antd's
default 'No data' box. Add the same ExportOutlined + noData empty state as the
card (mobile) view.

* style(sidebar): use ExportOutlined for the Outbounds nav item

The Outbounds sidebar item used UploadOutlined (an upload tray). Switch to
ExportOutlined, matching the outbound icon now used in the routing target and
the outbounds empty states.

* feat(hosts): icons on the form tabs (icon-only on mobile)

Wrap every Host form tab label (Basic/Security/Advanced/Clash/Subscription
scope and the nested General/Mux/Sockopt/Final Mask) with catTabLabel, so the
tabs show icon + text on desktop and just the icon (with a tooltip) on mobile,
matching the Settings/Xray tab bars.

* refactor(hosts): fold Exclude-from-formats into Advanced, drop the one-field tab

The Subscription scope tab held only excludeFromSubTypes after Tags moved to
Basic — a niche per-format scoping knob. Move it into the Advanced > General
sub-tab and remove the standalone tab (and its now-unused subScope label/icon).

* feat(sub): per-client remark template variables; drop the remark model & Show Usage Info

* fix(migration): cap seeded host remark at the model's 256-char limit, not 40
This commit is contained in:
Sanaei
2026-06-17 12:06:55 +02:00
committed by GitHub
parent 37c5e0bfd2
commit 709b332d17
115 changed files with 6481 additions and 1044 deletions
@@ -0,0 +1,60 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { HttpUtil } from '@/utils';
import { keys } from '@/api/queryKeys';
import type { HostFormValues } from '@/schemas/api/host';
const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } };
export function useHostMutations() {
const queryClient = useQueryClient();
const invalidate = () => queryClient.invalidateQueries({ queryKey: keys.hosts.root() });
const createMut = useMutation({
mutationFn: (payload: Partial<HostFormValues>) => HttpUtil.post('/panel/api/hosts/add', payload),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const updateMut = useMutation({
mutationFn: ({ id, payload }: { id: number; payload: Partial<HostFormValues> }) =>
HttpUtil.post(`/panel/api/hosts/update/${id}`, payload),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const removeMut = useMutation({
mutationFn: (id: number) => HttpUtil.post(`/panel/api/hosts/del/${id}`),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const setEnableMut = useMutation({
mutationFn: ({ id, enable }: { id: number; enable: boolean }) =>
HttpUtil.post(`/panel/api/hosts/setEnable/${id}`, { enable }),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const reorderMut = useMutation({
mutationFn: (ids: number[]) => HttpUtil.post('/panel/api/hosts/reorder', { ids }, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const bulkEnableMut = useMutation({
mutationFn: ({ ids, enable }: { ids: number[]; enable: boolean }) =>
HttpUtil.post('/panel/api/hosts/bulk/setEnable', { ids, enable }, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
const bulkDelMut = useMutation({
mutationFn: (ids: number[]) => HttpUtil.post('/panel/api/hosts/bulk/del', { ids }, JSON_HEADERS),
onSuccess: (msg) => { if (msg?.success) invalidate(); },
});
return {
create: (payload: Partial<HostFormValues>) => createMut.mutateAsync(payload),
update: (id: number, payload: Partial<HostFormValues>) => updateMut.mutateAsync({ id, payload }),
remove: (id: number) => removeMut.mutateAsync(id),
setEnable: (id: number, enable: boolean) => setEnableMut.mutateAsync({ id, enable }),
reorder: (ids: number[]) => reorderMut.mutateAsync(ids),
bulkSetEnable: (ids: number[], enable: boolean) => bulkEnableMut.mutateAsync({ ids, enable }),
bulkDel: (ids: number[]) => bulkDelMut.mutateAsync(ids),
};
}
+33
View File
@@ -0,0 +1,33 @@
import { useQuery } from '@tanstack/react-query';
import { useMemo } from 'react';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { HostListSchema, type HostRecord } from '@/schemas/api/host';
import { keys } from '@/api/queryKeys';
export type { HostRecord };
async function fetchHosts(): Promise<HostRecord[]> {
const msg = await HttpUtil.get('/panel/api/hosts/list', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch hosts');
const validated = parseMsg(msg, HostListSchema, 'hosts/list');
return Array.isArray(validated.obj) ? validated.obj : [];
}
export function useHostsQuery() {
const query = useQuery({
queryKey: keys.hosts.list(),
queryFn: fetchHosts,
});
const hosts = useMemo(() => query.data ?? [], [query.data]);
return {
hosts,
loading: query.isFetching,
fetched: query.data !== undefined || query.isError,
fetchError: query.error ? (query.error as Error).message : '',
refetch: query.refetch,
};
}
+6
View File
@@ -6,6 +6,12 @@ export const keys = {
root: () => ['nodes'] as const,
list: () => ['nodes', 'list'] as const,
},
hosts: {
root: () => ['hosts'] as const,
list: () => ['hosts', 'list'] as const,
byInbound: (inboundId: number) => ['hosts', 'byInbound', inboundId] as const,
tags: () => ['hosts', 'tags'] as const,
},
settings: {
root: () => ['settings'] as const,
all: () => ['settings', 'all'] as const,
@@ -0,0 +1,71 @@
import { useRef } from 'react';
import { Button, Input, Popover, Tooltip } from 'antd';
import type { InputRef } from 'antd';
import { CodeOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { hasRemarkTokens, previewRemark, wrapToken } from '@/lib/remark/remarkVariables';
import RemarkVarPicker from './RemarkVarPicker';
interface RemarkTemplateFieldProps {
// Injected by antd Form.Item:
value?: string;
onChange?: (value: string) => void;
maxLength?: number;
placeholder?: string;
}
/**
* RemarkTemplateField is a text input augmented with a {{VAR}} template picker
* (insert-at-caret) and a live, sample-based preview of the expanded result.
* Used for the global subscription Remark Template.
*/
export default function RemarkTemplateField({ value = '', onChange, maxLength, placeholder }: RemarkTemplateFieldProps) {
const { t } = useTranslation();
const inputRef = useRef<InputRef>(null);
function insertToken(token: string) {
const el = inputRef.current?.input;
const start = el?.selectionStart ?? value.length;
const end = el?.selectionEnd ?? value.length;
const insert = wrapToken(token);
const next = value.slice(0, start) + insert + value.slice(end);
onChange?.(maxLength ? next.slice(0, maxLength) : next);
const caret = start + insert.length;
// The controlled value updates next render; restore the caret after it.
requestAnimationFrame(() => {
el?.focus();
el?.setSelectionRange(caret, caret);
});
}
return (
<div>
<Input
ref={inputRef}
value={value}
maxLength={maxLength}
placeholder={placeholder}
onChange={(e) => onChange?.(e.target.value)}
addonAfter={
<Popover
content={<RemarkVarPicker onPick={insertToken} />}
trigger="click"
placement="bottomRight"
title={t('pages.hosts.remarkVars.title')}
>
<Tooltip title={t('pages.hosts.remarkVars.title')}>
<Button type="text" size="small" icon={<CodeOutlined />} style={{ margin: '0 -7px' }} />
</Tooltip>
</Popover>
}
/>
{hasRemarkTokens(value) && (
<div style={{ fontSize: 12, marginTop: 4, opacity: 0.7 }}>
{t('pages.hosts.remarkVars.preview')}:{' '}
<span style={{ fontFamily: 'monospace' }}>{previewRemark(value) || '—'}</span>
</div>
)}
</div>
);
}
@@ -0,0 +1,43 @@
import { Tag, Tooltip, Typography } from 'antd';
import { useTranslation } from 'react-i18next';
import { REMARK_VARIABLES, REMARK_VAR_GROUPS, wrapToken } from '@/lib/remark/remarkVariables';
interface RemarkVarPickerProps {
/** Called with the bare token (e.g. "EMAIL") when a chip is clicked. */
onPick: (token: string) => void;
}
/**
* RemarkVarPicker is the grouped, tooltipped chip list of {{VAR}} tokens used by
* the global remark-template field.
*/
export default function RemarkVarPicker({ onPick }: RemarkVarPickerProps) {
const { t } = useTranslation();
return (
<div style={{ maxWidth: 460, maxHeight: 'min(70vh, 640px)', overflowY: 'auto' }}>
<Typography.Paragraph type="secondary" style={{ fontSize: 12, marginBottom: 8 }}>
{t('pages.hosts.remarkVars.intro')}
</Typography.Paragraph>
{REMARK_VAR_GROUPS.map((group) => (
<div key={group} style={{ marginBottom: 8 }}>
<div style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', opacity: 0.6, marginBottom: 4 }}>
{t(`pages.hosts.remarkVars.groups.${group}`)}
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
{REMARK_VARIABLES.filter((v) => v.group === group).map((v) => (
<Tooltip key={v.token} title={t(`pages.hosts.remarkVars.desc${v.token}`)}>
<Tag
onClick={() => onPick(v.token)}
style={{ cursor: 'pointer', margin: 0, fontFamily: 'monospace' }}
>
{wrapToken(v.token)}
</Tag>
</Tooltip>
))}
</div>
</div>
))}
</div>
);
}
+3
View File
@@ -2,3 +2,6 @@ export { default as DateTimePicker } from './DateTimePicker';
export { default as JsonEditor } from './JsonEditor';
export { default as HeaderMapEditor } from './HeaderMapEditor';
export { default as SelectAllClearButtons } from './SelectAllClearButtons';
export { default as RemarkTemplateField } from './RemarkTemplateField';
export { default as RemarkVarPicker } from './RemarkVarPicker';
export { default as CustomSockoptList } from '../../lib/xray/forms/transport/CustomSockoptList';
+47 -6
View File
@@ -27,7 +27,7 @@ export const EXAMPLES: Record<string, unknown> = {
"ldapVlessField": "",
"pageSize": 0,
"panelOutbound": "",
"remarkModel": "",
"remarkTemplate": "",
"restartXrayOnClientDisable": false,
"sessionMaxAge": 1,
"smtpCpu": 0,
@@ -47,7 +47,6 @@ export const EXAMPLES: Record<string, unknown> = {
"subClashRules": "",
"subClashURI": "",
"subDomain": "",
"subEmailInRemark": false,
"subEnable": false,
"subEnableRouting": false,
"subEncrypt": false,
@@ -63,7 +62,6 @@ export const EXAMPLES: Record<string, unknown> = {
"subPort": 1,
"subProfileUrl": "",
"subRoutingRules": "",
"subShowInfo": false,
"subSupportUrl": "",
"subThemeDir": "",
"subTitle": "",
@@ -126,7 +124,7 @@ export const EXAMPLES: Record<string, unknown> = {
"ldapVlessField": "",
"pageSize": 0,
"panelOutbound": "",
"remarkModel": "",
"remarkTemplate": "",
"restartXrayOnClientDisable": false,
"sessionMaxAge": 1,
"smtpCpu": 0,
@@ -146,7 +144,6 @@ export const EXAMPLES: Record<string, unknown> = {
"subClashRules": "",
"subClashURI": "",
"subDomain": "",
"subEmailInRemark": false,
"subEnable": false,
"subEnableRouting": false,
"subEncrypt": false,
@@ -162,7 +159,6 @@ export const EXAMPLES: Record<string, unknown> = {
"subPort": 1,
"subProfileUrl": "",
"subRoutingRules": "",
"subShowInfo": false,
"subSupportUrl": "",
"subThemeDir": "",
"subTitle": "",
@@ -277,6 +273,51 @@ export const EXAMPLES: Record<string, unknown> = {
"id": 0,
"seederName": ""
},
"Host": {
"address": "cdn.example.com",
"allowInsecure": false,
"alpn": [
""
],
"createdAt": 0,
"echConfigList": "",
"excludeFromSubTypes": [
""
],
"finalMask": "",
"fingerprint": "",
"hostHeader": "",
"id": 1,
"inboundId": 1,
"isDisabled": false,
"isHidden": false,
"keepSniBlank": false,
"mihomoIpVersion": "dual",
"mihomoX25519": false,
"muxParams": null,
"nodeGuids": [
""
],
"overrideSniFromAddress": false,
"path": "",
"pinnedPeerCertSha256": [
""
],
"port": 8443,
"remark": "cdn-front",
"security": "same",
"serverDescription": "",
"shuffleHost": false,
"sni": "",
"sockoptParams": null,
"sortOrder": 0,
"tags": [
""
],
"updatedAt": 0,
"verifyPeerCertByName": false,
"vlessRoute": ""
},
"Inbound": {
"clientStats": [
{
+181 -26
View File
@@ -98,8 +98,8 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Xray outbound tag for the panel's own outbound HTTP (update checks/downloads, Telegram, geo updates, outbound-subscription fetches)",
"type": "string"
},
"remarkModel": {
"description": "Remark model pattern for inbounds",
"remarkTemplate": {
"description": "Subscription remark template ({{VAR}} tokens) rendered per client",
"type": "string"
},
"restartXrayOnClientDisable": {
@@ -184,10 +184,6 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Domain for subscription server validation",
"type": "string"
},
"subEmailInRemark": {
"description": "Include email in subscription remark/name",
"type": "boolean"
},
"subEnable": {
"description": "Subscription server settings\nEnable subscription server",
"type": "boolean"
@@ -249,10 +245,6 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Subscription global routing rules (Only for Happ)",
"type": "string"
},
"subShowInfo": {
"description": "Show client information in subscriptions",
"type": "boolean"
},
"subSupportUrl": {
"description": "Subscription support URL",
"type": "string"
@@ -398,7 +390,7 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapVlessField",
"pageSize",
"panelOutbound",
"remarkModel",
"remarkTemplate",
"restartXrayOnClientDisable",
"sessionMaxAge",
"smtpCpu",
@@ -418,7 +410,6 @@ export const SCHEMAS: Record<string, unknown> = {
"subClashRules",
"subClashURI",
"subDomain",
"subEmailInRemark",
"subEnable",
"subEnableRouting",
"subEncrypt",
@@ -434,7 +425,6 @@ export const SCHEMAS: Record<string, unknown> = {
"subPort",
"subProfileUrl",
"subRoutingRules",
"subShowInfo",
"subSupportUrl",
"subThemeDir",
"subTitle",
@@ -584,8 +574,8 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Xray outbound tag for the panel's own outbound HTTP (update checks/downloads, Telegram, geo updates, outbound-subscription fetches)",
"type": "string"
},
"remarkModel": {
"description": "Remark model pattern for inbounds",
"remarkTemplate": {
"description": "Subscription remark template ({{VAR}} tokens) rendered per client",
"type": "string"
},
"restartXrayOnClientDisable": {
@@ -670,10 +660,6 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Domain for subscription server validation",
"type": "string"
},
"subEmailInRemark": {
"description": "Include email in subscription remark/name",
"type": "boolean"
},
"subEnable": {
"description": "Subscription server settings\nEnable subscription server",
"type": "boolean"
@@ -735,10 +721,6 @@ export const SCHEMAS: Record<string, unknown> = {
"description": "Subscription global routing rules (Only for Happ)",
"type": "string"
},
"subShowInfo": {
"description": "Show client information in subscriptions",
"type": "boolean"
},
"subSupportUrl": {
"description": "Subscription support URL",
"type": "string"
@@ -891,7 +873,7 @@ export const SCHEMAS: Record<string, unknown> = {
"ldapVlessField",
"pageSize",
"panelOutbound",
"remarkModel",
"remarkTemplate",
"restartXrayOnClientDisable",
"sessionMaxAge",
"smtpCpu",
@@ -911,7 +893,6 @@ export const SCHEMAS: Record<string, unknown> = {
"subClashRules",
"subClashURI",
"subDomain",
"subEmailInRemark",
"subEnable",
"subEnableRouting",
"subEncrypt",
@@ -927,7 +908,6 @@ export const SCHEMAS: Record<string, unknown> = {
"subPort",
"subProfileUrl",
"subRoutingRules",
"subShowInfo",
"subSupportUrl",
"subThemeDir",
"subTitle",
@@ -1326,6 +1306,181 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"Host": {
"description": "Host is an override endpoint attached to an inbound: at subscription time each\nenabled host renders one share link/proxy with its own address/port/TLS/etc.,\nsuperseding the legacy externalProxy array. Free-JSON fields are stored as\ntext and parsed in the sub layer; slice fields use the json serializer.",
"properties": {
"address": {
"example": "cdn.example.com",
"type": "string"
},
"allowInsecure": {
"type": "boolean"
},
"alpn": {
"items": {
"type": "string"
},
"type": "array"
},
"createdAt": {
"type": "integer"
},
"echConfigList": {
"type": "string"
},
"excludeFromSubTypes": {
"items": {
"type": "string"
},
"type": "array"
},
"finalMask": {
"description": "FinalMask is a JSON object of xray finalmask masks (tcp/udp/quicParams),\nmerged into this host's JSON-subscription stream. Empty = no override.",
"type": "string"
},
"fingerprint": {
"type": "string"
},
"hostHeader": {
"type": "string"
},
"id": {
"example": 1,
"type": "integer"
},
"inboundId": {
"example": 1,
"type": "integer"
},
"isDisabled": {
"type": "boolean"
},
"isHidden": {
"type": "boolean"
},
"keepSniBlank": {
"type": "boolean"
},
"mihomoIpVersion": {
"enum": [
"dual",
"ipv4",
"ipv6",
"ipv4-prefer",
"ipv6-prefer"
],
"type": "string"
},
"mihomoX25519": {
"type": "boolean"
},
"muxParams": {},
"nodeGuids": {
"items": {
"type": "string"
},
"type": "array"
},
"overrideSniFromAddress": {
"type": "boolean"
},
"path": {
"type": "string"
},
"pinnedPeerCertSha256": {
"items": {
"type": "string"
},
"type": "array"
},
"port": {
"example": 8443,
"maximum": 65535,
"minimum": 0,
"type": "integer"
},
"remark": {
"example": "cdn-front",
"maxLength": 256,
"type": "string"
},
"security": {
"enum": [
"same",
"tls",
"none",
"reality"
],
"example": "same",
"type": "string"
},
"serverDescription": {
"maxLength": 64,
"type": "string"
},
"shuffleHost": {
"type": "boolean"
},
"sni": {
"type": "string"
},
"sockoptParams": {},
"sortOrder": {
"type": "integer"
},
"tags": {
"items": {
"type": "string"
},
"type": "array"
},
"updatedAt": {
"type": "integer"
},
"verifyPeerCertByName": {
"type": "boolean"
},
"vlessRoute": {
"description": "VlessRoute is a free-form port/range routing spec (e.g. \"53,443,1000-2000\");\nstored verbatim, format-validated on the frontend.",
"type": "string"
}
},
"required": [
"address",
"allowInsecure",
"alpn",
"createdAt",
"echConfigList",
"excludeFromSubTypes",
"finalMask",
"fingerprint",
"hostHeader",
"id",
"inboundId",
"isDisabled",
"isHidden",
"keepSniBlank",
"mihomoIpVersion",
"mihomoX25519",
"muxParams",
"overrideSniFromAddress",
"path",
"pinnedPeerCertSha256",
"port",
"remark",
"security",
"serverDescription",
"shuffleHost",
"sni",
"sockoptParams",
"sortOrder",
"tags",
"updatedAt",
"verifyPeerCertByName",
"vlessRoute"
],
"type": "object"
},
"Inbound": {
"description": "Inbound represents an Xray inbound configuration with traffic statistics and settings.",
"properties": {
+38 -6
View File
@@ -33,7 +33,7 @@ export interface AllSetting {
ldapVlessField: string;
pageSize: number;
panelOutbound: string;
remarkModel: string;
remarkTemplate: string;
restartXrayOnClientDisable: boolean;
sessionMaxAge: number;
smtpCpu: number;
@@ -53,7 +53,6 @@ export interface AllSetting {
subClashRules: string;
subClashURI: string;
subDomain: string;
subEmailInRemark: boolean;
subEnable: boolean;
subEnableRouting: boolean;
subEncrypt: boolean;
@@ -69,7 +68,6 @@ export interface AllSetting {
subPort: number;
subProfileUrl: string;
subRoutingRules: string;
subShowInfo: boolean;
subSupportUrl: string;
subThemeDir: string;
subTitle: string;
@@ -133,7 +131,7 @@ export interface AllSettingView {
ldapVlessField: string;
pageSize: number;
panelOutbound: string;
remarkModel: string;
remarkTemplate: string;
restartXrayOnClientDisable: boolean;
sessionMaxAge: number;
smtpCpu: number;
@@ -153,7 +151,6 @@ export interface AllSettingView {
subClashRules: string;
subClashURI: string;
subDomain: string;
subEmailInRemark: boolean;
subEnable: boolean;
subEnableRouting: boolean;
subEncrypt: boolean;
@@ -169,7 +166,6 @@ export interface AllSettingView {
subPort: number;
subProfileUrl: string;
subRoutingRules: string;
subShowInfo: boolean;
subSupportUrl: string;
subThemeDir: string;
subTitle: string;
@@ -294,6 +290,42 @@ export interface HistoryOfSeeders {
seederName: string;
}
export interface Host {
address: string;
allowInsecure: boolean;
alpn: string[];
createdAt: number;
echConfigList: string;
excludeFromSubTypes: string[];
finalMask: string;
fingerprint: string;
hostHeader: string;
id: number;
inboundId: number;
isDisabled: boolean;
isHidden: boolean;
keepSniBlank: boolean;
mihomoIpVersion: string;
mihomoX25519: boolean;
muxParams: unknown;
nodeGuids?: string[];
overrideSniFromAddress: boolean;
path: string;
pinnedPeerCertSha256: string[];
port: number;
remark: string;
security: string;
serverDescription: string;
shuffleHost: boolean;
sni: string;
sockoptParams: unknown;
sortOrder: number;
tags: string[];
updatedAt: number;
verifyPeerCertByName: boolean;
vlessRoute: string;
}
export interface Inbound {
clientStats: ClientTraffic[];
down: number;
+39 -6
View File
@@ -45,7 +45,7 @@ export const AllSettingSchema = z.object({
ldapVlessField: z.string(),
pageSize: z.number().int().min(0).max(1000),
panelOutbound: z.string(),
remarkModel: z.string(),
remarkTemplate: z.string(),
restartXrayOnClientDisable: z.boolean(),
sessionMaxAge: z.number().int().min(1).max(525600),
smtpCpu: z.number().int().min(0).max(100),
@@ -65,7 +65,6 @@ export const AllSettingSchema = z.object({
subClashRules: z.string(),
subClashURI: z.string(),
subDomain: z.string(),
subEmailInRemark: z.boolean(),
subEnable: z.boolean(),
subEnableRouting: z.boolean(),
subEncrypt: z.boolean(),
@@ -81,7 +80,6 @@ export const AllSettingSchema = z.object({
subPort: z.number().int().min(1).max(65535),
subProfileUrl: z.string(),
subRoutingRules: z.string(),
subShowInfo: z.boolean(),
subSupportUrl: z.string(),
subThemeDir: z.string(),
subTitle: z.string(),
@@ -146,7 +144,7 @@ export const AllSettingViewSchema = z.object({
ldapVlessField: z.string(),
pageSize: z.number().int().min(0).max(1000),
panelOutbound: z.string(),
remarkModel: z.string(),
remarkTemplate: z.string(),
restartXrayOnClientDisable: z.boolean(),
sessionMaxAge: z.number().int().min(1).max(525600),
smtpCpu: z.number().int().min(0).max(100),
@@ -166,7 +164,6 @@ export const AllSettingViewSchema = z.object({
subClashRules: z.string(),
subClashURI: z.string(),
subDomain: z.string(),
subEmailInRemark: z.boolean(),
subEnable: z.boolean(),
subEnableRouting: z.boolean(),
subEncrypt: z.boolean(),
@@ -182,7 +179,6 @@ export const AllSettingViewSchema = z.object({
subPort: z.number().int().min(1).max(65535),
subProfileUrl: z.string(),
subRoutingRules: z.string(),
subShowInfo: z.boolean(),
subSupportUrl: z.string(),
subThemeDir: z.string(),
subTitle: z.string(),
@@ -317,6 +313,43 @@ export const HistoryOfSeedersSchema = z.object({
});
export type HistoryOfSeeders = z.infer<typeof HistoryOfSeedersSchema>;
export const HostSchema = z.object({
address: z.string(),
allowInsecure: z.boolean(),
alpn: z.array(z.string()),
createdAt: z.number().int(),
echConfigList: z.string(),
excludeFromSubTypes: z.array(z.string()),
finalMask: z.string(),
fingerprint: z.string(),
hostHeader: z.string(),
id: z.number().int(),
inboundId: z.number().int(),
isDisabled: z.boolean(),
isHidden: z.boolean(),
keepSniBlank: z.boolean(),
mihomoIpVersion: z.enum(['dual', 'ipv4', 'ipv6', 'ipv4-prefer', 'ipv6-prefer']),
mihomoX25519: z.boolean(),
muxParams: z.unknown(),
nodeGuids: z.array(z.string()).optional(),
overrideSniFromAddress: z.boolean(),
path: z.string(),
pinnedPeerCertSha256: z.array(z.string()),
port: z.number().int().min(0).max(65535),
remark: z.string().max(256),
security: z.enum(['same', 'tls', 'none', 'reality']),
serverDescription: z.string().max(64),
shuffleHost: z.boolean(),
sni: z.string(),
sockoptParams: z.unknown(),
sortOrder: z.number().int(),
tags: z.array(z.string()),
updatedAt: z.number().int(),
verifyPeerCertByName: z.boolean(),
vlessRoute: z.string(),
});
export type Host = z.infer<typeof HostSchema>;
export const InboundSchema = z.object({
clientStats: z.array(z.lazy(() => ClientTrafficSchema)),
down: z.number().int(),
+6 -3
View File
@@ -12,7 +12,9 @@ import {
CodeOutlined,
DashboardOutlined,
DatabaseOutlined,
ExportOutlined,
GithubOutlined,
GlobalOutlined,
HeartOutlined,
ImportOutlined,
LogoutOutlined,
@@ -28,7 +30,6 @@ import {
TagsOutlined,
TeamOutlined,
ToolOutlined,
UploadOutlined,
} from '@ant-design/icons';
import { HttpUtil } from '@/utils';
@@ -41,7 +42,7 @@ const DONATE_URL = 'https://donate.sanaei.dev/';
const REPO_URL = 'https://github.com/MHSanaei/3x-ui';
const LOGOUT_KEY = '__logout__';
type IconName = 'dashboard' | 'inbound' | 'team' | 'groups' | 'setting' | 'tool' | 'cluster' | 'logout' | 'apidocs' | 'outbound';
type IconName = 'dashboard' | 'inbound' | 'team' | 'groups' | 'setting' | 'tool' | 'cluster' | 'hosts' | 'logout' | 'apidocs' | 'outbound';
const iconByName: Record<IconName, ComponentType> = {
dashboard: DashboardOutlined,
@@ -51,9 +52,10 @@ const iconByName: Record<IconName, ComponentType> = {
setting: SettingOutlined,
tool: ToolOutlined,
cluster: ClusterOutlined,
hosts: GlobalOutlined,
logout: LogoutOutlined,
apidocs: ApiOutlined,
outbound: UploadOutlined,
outbound: ExportOutlined,
};
function readCollapsed(): boolean {
@@ -139,6 +141,7 @@ export default function AppSidebar() {
{ key: '/clients', icon: 'team', title: t('menu.clients') },
{ key: '/groups', icon: 'groups', title: t('menu.groups') },
{ key: '/nodes', icon: 'cluster', title: t('menu.nodes') },
{ key: '/hosts', icon: 'hosts', title: t('menu.hosts') },
{ key: '/xray#outbound', icon: 'outbound', title: t('pages.xray.Outbounds') },
{ key: '/settings', icon: 'setting', title: t('menu.settings') },
{ key: '/xray', icon: 'tool', title: t('menu.xray') },
+50
View File
@@ -0,0 +1,50 @@
import type { ExternalProxyEntry } from '@/schemas/protocols/stream/external-proxy';
import type { HostFormValues } from '@/schemas/api/host';
// The subset of a host that affects its share link. Mirrors the fields the
// backend's hostToExternalProxyMap reads.
export type HostLinkInput = Pick<
HostFormValues,
| 'security'
| 'address'
| 'port'
| 'remark'
| 'sni'
| 'alpn'
| 'fingerprint'
| 'pinnedPeerCertSha256'
| 'echConfigList'
| 'overrideSniFromAddress'
| 'keepSniBlank'
>;
// hostToExternalProxyEntry projects a host onto the ExternalProxyEntry shape the
// share-link preview generators already understand — the frontend mirror of the
// backend's hostToExternalProxyMap. security "reality"/"same" keep the inbound's
// base TLS (forceTls "same"); the preview falls back to port 443 when the host
// inherits the inbound port (port 0).
export function hostToExternalProxyEntry(host: HostLinkInput): ExternalProxyEntry {
const forceTls = host.security === 'tls' || host.security === 'none' ? host.security : 'same';
let sni: string | undefined;
if (host.keepSniBlank) {
sni = undefined;
} else if (host.overrideSniFromAddress) {
sni = host.address || undefined;
} else {
sni = host.sni || undefined;
}
return {
forceTls,
dest: host.address || '',
port: host.port && host.port > 0 ? host.port : 443,
remark: host.remark || '',
sni,
fingerprint: host.fingerprint,
alpn: host.alpn && host.alpn.length > 0 ? host.alpn : undefined,
pinnedPeerCertSha256:
host.pinnedPeerCertSha256 && host.pinnedPeerCertSha256.length > 0 ? host.pinnedPeerCertSha256 : undefined,
echConfigList: host.echConfigList || undefined,
};
}
@@ -0,0 +1,70 @@
// Template variables an operator can embed in a Host's Remark. At subscription
// time the backend (internal/sub/remark_vars.go) substitutes each {{TOKEN}}
// 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 interface RemarkVar {
/** Bare token name, e.g. "TRAFFIC_LEFT" (rendered as {{TRAFFIC_LEFT}}). */
token: string;
group: RemarkVarGroup;
/** Example value used only for the form's live preview. */
sample: string;
}
export const REMARK_VAR_GROUPS: RemarkVarGroup[] = ['client', 'traffic', 'time'];
export const REMARK_VARIABLES: RemarkVar[] = [
// Client identity
{ token: 'EMAIL', group: 'client', sample: 'john' },
{ token: 'INBOUND', group: 'client', sample: 'Germany' },
{ token: 'HOST', group: 'client', sample: 'CDN' },
{ token: 'ID', group: 'client', sample: '3f2a9c1b-aaaa-bbbb-cccc-1234567890ab' },
{ token: 'SHORT_ID', group: 'client', sample: '3f2a9c1b' },
{ token: 'TELEGRAM_ID', group: 'client', sample: '123456789' },
{ token: 'SUB_ID', group: 'client', sample: 'subABC' },
{ token: 'COMMENT', group: 'client', sample: 'vip' },
// Traffic
{ token: 'TRAFFIC_USED', group: 'traffic', sample: '8.40GB' },
{ token: 'TRAFFIC_LEFT', group: 'traffic', sample: '41.60GB' },
{ token: 'TRAFFIC_TOTAL', group: 'traffic', sample: '50.00GB' },
{ token: 'TRAFFIC_USED_BYTES', group: 'traffic', sample: '9019431321' },
{ token: 'TRAFFIC_LEFT_BYTES', group: 'traffic', sample: '44667656679' },
{ token: 'TRAFFIC_TOTAL_BYTES', group: 'traffic', sample: '53687091200' },
{ token: 'UP', group: 'traffic', sample: '5.20GB' },
{ token: 'DOWN', group: 'traffic', sample: '3.20GB' },
// Time / status
{ token: 'STATUS', group: 'time', sample: 'active' },
{ token: 'DAYS_LEFT', group: 'time', sample: '12' },
{ token: 'EXPIRE_DATE', group: 'time', sample: '2026-09-01' },
{ token: 'EXPIRE_UNIX', group: 'time', sample: '1788300000' },
{ token: 'CREATED_UNIX', group: 'time', sample: '1700000000' },
{ token: 'RESET_DAYS', group: 'time', sample: '30' },
];
const SAMPLE_BY_TOKEN: Record<string, string> = Object.fromEntries(
REMARK_VARIABLES.map((v) => [v.token, v.sample]),
);
const TOKEN_RE = /\{\{([A-Z_]+)\}\}/g;
/** wrapToken("EMAIL") → "{{EMAIL}}". */
export function wrapToken(token: string): string {
return `{{${token}}}`;
}
/** Whether a remark string uses any {{VAR}} token at all. */
export function hasRemarkTokens(template: string): boolean {
return template.includes('{{');
}
/**
* previewRemark renders a template against the sample values, mirroring the
* backend substitution closely enough for an at-a-glance preview. Unknown
* tokens collapse to empty, just like the server.
*/
export function previewRemark(template: string): string {
if (!hasRemarkTokens(template)) return template;
return template.replace(TOKEN_RE, (_m, tok: string) => SAMPLE_BY_TOKEN[tok] ?? '');
}
@@ -0,0 +1,76 @@
import { Button, Divider, Form, Input, Select } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { NamePath } from 'antd/es/form/interface';
// 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
// the sockopt form. Shared by the inbound and outbound (and host) sockopt forms.
// Ref: https://xtls.github.io/config/transports/sockopt.html#sockoptobject
const SYSTEM_OPTIONS = [
{ value: 'linux', label: 'linux' },
{ value: 'windows', label: 'windows' },
{ value: 'darwin', label: 'darwin' },
];
const TYPE_OPTIONS = [
{ value: 'int', label: 'int' },
{ value: 'str', label: 'str' },
];
interface CustomSockoptListProps {
name?: NamePath;
}
export default function CustomSockoptList({
name = ['streamSettings', 'sockopt', 'customSockopt'],
}: CustomSockoptListProps) {
const { t } = useTranslation();
return (
<Form.List name={name}>
{(fields, { add, remove }) => (
<>
<Form.Item label={t('pages.inbounds.form.customSockopt')}>
<Button
type="dashed"
size="small"
icon={<PlusOutlined />}
onClick={() => add({ type: 'int', level: '6', opt: '', value: '' })}
>
{t('pages.inbounds.form.addCustomOption')}
</Button>
</Form.Item>
{fields.map((field, idx) => (
<div key={field.key}>
<Divider plain style={{ margin: '4px 0 8px' }}>
{t('pages.inbounds.form.customSockopt')} {idx + 1}
<DeleteOutlined
className="danger-icon"
style={{ marginInlineStart: 8 }}
onClick={() => remove(field.name)}
/>
</Divider>
<Form.Item label="System" name={[field.name, 'system']}>
<Select placeholder="all" allowClear options={SYSTEM_OPTIONS} />
</Form.Item>
<Form.Item label="Level" name={[field.name, 'level']}>
<Input placeholder="6 (SOL_TCP)" />
</Form.Item>
<Form.Item label="Opt" name={[field.name, 'opt']}>
<Input placeholder="decimal, e.g. 19" />
</Form.Item>
<Form.Item label="Type" name={[field.name, 'type']}>
<Select options={TYPE_OPTIONS} />
</Form.Item>
<Form.Item label="Value" name={[field.name, 'value']}>
<Input placeholder="value" />
</Form.Item>
</div>
))}
</>
)}
</Form.List>
);
}
@@ -71,7 +71,7 @@ function defaultTcpMaskSettings(type: string): Record<string, unknown> {
return { packets: '1-3', length: '100-200', delay: '', maxSplit: '' };
case 'sudoku':
return {
password: '', ascii: '', customTable: '', customTables: [''],
password: '', ascii: '', customTable: '', customTables: [],
paddingMin: 0, paddingMax: 0,
};
case 'header-custom':
+12 -27
View File
@@ -983,23 +983,19 @@ export interface GenAllLinksEntry {
export interface GenAllLinksInput {
inbound: Inbound;
remark?: string;
remarkModel?: string;
client: ClientShape;
hostOverride?: string;
fallbackHostname: string;
}
// Fans out a single client's link per externalProxy entry, or just one
// link when there are no external proxies. remarkModel is a 4-char
// string: first char is the separator, remaining chars pick which
// pieces to compose into the per-link remark — 'i' = inbound remark,
// 'e' = client email, 'o' = externalProxy remark. Defaults to '-io'
// (dash-separated, inbound + email + proxy).
// Fans out a single client's link per externalProxy entry, or just one link
// when there are no external proxies. The panel copy/QR remark is the inbound
// remark plus the externalProxy remark, dash-joined (the configurable
// subscription remark model was removed; subscription output uses the template).
export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
const {
inbound,
remark = '',
remarkModel = '-io',
client,
hostOverride = '',
fallbackHostname,
@@ -1007,17 +1003,9 @@ export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const port = inbound.port;
const separationChar = remarkModel.charAt(0);
const orderChars = remarkModel.slice(1);
const email = client.email ?? '';
const composeRemark = (proxyRemark: string): string => {
const orders: Record<string, string> = { i: remark, e: email, o: proxyRemark };
return orderChars.split('')
.map((c) => orders[c] ?? '')
.filter((x) => x.length > 0)
.join(separationChar);
};
const composeRemark = (proxyRemark: string): string =>
[remark, proxyRemark].filter((x) => x.length > 0).join('-');
const externals = inbound.streamSettings?.externalProxy;
if (!externals || externals.length === 0) {
@@ -1044,7 +1032,6 @@ export function genAllLinks(input: GenAllLinksInput): GenAllLinksEntry[] {
export interface GenInboundLinksInput {
inbound: Inbound;
remark?: string;
remarkModel?: string;
hostOverride?: string;
fallbackHostname: string;
}
@@ -1058,7 +1045,6 @@ export function genInboundLinks(input: GenInboundLinksInput): string {
const {
inbound,
remark = '',
remarkModel = '-io',
hostOverride = '',
fallbackHostname,
} = input;
@@ -1067,7 +1053,7 @@ export function genInboundLinks(input: GenInboundLinksInput): string {
if (clients) {
const links: string[] = [];
for (const client of clients) {
const entries = genAllLinks({ inbound, remark, remarkModel, client, hostOverride, fallbackHostname });
const entries = genAllLinks({ inbound, remark, client, hostOverride, fallbackHostname });
for (const e of entries) links.push(e.link);
}
return links.join('\r\n');
@@ -1076,7 +1062,7 @@ export function genInboundLinks(input: GenInboundLinksInput): string {
return genShadowsocksLink({ inbound, address: addr, port: inbound.port, forceTls: 'same', remark });
}
if (inbound.protocol === 'wireguard') {
return genWireguardConfigs({ inbound, remark, remarkModel, hostOverride, fallbackHostname });
return genWireguardConfigs({ inbound, remark, hostOverride, fallbackHostname });
}
return '';
}
@@ -1087,16 +1073,15 @@ export function genInboundLinks(input: GenInboundLinksInput): string {
export interface GenWireguardFanoutInput {
inbound: Inbound;
remark?: string;
remarkModel?: string;
hostOverride?: string;
fallbackHostname: string;
}
export function genWireguardLinks(input: GenWireguardFanoutInput): string {
const { inbound, remark = '', remarkModel = '-io', hostOverride = '', fallbackHostname } = input;
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
if (inbound.protocol !== 'wireguard') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = remarkModel.charAt(0);
const sep = '-';
return inbound.settings.peers
.map((p, i) => genWireguardLink({
settings: inbound.settings as WireguardInboundSettings,
@@ -1109,10 +1094,10 @@ export function genWireguardLinks(input: GenWireguardFanoutInput): string {
}
export function genWireguardConfigs(input: GenWireguardFanoutInput): string {
const { inbound, remark = '', remarkModel = '-io', hostOverride = '', fallbackHostname } = input;
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
if (inbound.protocol !== 'wireguard') return '';
const addr = resolveAddr(inbound, hostOverride, fallbackHostname);
const sep = remarkModel.charAt(0);
const sep = '-';
return inbound.settings.peers
.map((p, i) => genWireguardConfig({
settings: inbound.settings as WireguardInboundSettings,
+10 -23
View File
@@ -47,29 +47,16 @@ const TRANSPORT_COLOR = 'gold';
const TAG_STYLE = { marginInlineEnd: 0, fontWeight: 600, letterSpacing: '0.3px' };
/* Strip the client email and the optional traffic/expiry decorations the
panel appends to a remark (e.g. "5.23GB📊", "30D⏳", "⛔️N/A") together
with any separator chars left dangling, so the label shows just the
inbound remark. The email is known from the client record, so it can be
removed even though its position in the composed remark depends on the
panel's remark-model settings. */
function cleanRemark(remark: string, email: string): string {
let r = remark
.replace(/?N\/A/gu, '')
.replace(/[0-9][0-9A-Za-z.,]*[📊]/gu, '');
if (email) {
const esc = email.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
r = r.replace(new RegExp(`[\\s\\-_.|,@]*${esc}`, 'g'), '');
}
return r.replace(/^[\s\-_.|,@]+|[\s\-_.|,@]+$/gu, '').trim();
}
/* Pull protocol, transport, security plus the remark and port out of a share
link. vless/trojan carry network+security as `type`/`security` query params
and the remark in the URL hash; vmess packs them into the base64 JSON as
`net`/`tls`/`ps`/`port`. Returns null when the scheme is unknown or the
payload can't be parsed, so callers fall back to "Link N".
/* Pull protocol, transport, security plus the inbound remark and port out
of a share link. vless/trojan carry network+security as `type`/`security`
query params and the remark in the URL hash; vmess packs them into the
base64 JSON as `net`/`tls`/`ps`/`port`. Returns null when the scheme is
unknown or the payload can't be parsed, so callers fall back to "Link N". */
export function parseLinkParts(link: string, email = ''): LinkParts | null {
The remark is shown verbatim: the panel displays the subscription's clean
(name-only) remarks — the per-client traffic/expiry info is rendered only
into the body a client app imports, so there is nothing to strip here. */
export function parseLinkParts(link: string): LinkParts | null {
const trimmed = link.trim();
const scheme = /^([a-z0-9]+):\/\//i.exec(trimmed)?.[1]?.toLowerCase() ?? '';
if (!scheme) return null;
@@ -106,7 +93,7 @@ export function parseLinkParts(link: string, email = ''): LinkParts | null {
protocol,
network: network.toUpperCase(),
security: security.toUpperCase(),
remark: cleanRemark(remark, email),
remark: remark.trim(),
port,
};
}
+1 -3
View File
@@ -13,7 +13,7 @@ export class AllSetting {
pageSize = 25;
expireDiff = 0;
trafficDiff = 0;
remarkModel = '-io';
remarkTemplate = '{{INBOUND}}|📊{{TRAFFIC_LEFT}}|⏳{{DAYS_LEFT}}D';
datepicker: 'gregorian' | 'jalalian' = 'gregorian';
tgBotEnable = false;
tgBotToken = '';
@@ -48,8 +48,6 @@ export class AllSetting {
subKeyFile = '';
subUpdates = 12;
subEncrypt = true;
subShowInfo = true;
subEmailInRemark = true;
subURI = '';
subJsonURI = '';
subClashURI = '';
+93
View File
@@ -907,6 +907,99 @@ export const sections: readonly Section[] = [
],
},
{
id: 'hosts',
title: 'Hosts',
description:
'Per-inbound override endpoints. Each enabled host renders one extra subscription link/proxy with its own address/port/TLS, superseding the legacy externalProxy array. All endpoints under /panel/api/hosts.',
endpoints: [
{
method: 'GET',
path: '/panel/api/hosts/list',
summary: 'List every host across all inbounds, grouped by inbound then ordered by sort order.',
responseSchema: 'Host',
responseSchemaArray: true,
},
{
method: 'GET',
path: '/panel/api/hosts/get/:id',
summary: 'Fetch a single host by ID.',
params: [
{ name: 'id', in: 'path', type: 'number', desc: 'Host ID.' },
],
responseSchema: 'Host',
},
{
method: 'GET',
path: '/panel/api/hosts/byInbound/:inboundId',
summary: "Fetch one inbound's hosts, ordered by sort order then id.",
params: [
{ name: 'inboundId', in: 'path', type: 'number', desc: 'Inbound ID.' },
],
responseSchema: 'Host',
responseSchemaArray: true,
},
{
method: 'GET',
path: '/panel/api/hosts/tags',
summary: 'Distinct, sorted set of tags used across all hosts.',
response: '{\n "success": true,\n "obj": ["CDN", "EU", "FAST"]\n}',
},
{
method: 'POST',
path: '/panel/api/hosts/add',
summary: 'Create a host on an inbound. inboundId and remark are required; security defaults to "same" (inherit the inbound).',
body: '{\n "inboundId": 1,\n "remark": "cdn-front",\n "address": "cdn.example.com",\n "port": 8443,\n "security": "same",\n "sni": "",\n "tags": ["CDN"]\n}',
responseSchema: 'Host',
},
{
method: 'POST',
path: '/panel/api/hosts/update/:id',
summary: 'Replace a hosts content. The inbound and sort order are immutable here (use /reorder for ordering).',
params: [
{ name: 'id', in: 'path', type: 'number', desc: 'Host ID.' },
],
body: '{\n "inboundId": 1,\n "remark": "cdn-front",\n "address": "cdn.example.com",\n "port": 8443,\n "security": "same",\n "sni": "",\n "tags": ["CDN"]\n}',
responseSchema: 'Host',
},
{
method: 'POST',
path: '/panel/api/hosts/del/:id',
summary: 'Delete a host.',
params: [
{ name: 'id', in: 'path', type: 'number', desc: 'Host ID.' },
],
},
{
method: 'POST',
path: '/panel/api/hosts/setEnable/:id',
summary: 'Enable or disable a single host (disabled hosts are skipped in subscriptions).',
params: [
{ name: 'id', in: 'path', type: 'number', desc: 'Host ID.' },
],
body: '{\n "enable": true\n}',
},
{
method: 'POST',
path: '/panel/api/hosts/reorder',
summary: 'Set host sort order by the position of each id in the array.',
body: '{\n "ids": [3, 1, 2]\n}',
},
{
method: 'POST',
path: '/panel/api/hosts/bulk/setEnable',
summary: 'Enable or disable many hosts in one call.',
body: '{\n "ids": [1, 2, 3],\n "enable": false\n}',
},
{
method: 'POST',
path: '/panel/api/hosts/bulk/del',
summary: 'Delete many hosts in one call.',
body: '{\n "ids": [1, 2, 3]\n}',
},
],
},
{
id: 'backup',
title: 'Backup',
@@ -354,7 +354,7 @@ export default function ClientInfoModal({
<>
<Divider>{t('pages.inbounds.copyLink')}</Divider>
{links.map((link, idx) => {
const parts = parseLinkParts(link, client.email);
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;
+1 -1
View File
@@ -92,7 +92,7 @@ export default function ClientQrModal({
});
}
links.forEach((link, idx) => {
const parts = parseLinkParts(link, client?.email ?? '');
const parts = parseLinkParts(link);
const meta = parts ? linkMetaText(parts) : '';
const label: React.ReactNode = parts ? (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
+2 -2
View File
@@ -165,7 +165,7 @@ export default function SubLinksModal({
<Alert
type="warning"
showIcon
message={t('pages.clients.subLinksDisabled')}
title={t('pages.clients.subLinksDisabled')}
description={t('pages.clients.subLinksDisabledHint')}
style={{ marginBottom: 12 }}
/>
@@ -174,7 +174,7 @@ export default function SubLinksModal({
<Alert
type="info"
showIcon
message={t('pages.clients.subLinksEmpty')}
title={t('pages.clients.subLinksEmpty')}
style={{ marginBottom: 12 }}
/>
)}
+335
View File
@@ -0,0 +1,335 @@
import { useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Form, Input, InputNumber, Modal, Select, Switch, Tabs, message } from 'antd';
import {
ProfileOutlined,
SafetyCertificateOutlined,
ControlOutlined,
NodeIndexOutlined,
SettingOutlined,
PartitionOutlined,
DeploymentUnitOutlined,
RocketOutlined,
} from '@ant-design/icons';
import type { HostRecord } from '@/api/queries/useHostsQuery';
import type { HostFormValues } from '@/schemas/api/host';
import type { InboundOption } from '@/schemas/client';
import { ALPN_OPTION, UTLS_FINGERPRINT } from '@/schemas/primitives';
import { useNodesQuery } from '@/api/queries/useNodesQuery';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from '@/pages/settings/catTabLabel';
import { HostFinalMaskForm, HostMuxForm, HostSockoptForm } from './json-forms';
// inboundId is optional in the form so a new host starts unselected (the Select
// shows its placeholder instead of 0); the required rule enforces it on submit.
type FormShape = Omit<HostFormValues, 'isDisabled' | 'inboundId'> & { enable: boolean; inboundId?: number };
interface HostFormModalProps {
open: boolean;
mode: 'add' | 'edit';
host: HostRecord | null;
inboundOptions: InboundOption[];
save: (payload: Partial<HostFormValues>) => Promise<{ success?: boolean; msg?: string } | undefined>;
onOpenChange: (open: boolean) => void;
}
const asString = (v: unknown): string => (typeof v === 'string' ? v : '');
function defaultsFor(host: HostRecord | null): FormShape {
return {
inboundId: host?.inboundId,
sortOrder: host?.sortOrder ?? 0,
remark: host?.remark ?? '',
serverDescription: host?.serverDescription ?? '',
enable: host ? !host.isDisabled : true,
isHidden: host?.isHidden ?? false,
tags: host?.tags ?? [],
address: host?.address ?? '',
port: host?.port ?? 0,
security: (host?.security as HostFormValues['security']) ?? 'same',
sni: host?.sni ?? '',
hostHeader: host?.hostHeader ?? '',
path: host?.path ?? '',
alpn: (host?.alpn as HostFormValues['alpn']) ?? [],
fingerprint: host?.fingerprint as HostFormValues['fingerprint'],
overrideSniFromAddress: host?.overrideSniFromAddress ?? false,
keepSniBlank: host?.keepSniBlank ?? false,
pinnedPeerCertSha256: host?.pinnedPeerCertSha256 ?? [],
verifyPeerCertByName: host?.verifyPeerCertByName ?? false,
allowInsecure: host?.allowInsecure ?? false,
echConfigList: host?.echConfigList ?? '',
muxParams: asString(host?.muxParams),
sockoptParams: asString(host?.sockoptParams),
finalMask: host?.finalMask ?? '',
vlessRoute: host?.vlessRoute ?? '',
excludeFromSubTypes: (host?.excludeFromSubTypes as HostFormValues['excludeFromSubTypes']) ?? [],
nodeGuids: host?.nodeGuids ?? [],
mihomoIpVersion: host?.mihomoIpVersion as HostFormValues['mihomoIpVersion'],
mihomoX25519: host?.mihomoX25519 ?? false,
shuffleHost: host?.shuffleHost ?? false,
};
}
export default function HostFormModal({ open, mode, host, inboundOptions, save, onOpenChange }: HostFormModalProps) {
const { t } = useTranslation();
const { isMobile } = useMediaQuery();
const [form] = Form.useForm<FormShape>();
// Drive conditional field visibility off the selected security, like the
// legacy externalProxy form: same/none inherit fully and hide every TLS/cert
// field; reality shows only the reality-relevant subset (its keys are
// inherited from the inbound); tls shows the full TLS override set.
const security = (Form.useWatch('security', form) ?? 'same') as string;
const showTls = security === 'tls' || security === 'reality';
const showTlsExtras = security === 'tls';
useEffect(() => {
if (open) form.setFieldsValue(defaultsFor(host));
}, [open, host, form]);
const { nodes } = useNodesQuery();
const inboundSelectOptions = useMemo(
() => inboundOptions.map((ib) => ({
value: ib.id,
label: ib.remark || ib.tag || `#${ib.id}`,
})),
[inboundOptions],
);
const nodeSelectOptions = useMemo(
() => nodes
.filter((n) => n.guid)
.map((n) => ({ value: n.guid as string, label: n.name || n.remark || (n.guid as string) })),
[nodes],
);
const alpnOptions = useMemo(() => Object.values(ALPN_OPTION).map((v) => ({ value: v, label: v })), []);
const fpOptions = useMemo(() => Object.values(UTLS_FINGERPRINT).map((v) => ({ value: v, label: v })), []);
const onOk = async () => {
let values: FormShape;
try {
values = await form.validateFields();
} catch {
return;
}
const { enable, ...rest } = values;
const payload: Partial<HostFormValues> = { ...rest, isDisabled: !enable };
const res = await save(payload);
if (res?.success) {
message.success(t(mode === 'add' ? 'pages.hosts.toasts.add' : 'pages.hosts.toasts.update'));
onOpenChange(false);
} else if (res?.msg) {
message.error(res.msg);
}
};
return (
<Modal
open={open}
title={t(mode === 'add' ? 'pages.hosts.addHost' : 'pages.hosts.editHost')}
onOk={onOk}
onCancel={() => onOpenChange(false)}
okText={t('save')}
cancelText={t('cancel')}
destroyOnHidden
width={isMobile ? '95vw' : 760}
styles={{ body: { maxHeight: '70vh', overflowY: 'auto', overflowX: 'hidden' } }}
>
<Form
form={form}
colon={false}
labelCol={{ sm: { span: 8 } }}
wrapperCol={{ sm: { span: 14 } }}
labelWrap
initialValues={defaultsFor(host)}
preserve={false}
>
<Tabs
defaultActiveKey="basic"
items={[
{
key: 'basic',
forceRender: true,
label: catTabLabel(<ProfileOutlined />, t('pages.hosts.sections.basic'), isMobile),
children: (
<>
<Form.Item name="remark" label={t('pages.hosts.fields.remark')} tooltip={t('pages.hosts.hints.remark')} rules={[{ required: true, max: 256 }]}>
<Input maxLength={256} />
</Form.Item>
<Form.Item name="serverDescription" label={t('pages.hosts.fields.serverDescription')} tooltip={t('pages.hosts.hints.serverDescription')}>
<Input maxLength={64} />
</Form.Item>
<Form.Item name="inboundId" label={t('pages.hosts.fields.inbound')} rules={[{ required: true }]}>
<Select
options={inboundSelectOptions}
showSearch
optionFilterProp="label"
disabled={mode === 'edit'}
placeholder={t('pages.hosts.selectInbound')}
/>
</Form.Item>
<Form.Item name="address" label={t('pages.hosts.fields.address')} tooltip={t('pages.hosts.hints.address')}>
<Input placeholder="cdn.example.com" />
</Form.Item>
<Form.Item name="port" label={t('pages.hosts.fields.port')} tooltip={t('pages.hosts.hints.port')}>
<InputNumber min={0} max={65535} />
</Form.Item>
<Form.Item name="tags" label={t('pages.hosts.fields.tags')} tooltip={t('pages.hosts.hints.tags')}>
<Select mode="tags" allowClear tokenSeparators={[',']} />
</Form.Item>
<Form.Item name="nodeGuids" label={t('pages.hosts.fields.nodeGuids')} tooltip={t('pages.hosts.hints.nodeGuids')}>
<Select mode="multiple" allowClear options={nodeSelectOptions} optionFilterProp="label" />
</Form.Item>
<Form.Item name="enable" label={t('pages.hosts.fields.enable')} valuePropName="checked">
<Switch />
</Form.Item>
</>
),
},
{
key: 'security',
forceRender: true,
label: catTabLabel(<SafetyCertificateOutlined />, t('pages.hosts.sections.security'), isMobile),
children: (
<>
<Form.Item name="security" label={t('pages.hosts.fields.security')}>
<Select
options={['same', 'tls', 'none', 'reality'].map((v) => ({ value: v, label: v }))}
/>
</Form.Item>
{showTls && (
<>
<Form.Item name="sni" label={t('pages.hosts.fields.sni')}>
<Input />
</Form.Item>
<Form.Item name="overrideSniFromAddress" label={t('pages.hosts.fields.overrideSniFromAddress')} valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="keepSniBlank" label={t('pages.hosts.fields.keepSniBlank')} valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="fingerprint" label={t('pages.hosts.fields.fingerprint')}>
<Select allowClear options={fpOptions} />
</Form.Item>
</>
)}
{showTlsExtras && (
<>
<Form.Item name="alpn" label={t('pages.hosts.fields.alpn')}>
<Select mode="multiple" allowClear options={alpnOptions} />
</Form.Item>
<Form.Item name="pinnedPeerCertSha256" label={t('pages.hosts.fields.pins')}>
<Select mode="tags" allowClear tokenSeparators={[',']} />
</Form.Item>
<Form.Item name="verifyPeerCertByName" label={t('pages.hosts.fields.verifyPeerCertByName')} valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="allowInsecure" label={t('pages.hosts.fields.allowInsecure')} tooltip={t('pages.hosts.hints.allowInsecure')} valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="echConfigList" label={t('pages.hosts.fields.echConfigList')}>
<Input.TextArea rows={2} />
</Form.Item>
</>
)}
</>
),
},
{
key: 'advanced',
forceRender: true,
label: catTabLabel(<ControlOutlined />, t('pages.hosts.sections.advanced'), isMobile),
children: (
<Tabs
size="small"
defaultActiveKey="adv-general"
items={[
{
key: 'adv-general',
forceRender: true,
label: catTabLabel(<SettingOutlined />, t('pages.hosts.sections.general'), isMobile),
children: (
<>
<Form.Item name="hostHeader" label={t('pages.hosts.fields.hostHeader')}>
<Input />
</Form.Item>
<Form.Item name="path" label={t('pages.hosts.fields.path')}>
<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" />
</Form.Item>
<Form.Item name="excludeFromSubTypes" label={t('pages.hosts.fields.excludeFromSubTypes')}>
<Select
mode="multiple"
allowClear
options={['raw', 'json', 'clash'].map((v) => ({ value: v, label: v }))}
/>
</Form.Item>
</>
),
},
{
key: 'adv-mux',
forceRender: true,
label: catTabLabel(<PartitionOutlined />, t('pages.hosts.fields.muxParams'), isMobile),
children: (
<Form.Item name="muxParams" noStyle>
<HostMuxForm />
</Form.Item>
),
},
{
key: 'adv-sockopt',
forceRender: true,
label: catTabLabel(<DeploymentUnitOutlined />, t('pages.hosts.fields.sockoptParams'), isMobile),
children: (
<Form.Item name="sockoptParams" noStyle>
<HostSockoptForm />
</Form.Item>
),
},
{
key: 'adv-finalmask',
forceRender: true,
label: catTabLabel(<RocketOutlined />, t('pages.hosts.fields.finalMask'), isMobile),
children: (
<Form.Item name="finalMask" noStyle>
<HostFinalMaskForm />
</Form.Item>
),
},
]}
/>
),
},
{
key: 'clash',
forceRender: true,
label: catTabLabel(<NodeIndexOutlined />, t('pages.hosts.sections.clash'), isMobile),
children: (
<>
<Form.Item name="mihomoIpVersion" label={t('pages.hosts.fields.mihomoIpVersion')}>
<Select
allowClear
options={['dual', 'ipv4', 'ipv6', 'ipv4-prefer', 'ipv6-prefer'].map((v) => ({ value: v, label: v }))}
/>
</Form.Item>
<Form.Item name="mihomoX25519" label={t('pages.hosts.fields.mihomoX25519')} valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item name="shuffleHost" label={t('pages.hosts.fields.shuffleHost')} valuePropName="checked">
<Switch />
</Form.Item>
</>
),
},
]}
/>
</Form>
</Modal>
);
}
+58
View File
@@ -0,0 +1,58 @@
.hosts-card {
width: 100%;
}
.host-remark-cell {
display: flex;
flex-direction: column;
line-height: 1.3;
}
.host-remark {
font-weight: 500;
}
.host-desc {
font-size: 0.82em;
color: var(--ant-color-text-secondary);
}
.host-endpoint {
font-family: var(--font-mono, monospace);
font-size: 0.92em;
}
.host-muted {
color: var(--ant-color-text-quaternary);
}
/* card-toolbar is shared with the Clients/Inbounds list cards, but its rules
live in a lazily-loaded page stylesheet — re-declare here so the Hosts page
renders correctly when opened directly. */
.hosts-card .card-toolbar {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 6px 0;
}
@media (min-width: 769px) and (max-width: 920px) {
.hosts-card .card-toolbar {
gap: 6px;
}
}
/* Empty-table state. The shared .card-empty rule otherwise lives only in the
lazily-loaded Clients/Inbounds/Nodes stylesheets, so a direct /hosts refresh
would render it unstyled (faint + uncentered) until another page is visited.
Re-declare it here so it's correct on first load. */
.card-empty {
text-align: center;
color: var(--ant-color-text-secondary);
padding: 24px 12px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
+195
View File
@@ -0,0 +1,195 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Card, Space, Switch, Table, Tag, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
ArrowDownOutlined,
ArrowUpOutlined,
DeleteOutlined,
EditOutlined,
GlobalOutlined,
PlusOutlined,
} from '@ant-design/icons';
import type { HostRecord } from '@/api/queries/useHostsQuery';
import type { InboundOption } from '@/schemas/client';
import './HostList.css';
interface HostListProps {
hosts: HostRecord[];
inboundOptions: InboundOption[];
loading?: boolean;
isMobile?: boolean;
selectedIds: number[];
onSelectionChange: (ids: number[]) => void;
onAdd: () => void;
onEdit: (host: HostRecord) => void;
onDelete: (host: HostRecord) => void;
onToggleEnable: (host: HostRecord, next: boolean) => void;
onMove: (host: HostRecord, dir: 'up' | 'down') => void;
onBulkEnable: (enable: boolean) => void;
onBulkDelete: () => void;
}
// Sorted by inbound then sort_order then id — the same order the subscription
// renderer uses, so the list mirrors the emitted link order.
function sortHosts(hosts: HostRecord[]): HostRecord[] {
return [...hosts].sort((a, b) => {
if (a.inboundId !== b.inboundId) return a.inboundId - b.inboundId;
const sa = a.sortOrder ?? 0;
const sb = b.sortOrder ?? 0;
if (sa !== sb) return sa - sb;
return a.id - b.id;
});
}
export default function HostList(props: HostListProps) {
const { t } = useTranslation();
const {
hosts, inboundOptions, loading, isMobile, selectedIds, onSelectionChange,
onAdd, onEdit, onDelete, onToggleEnable, onMove, onBulkEnable, onBulkDelete,
} = props;
const inboundLabel = useMemo(() => {
const map = new Map<number, string>();
for (const ib of inboundOptions) map.set(ib.id, ib.remark || ib.tag || `#${ib.id}`);
return map;
}, [inboundOptions]);
const sorted = useMemo(() => sortHosts(hosts), [hosts]);
// Move is bounded to neighbours within the same inbound (sort_order is per-inbound).
const movable = useMemo(() => {
const byInbound = new Map<number, number>();
const idxInGroup = new Map<number, number>();
const counters = new Map<number, number>();
for (const h of sorted) byInbound.set(h.inboundId, (byInbound.get(h.inboundId) ?? 0) + 1);
for (const h of sorted) {
const c = counters.get(h.inboundId) ?? 0;
idxInGroup.set(h.id, c);
counters.set(h.inboundId, c + 1);
}
return { byInbound, idxInGroup };
}, [sorted]);
// Column order requested: Actions, Enable, then the rest.
const columns: ColumnsType<HostRecord> = [
{
title: t('pages.hosts.fields.actions'),
key: 'actions',
width: 168,
render: (_, h) => {
const idx = movable.idxInGroup.get(h.id) ?? 0;
const count = movable.byInbound.get(h.inboundId) ?? 1;
return (
<Space size={2}>
<Tooltip title={t('pages.hosts.moveUp')}>
<Button size="small" type="text" icon={<ArrowUpOutlined />} 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')} />
</Tooltip>
<Tooltip title={t('edit')}>
<Button size="small" type="text" icon={<EditOutlined />} onClick={() => onEdit(h)} />
</Tooltip>
<Tooltip title={t('delete')}>
<Button size="small" type="text" danger icon={<DeleteOutlined />} onClick={() => onDelete(h)} />
</Tooltip>
</Space>
);
},
},
{
title: t('pages.hosts.fields.enable'),
key: 'enable',
width: 90,
render: (_, h) => (
<Switch size="small" checked={!h.isDisabled} onChange={(next) => onToggleEnable(h, next)} />
),
},
{
title: t('pages.hosts.fields.remark'),
dataIndex: 'remark',
key: 'remark',
render: (_, h) => (
<div className="host-remark-cell">
<span className="host-remark">{h.remark}</span>
{h.serverDescription ? <span className="host-desc">{h.serverDescription}</span> : null}
</div>
),
},
{
title: t('pages.hosts.fields.endpoint'),
key: 'endpoint',
render: (_, h) => <span className="host-endpoint">{`${h.address || '—'}${h.port ? `:${h.port}` : ''}`}</span>,
},
{
title: t('pages.hosts.fields.inbound'),
key: 'inbound',
render: (_, h) => inboundLabel.get(h.inboundId) ?? `#${h.inboundId}`,
},
{
title: t('pages.hosts.fields.security'),
dataIndex: 'security',
key: 'security',
render: (security: string) => <Tag>{security || 'same'}</Tag>,
},
{
title: t('pages.hosts.fields.tags'),
key: 'tags',
render: (_, h) => (h.tags && h.tags.length > 0
? <Space size={[0, 4]} wrap>{h.tags.map((tag) => <Tag key={tag} color="blue">{tag}</Tag>)}</Space>
: <span className="host-muted"></span>),
},
];
const toolbar = (
<div className="card-toolbar">
{selectedIds.length === 0 ? (
<Button type="primary" icon={<PlusOutlined />} onClick={onAdd}>
{!isMobile && t('pages.hosts.addHost')}
</Button>
) : (
<>
<Tag
color="blue"
closable
onClose={() => onSelectionChange([])}
style={{ marginInlineEnd: 0, padding: '4px 8px', fontSize: 13 }}
>
{t('pages.hosts.selectedCount', { count: selectedIds.length })}
</Tag>
<Button onClick={() => onBulkEnable(true)}>{t('pages.hosts.bulkEnable')}</Button>
<Button onClick={() => onBulkEnable(false)}>{t('pages.hosts.bulkDisable')}</Button>
<Button danger icon={<DeleteOutlined />} onClick={onBulkDelete}>{t('pages.hosts.bulkDelete')}</Button>
</>
)}
</div>
);
return (
<Card size="small" hoverable title={toolbar} className="hosts-card">
<Table<HostRecord>
rowKey="id"
size="small"
loading={loading}
columns={columns}
dataSource={sorted}
pagination={false}
scroll={{ x: 'max-content' }}
rowSelection={{
selectedRowKeys: selectedIds,
onChange: (keys) => onSelectionChange(keys as number[]),
}}
locale={{
emptyText: (
<div className="card-empty">
<GlobalOutlined style={{ fontSize: 32, marginBottom: 8 }} />
<div>{t('noData')}</div>
</div>
),
}}
/>
</Card>
);
}
+210
View File
@@ -0,0 +1,210 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Card, Col, ConfigProvider, Layout, Modal, Result, Row, Spin, Statistic, message } from 'antd';
import { CheckCircleOutlined, GlobalOutlined, StopOutlined } from '@ant-design/icons';
import { useTheme } from '@/hooks/useTheme';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { useHostsQuery, type HostRecord } from '@/api/queries/useHostsQuery';
import { useHostMutations } from '@/api/queries/useHostMutations';
import { useInboundOptions } from '@/api/queries/useInboundOptions';
import AppSidebar from '@/layouts/AppSidebar';
import { setMessageInstance } from '@/utils/messageBus';
import type { HostFormValues } from '@/schemas/api/host';
import HostList from './HostList';
import HostFormModal from './HostFormModal';
// Hosts for one inbound in render order — used to compute a reorder payload.
function inboundHostsInOrder(hosts: HostRecord[], inboundId: number): HostRecord[] {
return hosts
.filter((h) => h.inboundId === inboundId)
.sort((a, b) => {
const sa = a.sortOrder ?? 0;
const sb = b.sortOrder ?? 0;
if (sa !== sb) return sa - sb;
return a.id - b.id;
});
}
export default function HostsPage() {
const { t } = useTranslation();
const { isDark, isUltra, antdThemeConfig } = useTheme();
const { isMobile } = useMediaQuery();
const [modal, modalContextHolder] = Modal.useModal();
const [messageApi, messageContextHolder] = message.useMessage();
useEffect(() => { setMessageInstance(messageApi); }, [messageApi]);
const { hosts, loading, fetched, fetchError, refetch } = useHostsQuery();
const { create, update, remove, setEnable, reorder, bulkSetEnable, bulkDel } = useHostMutations();
const { data: inboundOptions = [] } = useInboundOptions();
const [formOpen, setFormOpen] = useState(false);
const [formMode, setFormMode] = useState<'add' | 'edit'>('add');
const [formHost, setFormHost] = useState<HostRecord | null>(null);
const [selectedIds, setSelectedIds] = useState<number[]>([]);
const onAdd = useCallback(() => {
setFormMode('add');
setFormHost(null);
setFormOpen(true);
}, []);
const onEdit = useCallback((host: HostRecord) => {
setFormMode('edit');
setFormHost({ ...host });
setFormOpen(true);
}, []);
const onSave = useCallback(async (payload: Partial<HostFormValues>) => {
if (formMode === 'edit' && formHost?.id) {
return update(formHost.id, payload);
}
return create(payload);
}, [formMode, formHost, update, create]);
const onDelete = useCallback((host: HostRecord) => {
modal.confirm({
title: t('pages.hosts.deleteConfirmTitle', { name: host.remark }),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await remove(host.id);
if (msg?.success) messageApi.success(t('pages.hosts.toasts.delete'));
},
});
}, [modal, t, remove, messageApi]);
const onToggleEnable = useCallback(async (host: HostRecord, next: boolean) => {
await setEnable(host.id, next);
}, [setEnable]);
const onMove = useCallback(async (host: HostRecord, dir: 'up' | 'down') => {
const group = inboundHostsInOrder(hosts, host.inboundId);
const idx = group.findIndex((h) => h.id === host.id);
const swapWith = dir === 'up' ? idx - 1 : idx + 1;
if (idx < 0 || swapWith < 0 || swapWith >= group.length) return;
const ids = group.map((h) => h.id);
[ids[idx], ids[swapWith]] = [ids[swapWith], ids[idx]];
await reorder(ids);
}, [hosts, reorder]);
const onBulkEnable = useCallback(async (enable: boolean) => {
if (selectedIds.length === 0) return;
const msg = await bulkSetEnable(selectedIds, enable);
if (msg?.success) setSelectedIds([]);
}, [selectedIds, bulkSetEnable]);
const onBulkDelete = useCallback(() => {
if (selectedIds.length === 0) return;
modal.confirm({
title: t('pages.hosts.bulkDeleteConfirm', { count: selectedIds.length }),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await bulkDel(selectedIds);
if (msg?.success) {
messageApi.success(t('pages.hosts.toasts.delete'));
setSelectedIds([]);
}
},
});
}, [selectedIds, modal, t, bulkDel, messageApi]);
const summary = useMemo(() => {
const total = hosts.length;
const enabled = hosts.filter((h) => !h.isDisabled).length;
return { total, enabled, disabled: total - enabled };
}, [hosts]);
const pageClass = useMemo(() => {
const classes = ['hosts-page'];
if (isDark) classes.push('is-dark');
if (isUltra) classes.push('is-ultra');
return classes.join(' ');
}, [isDark, isUltra]);
return (
<ConfigProvider theme={antdThemeConfig}>
{messageContextHolder}
{modalContextHolder}
<Layout className={pageClass}>
<AppSidebar />
<Layout className="content-shell">
<Layout.Content id="content-layout" className="content-area">
<Spin spinning={!fetched} delay={200} size="large">
{!fetched ? (
<div className="loading-spacer" />
) : fetchError ? (
<Result
status="error"
title={t('somethingWentWrong')}
subTitle={fetchError}
extra={<Button type="primary" loading={loading} onClick={() => refetch()}>{t('refresh')}</Button>}
/>
) : (
<Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
<Col span={24}>
<Card size="small" hoverable className="summary-card">
<Row gutter={[16, 12]}>
<Col xs={8} sm={8} md={8}>
<Statistic
title={t('pages.hosts.summary.total')}
value={String(summary.total)}
prefix={<GlobalOutlined />}
/>
</Col>
<Col xs={8} sm={8} md={8}>
<Statistic
title={t('pages.hosts.summary.enabled')}
value={String(summary.enabled)}
prefix={<CheckCircleOutlined style={{ color: 'var(--ant-color-success)' }} />}
/>
</Col>
<Col xs={8} sm={8} md={8}>
<Statistic
title={t('pages.hosts.summary.disabled')}
value={String(summary.disabled)}
prefix={<StopOutlined style={{ color: 'var(--ant-color-text-quaternary)' }} />}
/>
</Col>
</Row>
</Card>
</Col>
<Col span={24}>
<HostList
hosts={hosts}
inboundOptions={inboundOptions}
loading={loading}
isMobile={isMobile}
selectedIds={selectedIds}
onSelectionChange={setSelectedIds}
onAdd={onAdd}
onEdit={onEdit}
onDelete={onDelete}
onToggleEnable={onToggleEnable}
onMove={onMove}
onBulkEnable={onBulkEnable}
onBulkDelete={onBulkDelete}
/>
</Col>
</Row>
)}
</Spin>
</Layout.Content>
</Layout>
<HostFormModal
open={formOpen}
mode={formMode}
host={formHost}
inboundOptions={inboundOptions}
save={onSave}
onOpenChange={setFormOpen}
/>
</Layout>
</ConfigProvider>
);
}
@@ -0,0 +1,55 @@
import { useEffect, useRef, useState } from 'react';
import { Form } from 'antd';
import { FinalMaskForm } from '@/lib/xray/forms/transport';
import type { FinalMaskStreamSettings } from '@/schemas/protocols/stream/finalmask';
// Per-host Final Mask editor — same shape as the sub-JSON settings one
// (SubJsonFinalMaskForm) but reused for a host: reads/writes the host's
// finalMask JSON string. The masks are merged into this host's JSON stream.
function hasValue(v: unknown): boolean {
if (v == null) return false;
if (Array.isArray(v)) return v.some(hasValue);
if (typeof v === 'object') return Object.values(v as Record<string, unknown>).some(hasValue);
if (typeof v === 'string') return v.length > 0;
return true;
}
function parseFinalMask(raw: string): FinalMaskStreamSettings {
try {
if (raw) return JSON.parse(raw) as FinalMaskStreamSettings;
} catch {
return { tcp: [], udp: [] };
}
return { tcp: [], udp: [] };
}
export default function HostFinalMaskForm({ value = '', onChange }: { value?: string; onChange?: (next: string) => void }) {
const [form] = Form.useForm();
const [initial] = useState(() => parseFinalMask(value));
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const finalmask = Form.useWatch('finalmask', form) as FinalMaskStreamSettings | undefined;
useEffect(() => {
if (finalmask === undefined) return;
const next = hasValue(finalmask) ? JSON.stringify(finalmask) : '';
if (next !== value) onChangeRef.current?.(next);
}, [finalmask, value]);
return (
<Form
form={form}
component={false}
colon={false}
labelCol={{ sm: { span: 8 } }}
wrapperCol={{ sm: { span: 14 } }}
labelWrap
initialValues={{ finalmask: initial }}
>
<FinalMaskForm name="finalmask" network="" protocol="" form={form} showAll />
</Form>
);
}
@@ -0,0 +1,25 @@
import { MuxForm } from '@/pages/xray/outbounds/transport';
import OutboundSubtreeJsonForm from './OutboundSubtreeJsonForm';
import { serializeOverride } from './helpers';
// Mux override editor — reuses the outbound MuxForm (same fields as the sub-JSON
// settings editor). Stored in the host's muxParams JSON string. Defaults match
// the sub-JSON editor; the host stores '' (= inherit the inbound/global mux)
// when the toggle is off, an explicit mux object when on.
const DEFAULT_MUX = { enabled: false, concurrency: 8, xudpConcurrency: 16, xudpProxyUDP443: 'reject' };
export default function HostMuxForm({ value, onChange }: { value?: string; onChange?: (next: string) => void }) {
return (
<OutboundSubtreeJsonForm
value={value}
onChange={onChange}
path={['mux']}
defaultSubtree={DEFAULT_MUX}
serialize={(mux) => ((mux as { enabled?: boolean } | undefined)?.enabled ? serializeOverride(mux) : '')}
// protocol/network are fixed only to satisfy MuxForm's isMuxAllowed gate;
// a host's mux override is protocol-agnostic and should always be editable.
render={(form) => <MuxForm form={form} protocol="vmess" network="tcp" />}
/>
);
}
@@ -0,0 +1,43 @@
import { SockoptForm } from '@/pages/xray/outbounds/transport';
import { useOutboundTagGroups } from '@/api/queries/useOutboundTags';
import OutboundSubtreeJsonForm from './OutboundSubtreeJsonForm';
import { serializeOverride } from './helpers';
// Sockopt override editor — reuses the outbound SockoptForm (which carries its
// own enable Switch and writes streamSettings.sockopt). Serialized to the host's
// sockoptParams JSON string.
//
// A host is the client/dialer side, so the inbound-only sockopt keys are dropped
// from the output. Verified against xray-core transport/internet/sockopt_*.go:
// only V6Only and the handler-level acceptProxyProtocol / trustedXForwardedFor
// are inbound-only — tproxy (IP_TRANSPARENT) and keepalive/interface ARE applied
// on the outbound/dialer socket, so they stay. The outbound form no longer shows
// the inbound-only keys, but its default object still seeds them, so strip here.
const INBOUND_ONLY_SOCKOPT = ['acceptProxyProtocol', 'V6Only', 'trustedXForwardedFor'];
function serializeClientSockopt(sockopt: unknown): string {
if (!sockopt || typeof sockopt !== 'object') return serializeOverride(sockopt);
const copy = { ...(sockopt as Record<string, unknown>) };
for (const key of INBOUND_ONLY_SOCKOPT) delete copy[key];
return serializeOverride(copy);
}
export default function HostSockoptForm({ value, onChange }: { value?: string; onChange?: (next: string) => void }) {
// Populate the dialerProxy dropdown with the panel's outbound tags (a host can
// chain through one of the subscription's outbounds by tag). dialerProxy chains
// through a single outbound, so balancers (routing targets) are excluded — only
// the outbound group is used; blackhole is dropped too (chaining to it just
// drops the traffic).
const { data: tagGroups } = useOutboundTagGroups({ excludeBlackhole: true });
const outboundTags = tagGroups?.outbounds ?? [];
return (
<OutboundSubtreeJsonForm
value={value}
onChange={onChange}
path={['streamSettings', 'sockopt']}
serialize={serializeClientSockopt}
render={(form) => <SockoptForm form={form} outboundTags={outboundTags} />}
/>
);
}
@@ -0,0 +1,68 @@
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { Form, type FormInstance } from 'antd';
import type { OutboundFormValues } from '@/schemas/forms/outbound-form';
import { nestAtPath, parseJsonObject, serializeOverride } from './helpers';
interface OutboundSubtreeJsonFormProps {
value?: string;
onChange?: (next: string) => void;
// Form path the inner form edits, e.g. ['streamSettings', 'sockopt'] or ['mux'].
path: (string | number)[];
// Renders the reused outbound form given this wrapper's own form instance.
render: (form: FormInstance<OutboundFormValues>) => ReactNode;
// Seeds the form when the stored value is empty, so toggling a section on
// pre-fills sensible defaults instead of blanks (used by Mux).
defaultSubtree?: Record<string, unknown>;
// Turns the edited subtree into the stored JSON string (default: prune empties).
// Mux overrides this to store '' (= inherit) when its enable flag is off.
serialize?: (subtree: unknown) => string;
}
// Hosts the reused outbound transport forms (which bind to fixed form paths)
// inside an isolated antd Form, mirroring SubJsonFinalMaskForm: seed the form
// from the JSON string, watch the edited subtree, and report a JSON string back
// to the parent host form. component={false} avoids a nested <form> DOM node.
export default function OutboundSubtreeJsonForm({
value = '',
onChange,
path,
render,
defaultSubtree,
serialize = serializeOverride,
}: OutboundSubtreeJsonFormProps) {
const [form] = Form.useForm();
const [initial] = useState<Record<string, unknown>>(() => {
const parsed = parseJsonObject(value);
return Object.keys(parsed).length ? parsed : (defaultSubtree ?? {});
});
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const subtree = Form.useWatch(path, form);
useEffect(() => {
const next = serialize(subtree);
if (next !== value) onChangeRef.current?.(next);
// serialize is logically stable; re-run only when the edited subtree changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [subtree, value]);
const hasInitial = Object.keys(initial).length > 0;
const initialValues = nestAtPath(path, hasInitial ? initial : undefined);
return (
<Form
form={form}
component={false}
colon={false}
labelCol={{ sm: { span: 8 } }}
wrapperCol={{ sm: { span: 14 } }}
labelWrap
initialValues={initialValues}
>
{render(form as unknown as FormInstance<OutboundFormValues>)}
</Form>
);
}
@@ -0,0 +1,50 @@
// Shared helpers for the host's structured JSON-override editors. Each host
// override is persisted as a JSON string (muxParams / sockoptParams /
// finalMask); these convert between that string and the object the reused
// outbound/sub-JSON forms edit.
export function parseJsonObject(raw: string): Record<string, unknown> {
if (!raw) return {};
try {
const v = JSON.parse(raw);
return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
} catch {
return {};
}
}
// Recursively drop '', null, undefined, and empty arrays/objects so an override
// stays sparse — only the keys the operator actually set are emitted and merged
// into the inbound stream. 0 and false are kept (meaningful sockopt/mux values).
export function pruneEmptyDeep(value: unknown): unknown {
if (Array.isArray(value)) {
const arr = value.map(pruneEmptyDeep).filter((v) => v !== undefined);
return arr.length ? arr : undefined;
}
if (value && typeof value === 'object') {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
const pv = pruneEmptyDeep(v);
if (pv !== undefined) out[k] = pv;
}
return Object.keys(out).length ? out : undefined;
}
if (value === '' || value === null) return undefined;
return value;
}
// Prune then stringify; an all-empty override serializes to '' (= no override).
export function serializeOverride(value: unknown): string {
const pruned = pruneEmptyDeep(value);
return pruned === undefined ? '' : JSON.stringify(pruned);
}
// Build a nested object { a: { b: leaf } } from a form path ['a','b'] so the
// inner form can be seeded with initialValues at the exact path it edits.
export function nestAtPath(path: (string | number)[], leaf: unknown): Record<string, unknown> {
let acc: unknown = leaf;
for (let i = path.length - 1; i >= 0; i -= 1) {
acc = { [path[i]]: acc };
}
return acc as Record<string, unknown>;
}
@@ -0,0 +1,3 @@
export { default as HostMuxForm } from './HostMuxForm';
export { default as HostSockoptForm } from './HostSockoptForm';
export { default as HostFinalMaskForm } from './HostFinalMaskForm';
+2 -7
View File
@@ -90,7 +90,6 @@ export default function InboundsPage() {
subSettings,
tgBotEnable,
ipLimitEnable,
remarkModel,
refresh,
hydrateInbound,
applyTrafficEvent,
@@ -265,13 +264,12 @@ export default function InboundsPage() {
content: genInboundLinks({
inbound: inboundFromDb(projected),
remark: projected.remark,
remarkModel,
hostOverride: hostOverrideFor(dbInbound),
fallbackHostname: preferPublicHost(window.location.hostname, subSettings.publicHost),
}),
fileName: projected.remark || 'inbound',
});
}, [checkFallback, remarkModel, hostOverrideFor, subSettings.publicHost, openText, t]);
}, [checkFallback, hostOverrideFor, subSettings.publicHost, openText, t]);
const exportInboundClipboard = useCallback((dbInbound: DBInbound) => {
openText({ title: t('pages.inbounds.inboundJsonTitle'), content: JSON.stringify(dbInbound, null, 2), json: true });
@@ -303,13 +301,12 @@ export default function InboundsPage() {
out.push(genInboundLinks({
inbound: inboundFromDb(projected),
remark: projected.remark,
remarkModel,
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, remarkModel, hostOverrideFor, subSettings.publicHost, openText, t]);
}, [dbInbounds, hydrateInbound, checkFallback, hostOverrideFor, subSettings.publicHost, openText, t]);
const exportAllSubs = useCallback(async () => {
const hydrated = await Promise.all(
@@ -658,7 +655,6 @@ export default function InboundsPage() {
onClose={() => setInfoOpen(false)}
dbInbound={infoDbInbound}
clientIndex={infoClientIndex}
remarkModel={remarkModel}
expireDiff={expireDiff}
trafficDiff={trafficDiff}
ipLimitEnable={ipLimitEnable}
@@ -674,7 +670,6 @@ export default function InboundsPage() {
onClose={() => setQrOpen(false)}
dbInbound={qrDbInbound}
client={null}
remarkModel={remarkModel}
nodeAddress={qrNodeAddress}
subSettings={subSettings}
/>
@@ -65,7 +65,6 @@ import {
WireguardFields,
} from './protocols';
import {
ExternalProxyForm,
GrpcForm,
HttpUpgradeForm,
KcpForm,
@@ -251,23 +250,6 @@ export default function InboundFormModal({
onSecurityChange,
} = useSecurityActions({ form, setSaving, messageApi, nodeId: typeof wNodeId === 'number' ? wNodeId : null });
const toggleExternalProxy = (on: boolean) => {
if (on) {
const port = (form.getFieldValue('port') as number) ?? 443;
form.setFieldValue(['streamSettings', 'externalProxy'], [{
forceTls: 'same',
dest: typeof window !== 'undefined' ? window.location.hostname : '',
port,
remark: '',
sni: '',
fingerprint: '',
alpn: [],
pinnedPeerCertSha256: [],
}]);
} else {
form.setFieldValue(['streamSettings', 'externalProxy'], []);
}
};
const toggleSockopt = (on: boolean) => {
if (on) {
@@ -703,7 +685,7 @@ export default function InboundFormModal({
className="mt-12"
type="info"
showIcon
message={t('pages.inbounds.fallbacks.needsTls')}
title={t('pages.inbounds.fallbacks.needsTls')}
/>
)}
</>
@@ -811,12 +793,9 @@ export default function InboundFormModal({
</>
)}
{/* externalProxy only feeds client share links. Wireguard's per-peer
.conf fanout resolves its host elsewhere, and tunnel (dokodemo-door)
has no clients at all — the section is dead weight on both. */}
{protocol !== Protocols.WIREGUARD && protocol !== Protocols.TUNNEL && (
<ExternalProxyForm toggleExternalProxy={toggleExternalProxy} />
)}
{/* The legacy externalProxy section is replaced by the Hosts page; the
field is still parsed/rendered for backward compatibility but is no
longer editable here. */}
<SockoptForm toggleSockopt={toggleSockopt} network={network as string} />
@@ -1,209 +0,0 @@
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, InputNumber, Select, Space, Switch } from 'antd';
import { DeleteOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { ALPN_OPTION, UTLS_FINGERPRINT } from '@/schemas/primitives';
import './external-proxy.css';
const newEntry = () => ({
forceTls: 'same',
dest: '',
port: 443,
remark: '',
sni: '',
fingerprint: '',
alpn: [],
pinnedPeerCertSha256: [],
echConfigList: '',
});
function Field({ label, children }: { label: ReactNode; children: ReactNode }) {
return (
<div className="ext-proxy-field">
<span className="ext-proxy-flabel">{label}</span>
{children}
</div>
);
}
export default function ExternalProxyForm({
toggleExternalProxy,
}: {
toggleExternalProxy: (on: boolean) => void;
}) {
const { t } = useTranslation();
const form = Form.useFormInstance();
const generateRandomPin = (name: number) => {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
const hash = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
const path = ['streamSettings', 'externalProxy', name, 'pinnedPeerCertSha256'];
const current = (form.getFieldValue(path) as string[] | undefined) ?? [];
form.setFieldValue(path, [...current, hash]);
};
return (
<Form.Item
noStyle
shouldUpdate={(prev, curr) => {
const a = (prev.streamSettings as { externalProxy?: unknown[] } | undefined)?.externalProxy;
const b = (curr.streamSettings as { externalProxy?: unknown[] } | undefined)?.externalProxy;
return (Array.isArray(a) ? a.length : 0) !== (Array.isArray(b) ? b.length : 0);
}}
>
{({ getFieldValue }) => {
const arr = getFieldValue(['streamSettings', 'externalProxy']);
const on = Array.isArray(arr) && arr.length > 0;
return (
<>
<Form.Item label={t('pages.inbounds.form.externalProxy')}>
<Switch checked={on} onChange={toggleExternalProxy} />
</Form.Item>
{on && (
<Form.Item wrapperCol={{ span: 24 }}>
<Form.List name={['streamSettings', 'externalProxy']}>
{(fields, { add, remove }) => (
<>
<div className="ext-proxy-list">
{fields.map((field, idx) => (
<div key={field.key} className="ext-proxy-card">
<div className="ext-proxy-card__head">
<span className="ext-proxy-card__title">#{idx + 1}</span>
<Button
size="small"
type="text"
danger
icon={<DeleteOutlined />}
onClick={() => remove(field.name)}
/>
</div>
<div className="ext-proxy-grid ext-proxy-grid--dest">
<Field label={t('pages.inbounds.form.forceTls')}>
<Form.Item name={[field.name, 'forceTls']} noStyle>
<Select
style={{ width: '100%' }}
options={[
{ value: 'same', label: t('pages.inbounds.same') },
{ value: 'none', label: t('none') },
{ value: 'tls', label: 'TLS' },
]}
/>
</Form.Item>
</Field>
<Field label={t('pages.inbounds.address')}>
<Form.Item name={[field.name, 'dest']} noStyle>
<Input placeholder={t('pages.inbounds.address')} />
</Form.Item>
</Field>
<Field label={t('pages.inbounds.port')}>
<Form.Item name={[field.name, 'port']} noStyle>
<InputNumber style={{ width: '100%' }} min={1} max={65535} />
</Form.Item>
</Field>
</div>
<Field label={t('pages.inbounds.remark')}>
<Form.Item name={[field.name, 'remark']} noStyle>
<Input placeholder={t('pages.inbounds.remark')} />
</Form.Item>
</Field>
<Form.Item
noStyle
shouldUpdate={(prev, curr) =>
prev.streamSettings?.externalProxy?.[field.name]?.forceTls
!== curr.streamSettings?.externalProxy?.[field.name]?.forceTls
}
>
{({ getFieldValue }) => {
const ft = getFieldValue([
'streamSettings', 'externalProxy', field.name, 'forceTls',
]);
if (ft !== 'tls') return null;
return (
<div className="ext-proxy-tls">
<div className="ext-proxy-grid ext-proxy-grid--tls">
<Field label="SNI">
<Form.Item name={[field.name, 'sni']} noStyle>
<Input placeholder={t('pages.inbounds.form.serverNameIndication')} />
</Form.Item>
</Field>
<Field label={t('pages.inbounds.form.fingerprint')}>
<Form.Item name={[field.name, 'fingerprint']} noStyle>
<Select
style={{ width: '100%' }}
placeholder={t('pages.inbounds.form.fingerprint')}
options={[
{ value: '', label: t('pages.inbounds.form.defaultOption') },
...Object.values(UTLS_FINGERPRINT).map((fp) => ({
value: fp,
label: fp,
})),
]}
/>
</Form.Item>
</Field>
<Field label="ALPN">
<Form.Item name={[field.name, 'alpn']} noStyle>
<Select
mode="multiple"
style={{ width: '100%' }}
placeholder="ALPN"
options={Object.values(ALPN_OPTION).map((a) => ({
value: a,
label: a,
}))}
/>
</Form.Item>
</Field>
</div>
<Field label={t('pages.inbounds.form.echConfig')}>
<Form.Item name={[field.name, 'echConfigList']} noStyle>
<Input placeholder={t('pages.inbounds.form.echConfig')} />
</Form.Item>
</Field>
<Field label={t('pages.inbounds.form.pinnedPeerCertSha256')}>
<Space.Compact block>
<Form.Item name={[field.name, 'pinnedPeerCertSha256']} noStyle>
<Select
mode="tags"
tokenSeparators={[',', ' ']}
placeholder={t('pages.inbounds.form.pinnedPeerCertSha256Placeholder')}
style={{ width: 'calc(100% - 32px)' }}
/>
</Form.Item>
<Button
icon={<ReloadOutlined />}
onClick={() => generateRandomPin(field.name)}
title={t('pages.inbounds.form.generateRandomPin')}
/>
</Space.Compact>
</Field>
</div>
);
}}
</Form.Item>
</div>
))}
</div>
<Button
className="ext-proxy-add"
block
type="dashed"
icon={<PlusOutlined />}
onClick={() => add(newEntry())}
>
{t('add')}
</Button>
</>
)}
</Form.List>
</Form.Item>
)}
</>
);
}}
</Form.Item>
);
}
@@ -4,5 +4,4 @@ export { default as GrpcForm } from './grpc';
export { default as XhttpForm } from './xhttp';
export { default as HttpUpgradeForm } from './httpupgrade';
export { default as KcpForm } from './kcp';
export { default as ExternalProxyForm } from './external-proxy';
export { default as SockoptForm } from './sockopt';
@@ -1,12 +1,8 @@
import { useTranslation } from 'react-i18next';
import { Alert, Button, Form, Input, InputNumber, Segmented, Select, Space, Switch } from 'antd';
import { Alert, Form, InputNumber, Segmented, Select, Switch } from 'antd';
import {
Address_Port_Strategy,
DOMAIN_STRATEGY_OPTION,
TCP_CONGESTION_OPTION,
} from '@/schemas/primitives';
import { HappyEyeballsSchema } from '@/schemas/protocols/stream/sockopt';
import { CustomSockoptList } from '@/components/form';
import { TCP_CONGESTION_OPTION } from '@/schemas/primitives';
// Transport key that carries its own acceptProxyProtocol field (mirrored
// alongside the sockopt-level one so the PROXY preset never silently no-ops).
@@ -157,7 +153,7 @@ export default function SockoptForm({
type="warning"
showIcon
style={{ marginBottom: 16 }}
message={t('pages.inbounds.form.realClientIpTrustedHeaderTransportWarn')}
title={t('pages.inbounds.form.realClientIpTrustedHeaderTransportWarn')}
/>
)}
{proxyMismatch && (
@@ -165,7 +161,7 @@ export default function SockoptForm({
type="warning"
showIcon
style={{ marginBottom: 16 }}
message={t('pages.inbounds.form.realClientIpProxyProtocolTransportWarn')}
title={t('pages.inbounds.form.realClientIpProxyProtocolTransportWarn')}
/>
)}
</>
@@ -218,13 +214,6 @@ export default function SockoptForm({
>
<Switch />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'tcpMptcp']}
label={t('pages.inbounds.form.multipathTcp')}
valuePropName="checked"
>
<Switch />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'penetrate']}
label={t('pages.inbounds.form.penetrate')}
@@ -239,15 +228,6 @@ export default function SockoptForm({
>
<Switch />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'domainStrategy']}
label={t('pages.xray.wireguard.domainStrategy')}
>
<Select
style={{ width: '50%' }}
options={Object.values(DOMAIN_STRATEGY_OPTION).map((d) => ({ value: d, label: d }))}
/>
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'tcpcongestion']}
label={t('pages.inbounds.form.tcpCongestion')}
@@ -267,15 +247,6 @@ export default function SockoptForm({
]}
/>
</Form.Item>
<Form.Item name={['streamSettings', 'sockopt', 'dialerProxy']} label={t('pages.inbounds.form.dialerProxy')}>
<Input />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'interface']}
label={t('pages.inbounds.info.interfaceName')}
>
<Input />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'trustedXForwardedFor']}
label={t('pages.inbounds.form.trustedXForwardedFor')}
@@ -293,115 +264,7 @@ export default function SockoptForm({
]}
/>
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'addressPortStrategy']}
label={t('pages.inbounds.form.addressPortStrategy')}
>
<Select
style={{ width: '50%' }}
options={Object.values(Address_Port_Strategy).map((v) => ({ value: v, label: v }))}
/>
</Form.Item>
<Form.Item shouldUpdate noStyle>
{({ getFieldValue, setFieldValue }) => {
const he = getFieldValue(['streamSettings', 'sockopt', 'happyEyeballs']);
const hasHe = he != null;
return (
<>
<Form.Item label="Happy Eyeballs">
<Switch
checked={hasHe}
onChange={(v) => {
setFieldValue(
['streamSettings', 'sockopt', 'happyEyeballs'],
v ? HappyEyeballsSchema.parse({}) : undefined,
);
}}
/>
</Form.Item>
{hasHe && (
<>
<Form.Item
name={['streamSettings', 'sockopt', 'happyEyeballs', 'tryDelayMs']}
label={t('pages.inbounds.form.tryDelayMs')}
>
<InputNumber min={0} placeholder="0 disabled — 250 recommended" />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'happyEyeballs', 'prioritizeIPv6']}
label={t('pages.inbounds.form.prioritizeIPv6')}
valuePropName="checked"
>
<Switch />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'happyEyeballs', 'interleave']}
label={t('pages.inbounds.form.interleave')}
>
<InputNumber min={1} />
</Form.Item>
<Form.Item
name={['streamSettings', 'sockopt', 'happyEyeballs', 'maxConcurrentTry']}
label={t('pages.inbounds.form.maxConcurrentTry')}
>
<InputNumber min={0} />
</Form.Item>
</>
)}
</>
);
}}
</Form.Item>
<Form.List name={['streamSettings', 'sockopt', 'customSockopt']}>
{(fields, { add, remove }) => (
<>
<Form.Item label={t('pages.inbounds.form.customSockopt')}>
<Button
type="dashed"
size="small"
onClick={() => add({ type: 'int', level: '6', opt: '', value: '' })}
>
+ {t('pages.inbounds.form.addCustomOption')}
</Button>
</Form.Item>
{fields.map((field) => (
<Space.Compact key={field.key} style={{ display: 'flex', marginBottom: 8 }}>
<Form.Item name={[field.name, 'system']} noStyle>
<Select
placeholder="all"
allowClear
style={{ width: 100 }}
options={[
{ value: 'linux', label: 'linux' },
{ value: 'windows', label: 'windows' },
{ value: 'darwin', label: 'darwin' },
]}
/>
</Form.Item>
<Form.Item name={[field.name, 'type']} noStyle>
<Select
style={{ width: 80 }}
options={[
{ value: 'int', label: 'int' },
{ value: 'str', label: 'str' },
]}
/>
</Form.Item>
<Form.Item name={[field.name, 'level']} noStyle>
<Input placeholder="level (6=TCP)" style={{ width: 100 }} />
</Form.Item>
<Form.Item name={[field.name, 'opt']} noStyle>
<Input placeholder="opt" style={{ width: 120 }} />
</Form.Item>
<Form.Item name={[field.name, 'value']} noStyle>
<Input placeholder="value" style={{ flex: 1 }} />
</Form.Item>
<Button danger onClick={() => remove(field.name)}></Button>
</Space.Compact>
))}
</>
)}
</Form.List>
<CustomSockoptList />
</>
)}
</>
@@ -31,7 +31,6 @@ export default function InboundInfoModal({
onClose,
dbInbound,
clientIndex = 0,
remarkModel = '-io',
expireDiff = 0,
trafficDiff = 0,
ipLimitEnable = false,
@@ -120,7 +119,6 @@ export default function InboundInfoModal({
genWireguardConfigs({
inbound: inboundForLinks,
remark: dbInbound.remark,
remarkModel: '-io',
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
@@ -129,7 +127,6 @@ export default function InboundInfoModal({
genWireguardLinks({
inbound: inboundForLinks,
remark: dbInbound.remark,
remarkModel: '-io',
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
@@ -140,7 +137,6 @@ export default function InboundInfoModal({
genAllLinks({
inbound: inboundForLinks,
remark: dbInbound.remark,
remarkModel,
client: (clientSet ?? {}) as Parameters<typeof genAllLinks>[0]['client'],
hostOverride: nodeAddress,
fallbackHostname,
@@ -189,7 +185,7 @@ export default function InboundInfoModal({
}
});
}
}, [open, dbInbound, clientIndex, remarkModel, nodeAddress, subSettings, ipLimitEnable, t]);
}, [open, dbInbound, clientIndex, nodeAddress, subSettings, ipLimitEnable, t]);
const isEnable = useMemo(() => {
if (clientSettings) return !!clientSettings.enable;
@@ -76,7 +76,6 @@ export interface InboundInfoModalProps {
onClose: () => void;
dbInbound: DBInboundLike | null;
clientIndex?: number;
remarkModel?: string;
expireDiff?: number;
trafficDiff?: number;
ipLimitEnable?: boolean;
@@ -26,7 +26,6 @@ interface QrCodeModalProps {
onClose: () => void;
dbInbound: (DbInboundLike & { remark?: string }) | null;
client?: ClientSetting | null;
remarkModel?: string;
nodeAddress?: string;
subSettings?: SubSettings;
}
@@ -43,7 +42,6 @@ export default function QrCodeModal({
onClose,
dbInbound,
client = null,
remarkModel = '-io',
nodeAddress = '',
subSettings,
}: QrCodeModalProps) {
@@ -67,7 +65,6 @@ export default function QrCodeModal({
genWireguardConfigs({
inbound,
remark: peerRemark,
remarkModel: '-io',
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
@@ -76,7 +73,6 @@ export default function QrCodeModal({
genWireguardLinks({
inbound,
remark: peerRemark,
remarkModel: '-io',
hostOverride: nodeAddress,
fallbackHostname,
}).split('\r\n'),
@@ -87,7 +83,6 @@ export default function QrCodeModal({
genAllLinks({
inbound,
remark: dbInbound.remark || '',
remarkModel,
client: client ?? {},
hostOverride: nodeAddress,
fallbackHostname,
@@ -106,7 +101,7 @@ export default function QrCodeModal({
}
setSubLink(nextSub);
setSubJsonLink(nextSubJson);
}, [open, dbInbound, client, remarkModel, nodeAddress, subSettings]);
}, [open, dbInbound, client, nodeAddress, subSettings]);
const qrItems = useMemo<QrItem[]>(() => {
const items: QrItem[] = [];
@@ -161,7 +161,6 @@ export function useInbounds() {
const tgBotEnable = !!defaults.tgBotEnable;
const ipLimitEnable = !!defaults.ipLimitEnable;
const pageSize = defaults.pageSize ?? 0;
const remarkModel = defaults.remarkModel || '-io';
const datepicker = (defaults.datepicker as 'gregorian' | 'jalalian') || 'gregorian';
const subSettings: SubSettings = useMemo(() => ({
@@ -528,7 +527,6 @@ export function useInbounds() {
expireDiff,
trafficDiff,
subSettings,
remarkModel,
datepicker,
tgBotEnable,
ipLimitEnable,
+1 -1
View File
@@ -102,7 +102,7 @@ export default function EmailTab({ allSetting, updateSetting }: EmailTabProps) {
{testResult && (
<Alert
type={testResult.success ? 'success' : 'error'}
message={
title={
testResult.success
? t('pages.settings.' + testResult.msg)
: <span><b>{stageLabel[testResult.stage || ''] || testResult.stage}:</b> {t('pages.settings.' + testResult.msg)}</span>
@@ -1,17 +1,13 @@
import { useMemo } from 'react';
import { Input, InputNumber, Select, Space, Switch, Tabs } from 'antd';
import { Input, InputNumber, Switch, Tabs } from 'antd';
import { BranchesOutlined, IdcardOutlined, InfoCircleOutlined, NodeIndexOutlined, SafetyCertificateOutlined, SettingOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import type { AllSetting } from '@/models/setting';
import { SettingListItem } from '@/components/ui';
import { RemarkTemplateField } from '@/components/form';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel';
import { sanitizePath, normalizePath } from './uriPath';
const REMARK_MODELS: Record<string, string> = { i: 'Inbound', e: 'Email', o: 'External Proxy' };
const REMARK_SAMPLES: Record<string, string> = { i: 'Germany', e: 'john', o: 'Relay' };
const REMARK_SEPARATORS = [' ', '-', '_', '@', ':', '~', '|', ',', '.', '/'];
interface SubscriptionGeneralTabProps {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
@@ -21,30 +17,6 @@ export default function SubscriptionGeneralTab({ allSetting, updateSetting }: Su
const { t } = useTranslation();
const { isMobile } = useMediaQuery();
const remarkModel = useMemo(() => {
const rm = allSetting.remarkModel || '';
return rm.length > 1 ? rm.substring(1).split('') : [];
}, [allSetting.remarkModel]);
const remarkSeparator = useMemo(() => {
const rm = allSetting.remarkModel || '-';
return rm.length > 1 ? rm.charAt(0) : '-';
}, [allSetting.remarkModel]);
const remarkSample = useMemo(() => {
const parts = remarkModel.map((k) => REMARK_SAMPLES[k]);
return parts.length === 0 ? '' : parts.join(remarkSeparator);
}, [remarkModel, remarkSeparator]);
function setRemarkModel(parts: string[]) {
updateSetting({ remarkModel: remarkSeparator + parts.join('') });
}
function setRemarkSeparator(sep: string) {
const tail = (allSetting.remarkModel || '-').substring(1);
updateSetting({ remarkModel: sep + tail });
}
return (
<Tabs defaultActiveKey="1" items={[
{
@@ -94,49 +66,16 @@ export default function SubscriptionGeneralTab({ allSetting, updateSetting }: Su
<SettingListItem paddings="small" title={t('pages.settings.subEncrypt')} description={t('pages.settings.subEncryptDesc')}>
<Switch checked={allSetting.subEncrypt} onChange={(v) => updateSetting({ subEncrypt: v })} />
</SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.subShowInfo')} description={t('pages.settings.subShowInfoDesc')}>
<Switch checked={allSetting.subShowInfo} onChange={(v) => updateSetting({ subShowInfo: v })} />
</SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.subEmailInRemark')} description={t('pages.settings.subEmailInRemarkDesc')}>
<Switch checked={allSetting.subEmailInRemark} onChange={(v) => updateSetting({ subEmailInRemark: v })} />
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.remarkModel')}
description={
<>
{t('pages.settings.sampleRemark')}:{' '}
<span
style={{
fontFamily: 'monospace',
padding: '1px 6px',
borderRadius: 4,
border: '1px solid var(--ant-color-border)',
background: 'var(--ant-color-fill-tertiary)',
whiteSpace: 'pre',
}}
>
{remarkSample ? `#${remarkSample}` : '—'}
</span>
</>
}
title={t('pages.settings.remarkTemplate')}
description={t('pages.settings.remarkTemplateDesc')}
>
<Space.Compact style={{ width: '100%' }}>
<Select
mode="multiple"
value={remarkModel}
onChange={setRemarkModel}
style={{ paddingRight: '.5rem', minWidth: '80%', width: 'auto' }}
options={Object.entries(REMARK_MODELS).map(([k, l]) => ({ value: k, label: l }))}
/>
<Select
value={remarkSeparator}
onChange={setRemarkSeparator}
style={{ width: '20%' }}
options={REMARK_SEPARATORS.map((s) => ({ value: s, label: s === ' ' ? '␣' : s }))}
/>
</Space.Compact>
<RemarkTemplateField
value={allSetting.remarkTemplate}
onChange={(v) => updateSetting({ remarkTemplate: v })}
maxLength={256}
/>
</SettingListItem>
<SettingListItem paddings="small" title={t('pages.settings.subUpdates')} description={t('pages.settings.subUpdatesDesc')}>
+1 -1
View File
@@ -222,7 +222,7 @@ export default function TelegramTab({ allSetting, updateSetting }: TelegramTabPr
{testResult && (
<Alert
type={testResult.success ? 'success' : 'error'}
message={testResult.msg}
title={testResult.msg}
showIcon
closable
onClose={() => setTestResult(null)}
+3 -1
View File
@@ -58,6 +58,7 @@ const subClashUrl = subData.subClashUrl || '';
const subTitle = subData.subTitle || '';
const links: string[] = Array.isArray(subData.links) ? subData.links : [];
const linkEmails: string[] = Array.isArray(subData.emails) ? subData.emails : [];
const subEmail = [...new Set(linkEmails.filter(Boolean))].join(', ');
const datepicker = subData.datepicker || 'gregorian';
const isUnlimited = totalByte <= 0 && expireMs === 0;
@@ -149,6 +150,7 @@ export default function SubPage() {
const descriptionsItems = useMemo(() => {
const items = [
{ key: 'subId', label: t('subscription.subId'), children: sId },
...(subEmail ? [{ key: 'email', label: t('subscription.email'), children: subEmail }] : []),
{
key: 'status',
label: t('subscription.status'),
@@ -413,7 +415,7 @@ export default function SubPage() {
</div>
</div>
{links.map((link, idx) => {
const parts = parseLinkParts(link, linkEmails[idx] || '');
const parts = parseLinkParts(link);
const fallback = `Link ${idx + 1}`;
const rowTitle = parts?.remark || fallback;
const qrLabel = [parts?.remark, linkEmails[idx]].filter(Boolean).join('-') || rowTitle;
@@ -8,6 +8,7 @@ import {
VerticalAlignTopOutlined,
ThunderboltOutlined,
LoadingOutlined,
ExportOutlined,
} from '@ant-design/icons';
import { SizeFormatter } from '@/utils';
@@ -50,7 +51,12 @@ export default function OutboundCardList({
}: OutboundCardListProps) {
const { t } = useTranslation();
if (rows.length === 0) {
return <div className="card-empty"></div>;
return (
<div className="card-empty">
<ExportOutlined style={{ fontSize: 32, marginBottom: 8 }} />
<div>{t('noData')}</div>
</div>
);
}
return (
<>
@@ -3,10 +3,17 @@
justify-content: flex-end;
}
/* Keep this in sync with the other pages' .card-empty (it's a global class):
the previous opacity:0.4 here leaked onto whichever page's empty state was
shown after the Outbounds CSS loaded, fading it. */
.card-empty {
text-align: center;
opacity: 0.4;
padding: 16px 0;
color: var(--ant-color-text-secondary);
padding: 24px 12px;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
}
.outbound-card {
@@ -33,6 +33,7 @@ import {
ArrowDownOutlined,
CheckCircleOutlined,
WarningOutlined,
ExportOutlined,
} from '@ant-design/icons';
import { HttpUtil } from '@/utils';
@@ -469,6 +470,14 @@ export default function OutboundsTab({
rowKey={(r) => r.key}
pagination={false}
size="small"
locale={{
emptyText: (
<div className="card-empty">
<ExportOutlined style={{ fontSize: 32, marginBottom: 8 }} />
<div>{t('noData')}</div>
</div>
),
}}
/>
)}
@@ -1,6 +1,7 @@
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, InputNumber, Select, Space, Switch, type FormInstance } from 'antd';
import { Form, Input, InputNumber, Select, Switch, type FormInstance } from 'antd';
import { CustomSockoptList } from '@/components/form';
import { DOMAIN_STRATEGY_OPTION, TCP_CONGESTION_OPTION } from '@/schemas/primitives';
import { HappyEyeballsSchema, SockoptStreamSettingsSchema } from '@/schemas/protocols/stream/sockopt';
import type { OutboundFormValues } from '@/schemas/forms/outbound-form';
@@ -136,54 +137,30 @@ export default function SockoptForm({
}))}
/>
</Form.Item>
<Form.Item
label={t('pages.xray.outboundForm.ipv6Only')}
name={['streamSettings', 'sockopt', 'V6Only']}
valuePropName="checked"
>
<Switch />
</Form.Item>
<Form.Item
label={t('pages.xray.outboundForm.acceptProxyProtocol')}
name={['streamSettings', 'sockopt', 'acceptProxyProtocol']}
valuePropName="checked"
>
<Switch />
</Form.Item>
<Form.Item
label={t('pages.xray.outboundForm.tcpUserTimeoutMs')}
name={['streamSettings', 'sockopt', 'tcpUserTimeout']}
>
<InputNumber min={0} style={{ width: '100%' }} />
<InputNumber min={0} />
</Form.Item>
<Form.Item
label={t('pages.xray.outboundForm.tcpKeepAliveIdleS')}
name={['streamSettings', 'sockopt', 'tcpKeepAliveIdle']}
>
<InputNumber min={0} style={{ width: '100%' }} />
<InputNumber min={0} />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.tcpMaxSeg')}
name={['streamSettings', 'sockopt', 'tcpMaxSeg']}
>
<InputNumber min={0} style={{ width: '100%' }} />
<InputNumber min={0} />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.tcpWindowClamp')}
name={['streamSettings', 'sockopt', 'tcpWindowClamp']}
tooltip={t('pages.inbounds.form.tcpWindowClampHint')}
>
<InputNumber min={0} style={{ width: '100%' }} />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.trustedXForwardedFor')}
name={['streamSettings', 'sockopt', 'trustedXForwardedFor']}
>
<Select
mode="tags"
tokenSeparators={[',', ' ']}
placeholder="trusted-proxy.example,10.0.0.0/8"
/>
<InputNumber min={0} />
</Form.Item>
<Form.Item shouldUpdate noStyle>
{() => {
@@ -210,7 +187,7 @@ export default function SockoptForm({
label={t('pages.inbounds.form.tryDelayMs')}
name={['streamSettings', 'sockopt', 'happyEyeballs', 'tryDelayMs']}
>
<InputNumber min={0} style={{ width: '100%' }} placeholder="0 (disabled) — 250 recommended" />
<InputNumber min={0} placeholder="0 (disabled) — 250 recommended" />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.prioritizeIPv6')}
@@ -223,13 +200,13 @@ export default function SockoptForm({
label={t('pages.inbounds.form.interleave')}
name={['streamSettings', 'sockopt', 'happyEyeballs', 'interleave']}
>
<InputNumber min={1} style={{ width: '100%' }} />
<InputNumber min={1} />
</Form.Item>
<Form.Item
label={t('pages.inbounds.form.maxConcurrentTry')}
name={['streamSettings', 'sockopt', 'happyEyeballs', 'maxConcurrentTry']}
>
<InputNumber min={0} style={{ width: '100%' }} />
<InputNumber min={0} />
</Form.Item>
</>
)}
@@ -237,56 +214,7 @@ export default function SockoptForm({
);
}}
</Form.Item>
<Form.List name={['streamSettings', 'sockopt', 'customSockopt']}>
{(fields, { add, remove }) => (
<>
<Form.Item label={t('pages.inbounds.form.customSockopt')}>
<Button
type="dashed"
size="small"
onClick={() => add({ type: 'int', level: '6', opt: '', value: '' })}
>
+ {t('pages.inbounds.form.addCustomOption')}
</Button>
</Form.Item>
{fields.map((field) => (
<Space.Compact key={field.key} style={{ display: 'flex', marginBottom: 8 }}>
<Form.Item name={[field.name, 'system']} noStyle>
<Select
placeholder="all"
allowClear
style={{ width: 100 }}
options={[
{ value: 'linux', label: 'linux' },
{ value: 'windows', label: 'windows' },
{ value: 'darwin', label: 'darwin' },
]}
/>
</Form.Item>
<Form.Item name={[field.name, 'type']} noStyle>
<Select
style={{ width: 80 }}
options={[
{ value: 'int', label: 'int' },
{ value: 'str', label: 'str' },
]}
/>
</Form.Item>
<Form.Item name={[field.name, 'level']} noStyle>
<Input placeholder="level (6=TCP)" style={{ width: 100 }} />
</Form.Item>
<Form.Item name={[field.name, 'opt']} noStyle>
<Input placeholder="opt (decimal)" style={{ width: 120 }} />
</Form.Item>
<Form.Item name={[field.name, 'value']} noStyle>
<Input placeholder="value" style={{ flex: 1 }} />
</Form.Item>
<Button danger onClick={() => remove(field.name)}></Button>
</Space.Compact>
))}
</>
)}
</Form.List>
<CustomSockoptList />
</>
)}
</>
+2
View File
@@ -8,6 +8,7 @@ const InboundsPage = lazy(() => import('@/pages/inbounds/InboundsPage'));
const ClientsPage = lazy(() => import('@/pages/clients/ClientsPage'));
const GroupsPage = lazy(() => import('@/pages/groups/GroupsPage'));
const NodesPage = lazy(() => import('@/pages/nodes/NodesPage'));
const HostsPage = lazy(() => import('@/pages/hosts/HostsPage'));
const SettingsPage = lazy(() => import('@/pages/settings/SettingsPage'));
const XrayPage = lazy(() => import('@/pages/xray/XrayPage'));
const ApiDocsPage = lazy(() => import('@/pages/api-docs/ApiDocsPage'));
@@ -26,6 +27,7 @@ const routes: RouteObject[] = [
{ path: 'clients', element: withSuspense(<ClientsPage />) },
{ path: 'groups', element: withSuspense(<GroupsPage />) },
{ path: 'nodes', element: withSuspense(<NodesPage />) },
{ path: 'hosts', element: withSuspense(<HostsPage />) },
{ path: 'settings', element: withSuspense(<SettingsPage />) },
{ path: 'xray', element: withSuspense(<XrayPage />) },
{ path: 'api-docs', element: withSuspense(<ApiDocsPage />) },
+116
View File
@@ -0,0 +1,116 @@
import { z } from 'zod';
import { AlpnSchema, UtlsFingerprintSchema } from '@/schemas/protocols/security/tls';
// A Host is a per-inbound override endpoint: at subscription time each enabled
// host renders one extra share link/proxy with its own address/port/TLS, etc.,
// superseding the legacy externalProxy array. The form schema mirrors the field
// logic of schemas/protocols/stream/external-proxy.ts and reuses the shared
// ALPN / uTLS primitives.
export const HostSecuritySchema = z.enum(['same', 'tls', 'none', 'reality']);
export type HostSecurity = z.infer<typeof HostSecuritySchema>;
export const MihomoIpVersionSchema = z.enum(['dual', 'ipv4', 'ipv6', 'ipv4-prefer', 'ipv6-prefer']);
export const SubTypeSchema = z.enum(['raw', 'json', 'clash']);
// Tags are short uppercase identifiers (≤10 tags, each ≤36 chars). Enforced on
// the frontend; the backend stores them verbatim.
const HostTagSchema = z.string().regex(/^[A-Z0-9_:]+$/, 'pages.hosts.toasts.badTag').max(36);
// HostFormValues is what the form edits and POSTs.
export const HostFormSchema = z.object({
id: z.number().optional(),
inboundId: z.number().int().positive(),
sortOrder: z.number().int().default(0),
// Remark may contain {{VAR}} template tokens expanded per client at
// subscription time, so the stored template gets a generous cap.
remark: z.string().trim().min(1).max(256),
serverDescription: z.string().max(64).default(''),
isDisabled: z.boolean().default(false),
isHidden: z.boolean().default(false),
tags: z.array(HostTagSchema).max(10).default([]),
address: z.string().default(''),
port: z.number().int().min(0).max(65535).default(0),
security: HostSecuritySchema.default('same'),
sni: z.string().default(''),
hostHeader: z.string().default(''),
path: z.string().default(''),
alpn: z.array(AlpnSchema).default([]),
fingerprint: z.preprocess(
(val) => (val === '' ? undefined : val),
UtlsFingerprintSchema.optional(),
),
overrideSniFromAddress: z.boolean().default(false),
keepSniBlank: z.boolean().default(false),
pinnedPeerCertSha256: z.array(z.string()).default([]),
verifyPeerCertByName: z.boolean().default(false),
allowInsecure: z.boolean().default(false),
echConfigList: z.string().default(''),
muxParams: z.string().default(''),
sockoptParams: z.string().default(''),
finalMask: z.string().default(''),
// A comma-separated list of ports/ranges (e.g. "53,443,1000-2000"). Empty = none.
vlessRoute: z
.string()
.trim()
.regex(/^(\d{1,5}(-\d{1,5})?)(\s*,\s*\d{1,5}(-\d{1,5})?)*$/, 'pages.hosts.toasts.badVlessRoute')
.or(z.literal(''))
.default(''),
excludeFromSubTypes: z.array(SubTypeSchema).default([]),
// Visual-only assignment of nodes that resolve from this host (stored, not yet
// wired into routing).
nodeGuids: z.array(z.string()).default([]),
mihomoIpVersion: z.preprocess(
(val) => (val === '' ? undefined : val),
MihomoIpVersionSchema.optional(),
),
mihomoX25519: z.boolean().default(false),
shuffleHost: z.boolean().default(false),
});
export type HostFormValues = z.infer<typeof HostFormSchema>;
// HostRecord is the loose list/read projection from /panel/api/hosts. Slice and
// free-JSON fields tolerate the backend serializing nil as null.
export const HostRecordSchema = z.object({
id: z.number(),
inboundId: z.number(),
sortOrder: z.number().optional(),
remark: z.string().optional(),
serverDescription: z.string().optional(),
isDisabled: z.boolean().optional(),
isHidden: z.boolean().optional(),
tags: z.array(z.string()).nullish(),
address: z.string().optional(),
port: z.number().optional(),
security: z.string().optional(),
sni: z.string().optional(),
hostHeader: z.string().optional(),
path: z.string().optional(),
alpn: z.array(z.string()).nullish(),
fingerprint: z.string().optional(),
overrideSniFromAddress: z.boolean().optional(),
keepSniBlank: z.boolean().optional(),
pinnedPeerCertSha256: z.array(z.string()).nullish(),
verifyPeerCertByName: z.boolean().optional(),
allowInsecure: z.boolean().optional(),
echConfigList: z.string().optional(),
muxParams: z.unknown().optional(),
sockoptParams: z.unknown().optional(),
finalMask: z.string().optional(),
vlessRoute: z.string().optional(),
excludeFromSubTypes: z.array(z.string()).nullish(),
nodeGuids: z.array(z.string()).nullish(),
mihomoIpVersion: z.string().optional(),
mihomoX25519: z.boolean().optional(),
shuffleHost: z.boolean().optional(),
}).loose();
export type HostRecord = z.infer<typeof HostRecordSchema>;
export const HostListSchema = z.array(HostRecordSchema);
-1
View File
@@ -12,7 +12,6 @@ export const DefaultsPayloadSchema = z.object({
subClashURI: z.string().optional(),
subClashEnable: z.boolean().optional(),
pageSize: z.number().optional(),
remarkModel: z.string().optional(),
datepicker: z.enum(['gregorian', 'jalalian']).optional(),
ipLimitEnable: z.boolean().optional(),
accessLogEnable: z.boolean().optional(),
+1 -3
View File
@@ -17,7 +17,7 @@ export const AllSettingSchema = z.object({
pageSize: z.number().int().min(0).max(1000).optional(),
expireDiff: nonNegativeInt.optional(),
trafficDiff: nonNegativeInt.max(100).optional(),
remarkModel: z.string().optional(),
remarkTemplate: z.string().optional(),
datepicker: z.enum(['gregorian', 'jalalian']).optional(),
tgBotEnable: z.boolean().optional(),
tgBotToken: z.string().optional(),
@@ -53,8 +53,6 @@ export const AllSettingSchema = z.object({
subKeyFile: z.string().optional(),
subUpdates: z.number().int().min(1).max(168).optional(),
subEncrypt: z.boolean().optional(),
subShowInfo: z.boolean().optional(),
subEmailInRemark: z.boolean().optional(),
subURI: z.string().optional(),
subJsonURI: z.string().optional(),
subClashURI: z.string().optional(),
+41
View File
@@ -85,3 +85,44 @@
.api-docs-page .ant-card .ant-card-actions {
background: transparent;
}
/* Hosts page shares the same card styling + hover shadows (without the default
antd hoverable pointer/blur), matching Clients/Inbounds/etc. */
.hosts-page .ant-card {
border-radius: 12px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
transition: transform 0.2s ease, box-shadow 0.25s ease, border-color 0.2s ease;
}
.hosts-page.is-dark .ant-card {
box-shadow:
0 1px 2px rgba(0, 0, 0, 0.4),
inset 0 1px 0 rgba(255, 255, 255, 0.03);
}
.hosts-page.is-dark.is-ultra .ant-card {
box-shadow:
0 1px 2px rgba(0, 0, 0, 0.6),
inset 0 1px 0 rgba(255, 255, 255, 0.025);
}
.hosts-page .ant-card.ant-card-hoverable:hover {
cursor: default;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
}
.hosts-page.is-dark .ant-card.ant-card-hoverable:hover {
box-shadow:
0 8px 24px rgba(0, 0, 0, 0.5),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
}
.hosts-page.is-dark.is-ultra .ant-card.ant-card-hoverable:hover {
box-shadow:
0 8px 24px rgba(0, 0, 0, 0.75),
inset 0 1px 0 rgba(255, 255, 255, 0.03);
}
.hosts-page .ant-card .ant-card-actions {
background: transparent;
}
+40
View File
@@ -176,3 +176,43 @@ body.dark .ant-dropdown-menu-item-divider {
padding: 8px;
}
}
/* Hosts page shares the standard panel page shell (background, transparent
layout, content padding, summary-card padding). */
.hosts-page {
--bg-page: #e6e8ec;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.hosts-page.is-dark {
--bg-page: #1a1b1f;
--bg-card: #23252b;
}
.hosts-page.is-dark.is-ultra {
--bg-page: #000;
--bg-card: #101013;
}
.hosts-page .ant-layout,
.hosts-page .ant-layout-content,
.hosts-page .content-shell {
background: transparent;
}
.hosts-page .content-area {
padding: 24px;
}
.hosts-page .summary-card {
padding: 16px;
}
@media (max-width: 768px) {
.hosts-page .content-area,
.hosts-page .summary-card {
padding: 8px;
}
}
@@ -36,12 +36,6 @@ exports[`inbound security forms > TlsForm field structure is stable 1`] = `
]
`;
exports[`inbound transport forms > ExternalProxyForm field structure is stable (one TLS entry) 1`] = `
[
"External Proxy",
]
`;
exports[`inbound transport forms > GrpcForm field structure is stable 1`] = `
[
"Service Name",
@@ -77,7 +71,7 @@ exports[`inbound transport forms > RawForm field structure is stable 1`] = `
]
`;
exports[`inbound transport forms > SockoptForm field structure is stable (enabled + happy eyeballs) 1`] = `
exports[`inbound transport forms > SockoptForm field structure is stable (server-side fields only) 1`] = `
[
"Sockopt",
"Real client IP",
@@ -89,21 +83,11 @@ exports[`inbound transport forms > SockoptForm field structure is stable (enable
"TCP Window Clamp",
"Proxy Protocol",
"TCP Fast Open",
"Multipath TCP",
"Penetrate",
"V6 Only",
"Domain Strategy",
"TCP Congestion",
"TProxy",
"Dialer Proxy",
"Interface name",
"Trusted X-Forwarded-For",
"Address+port strategy",
"Happy Eyeballs",
"Try delay (ms)",
"Prioritize IPv6",
"Interleave",
"Max concurrent try",
"Custom sockopt",
]
`;
+54
View File
@@ -0,0 +1,54 @@
/// <reference types="vite/client" />
import { describe, expect, it } from 'vitest';
import { hostToExternalProxyEntry } from '@/lib/hosts/host-link';
describe('hostToExternalProxyEntry', () => {
const base = {
security: 'tls' as const,
address: 'cdn.example.com',
port: 8443,
remark: 'R',
sni: 'sni.example.com',
alpn: ['h2'] as ('h2' | 'h3' | 'http/1.1')[],
fingerprint: 'chrome' as const,
pinnedPeerCertSha256: ['AAAA'],
echConfigList: 'ECH',
overrideSniFromAddress: false,
keepSniBlank: false,
};
it('maps the overlapping fields onto an external-proxy entry', () => {
const ep = hostToExternalProxyEntry(base);
expect(ep.forceTls).toBe('tls');
expect(ep.dest).toBe('cdn.example.com');
expect(ep.port).toBe(8443);
expect(ep.remark).toBe('R');
expect(ep.sni).toBe('sni.example.com');
expect(ep.alpn).toEqual(['h2']);
expect(ep.fingerprint).toBe('chrome');
expect(ep.pinnedPeerCertSha256).toEqual(['AAAA']);
expect(ep.echConfigList).toBe('ECH');
});
it('maps reality/same security to forceTls "same"', () => {
expect(hostToExternalProxyEntry({ ...base, security: 'reality' }).forceTls).toBe('same');
expect(hostToExternalProxyEntry({ ...base, security: 'same' }).forceTls).toBe('same');
expect(hostToExternalProxyEntry({ ...base, security: 'none' }).forceTls).toBe('none');
});
it('uses the address as sni when overrideSniFromAddress is set', () => {
const ep = hostToExternalProxyEntry({ ...base, overrideSniFromAddress: true });
expect(ep.sni).toBe('cdn.example.com');
});
it('omits sni when keepSniBlank is set', () => {
const ep = hostToExternalProxyEntry({ ...base, keepSniBlank: true });
expect(ep.sni).toBeUndefined();
});
it('falls back to port 443 when the host port is 0 (inherit)', () => {
const ep = hostToExternalProxyEntry({ ...base, port: 0 });
expect(ep.port).toBe(443);
});
});
+67
View File
@@ -0,0 +1,67 @@
/// <reference types="vite/client" />
import { describe, expect, it } from 'vitest';
import { HostFormSchema } from '@/schemas/api/host';
describe('HostFormSchema', () => {
const valid = {
inboundId: 1,
remark: 'cdn-front',
address: 'cdn.example.com',
port: 8443,
security: 'tls',
tags: ['CDN', 'EU'],
mihomoIpVersion: 'dual',
excludeFromSubTypes: ['clash'],
};
it('parses a valid host', () => {
const parsed = HostFormSchema.parse(valid);
expect(parsed.remark).toBe('cdn-front');
expect(parsed.security).toBe('tls');
expect(parsed.tags).toEqual(['CDN', 'EU']);
expect(parsed.excludeFromSubTypes).toEqual(['clash']);
});
it('rejects an empty remark', () => {
expect(() => HostFormSchema.parse({ ...valid, remark: '' })).toThrow();
});
it('accepts a templated remark up to 256 chars and rejects beyond', () => {
expect(() => HostFormSchema.parse({ ...valid, remark: 'x'.repeat(256) })).not.toThrow();
expect(() => HostFormSchema.parse({ ...valid, remark: 'x'.repeat(257) })).toThrow();
});
it('rejects an out-of-range port', () => {
expect(() => HostFormSchema.parse({ ...valid, port: 70000 })).toThrow();
});
it('rejects a bad security enum', () => {
expect(() => HostFormSchema.parse({ ...valid, security: 'bogus' })).toThrow();
});
it('rejects a tag with invalid characters', () => {
expect(() => HostFormSchema.parse({ ...valid, tags: ['lower-case'] })).toThrow();
});
it('rejects more than 10 tags', () => {
expect(() =>
HostFormSchema.parse({ ...valid, tags: Array.from({ length: 11 }, (_, i) => `T${i}`) }),
).toThrow();
});
it('rejects a bad mihomoIpVersion enum', () => {
expect(() => HostFormSchema.parse({ ...valid, mihomoIpVersion: 'nope' })).toThrow();
});
it('rejects a bad excludeFromSubTypes value', () => {
expect(() => HostFormSchema.parse({ ...valid, excludeFromSubTypes: ['xml'] })).toThrow();
});
it('defaults security to "same" and port to 0', () => {
const parsed = HostFormSchema.parse({ inboundId: 1, remark: 'r' });
expect(parsed.security).toBe('same');
expect(parsed.port).toBe(0);
expect(parsed.tags).toEqual([]);
});
});
+5 -23
View File
@@ -3,7 +3,6 @@ import { Form, type FormInstance } from 'antd';
import type { ReactNode } from 'react';
import {
ExternalProxyForm,
GrpcForm,
HttpUpgradeForm,
KcpForm,
@@ -67,30 +66,13 @@ describe('inbound transport forms', () => {
expect(fieldLabels()).toMatchSnapshot();
});
it('ExternalProxyForm field structure is stable (one TLS entry)', () => {
renderInForm(
() => <ExternalProxyForm toggleExternalProxy={noop} />,
{
streamSettings: {
externalProxy: [{
forceTls: 'tls',
dest: '',
port: 443,
remark: '',
sni: '',
fingerprint: '',
alpn: [],
}],
},
},
);
expect(fieldLabels()).toMatchSnapshot();
});
it('SockoptForm field structure is stable (enabled + happy eyeballs)', () => {
it('SockoptForm field structure is stable (server-side fields only)', () => {
// The inbound sockopt form shows only server/listening-side fields;
// outbound-only fields (dialerProxy, domainStrategy, interface,
// addressPortStrategy, happyEyeballs, tcpMptcp) live in the outbound form.
renderInForm(
() => <SockoptForm toggleSockopt={noop} network="tcp" />,
{ streamSettings: { sockopt: { happyEyeballs: {} } } },
{ streamSettings: { sockopt: { mark: 0 } } },
);
expect(fieldLabels()).toMatchSnapshot();
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest';
import { parseLinkParts, linkMetaText } from '@/lib/xray/link-label';
// The panel shows the subscription's remark verbatim. Per-client traffic/expiry
// info is rendered only into the body a client app imports (backend, first link
// only), so the panel's display links are already clean — nothing is stripped.
describe('link-label parseLinkParts', () => {
const linkWith = (remark: string) =>
`vless://uid@host.example.com:443?type=tcp&security=tls#${encodeURIComponent(remark)}`;
it('parses protocol / network / security and keeps the remark verbatim', () => {
const parts = parseLinkParts(linkWith('Germany-john@example.com'));
expect(parts?.protocol).toBe('Vless');
expect(parts?.network).toBe('TCP');
expect(parts?.security).toBe('TLS');
expect(parts?.remark).toBe('Germany-john@example.com');
expect(parts?.port).toBe('443');
});
it('linkMetaText joins the remark with the port', () => {
const parts = parseLinkParts(linkWith('Germany-john@example.com'));
expect(parts && linkMetaText(parts)).toBe('Germany-john@example.com:443');
});
it('returns null for an unparseable scheme', () => {
expect(parseLinkParts('not-a-link')).toBeNull();
});
});
@@ -0,0 +1,26 @@
import { describe, it, expect, vi } from 'vitest';
import { fireEvent, render, screen } from '@testing-library/react';
import RemarkTemplateField from '@/components/form/RemarkTemplateField';
describe('RemarkTemplateField', () => {
it('inserts a {{TOKEN}} when a variable chip is clicked', async () => {
const onChange = vi.fn();
render(<RemarkTemplateField value="DE " onChange={onChange} maxLength={256} />);
// Open the variable picker (the only button is the addon trigger).
fireEvent.click(screen.getByRole('button'));
fireEvent.click(await screen.findByText('{{EMAIL}}'));
expect(onChange).toHaveBeenCalledTimes(1);
const inserted = onChange.mock.calls[0][0] as string;
expect(inserted).toContain('{{EMAIL}}');
expect(inserted).toContain('DE');
});
it('renders a live preview of the expanded remark', () => {
render(<RemarkTemplateField value="{{EMAIL}}" onChange={() => {}} />);
// Sample expansion of {{EMAIL}} is "john".
expect(screen.getByText('john')).toBeTruthy();
});
});
@@ -0,0 +1,30 @@
import { describe, it, expect } from 'vitest';
import {
REMARK_VARIABLES,
hasRemarkTokens,
previewRemark,
wrapToken,
} from '@/lib/remark/remarkVariables';
describe('remark variables', () => {
it('wrapToken / hasRemarkTokens', () => {
expect(wrapToken('EMAIL')).toBe('{{EMAIL}}');
expect(hasRemarkTokens('hi {{EMAIL}}')).toBe(true);
expect(hasRemarkTokens('plain')).toBe(false);
});
it('previewRemark substitutes known tokens and drops unknown', () => {
expect(previewRemark('plain text')).toBe('plain text');
expect(previewRemark('{{EMAIL}}')).toBe('john');
expect(previewRemark('{{EMAIL}} · {{TRAFFIC_LEFT}} · {{DAYS_LEFT}}d')).toBe('john · 41.60GB · 12d');
expect(previewRemark('{{NOT_A_TOKEN}}')).toBe('');
});
it('every catalog token previews to its own sample', () => {
for (const v of REMARK_VARIABLES) {
expect(v.sample.length).toBeGreaterThan(0);
expect(previewRemark(wrapToken(v.token))).toBe(v.sample);
}
});
});