Compare commits

...

104 Commits

Author SHA1 Message Date
MHSanaei 6efc4b0665 Revert "perf(frontend): code-split heavy components to improve LCP"
This reverts commit 444b05cac9.
2026-05-10 17:45:05 +02:00
MHSanaei 94a7dbfe3c fix(docker): pin frontend stage to BUILDPLATFORM and drop removed buildx input
node:22-alpine has no manifest for linux/arm/v6, breaking multi-arch
builds. Frontend output is static JS/CSS that doesn't need to be
built per target arch — pin the stage to $BUILDPLATFORM so Vite
always runs on the host. Also drop `install: true` from
setup-buildx-action@v4 (input was removed).
2026-05-10 17:22:15 +02:00
qwardo e2649f98df fix(arch): correct x-ui service path (#4213) 2026-05-10 17:17:33 +02:00
MHSanaei 3d839e0ee1 v3.0.0 2026-05-10 17:15:48 +02:00
MHSanaei a96612f595 feat(xray/dns): align DNS settings with Xray docs + UI polish
- DNS server modal: rename expectIPs -> expectedIPs (per docs); add
  per-server tag, clientIP, serveStale, serveExpiredTTL, timeoutMs;
  flip skipFallback default to false; hydration still accepts legacy
  expectIPs for back-compat.
- DNS tab: add hosts editor (domain -> IP/array), serveStale +
  serveExpiredTTL controls, "Use Preset" button bringing back the
  legacy preset gallery (Google / Cloudflare / AdGuard + Family
  variants — fixed AdGuard Family IPs that were wrong in legacy),
  and a "Delete All" button to wipe the server list at once.
- i18n: add 15 new dns.* keys across all 13 locales.
- Frontend-wide formatter pass on Vue components (whitespace and
  attribute layout only, no behavior changes).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 17:03:11 +02:00
MHSanaei 8e7d215b4a feat(nodes): traffic-writer queue, full-mirror sync, WS event fixes
- Traffic-writer single-consumer queue (web/service/traffic_writer.go)
  serialises every DB write that touches up/down/all_time/last_online
  (AddTraffic, SetRemoteTraffic, Reset*, UpdateClientTrafficByEmail) so
  overlapping goroutines can no longer clobber each other's column-scoped
  Updates with a stale tx.Save.

- DB pool: WAL + busy_timeout=10s + synchronous=NORMAL + _txlock=
  immediate, MaxOpenConns=8 / MaxIdleConns=4. The immediate-tx PRAGMA
  fixes residual "database is locked [0ms]" cases where deferred-tx
  writer-upgrade conflicts bypass busy_timeout.

- SetRemoteTraffic full-mirrors node-authoritative state into central:
  settings JSON, remark, listen, port, total, expiry, all_time, enable,
  plus per-client total/expiry/reset/all_time. Inbounds and
  client_traffics rows present on node but missing from central are
  created; rows missing from snap are deleted (with cascading
  client_traffics removal).

- NodeTrafficSyncJob detects structural changes from the mirror and
  broadcasts invalidate(inbounds) so open central UIs re-fetch via REST
  on node-side add/del/edit without manual refresh.

- XrayTrafficJob broadcasts invalidate(inbounds) when auto-disable flips
  client_traffics.enable so the per-client toggle reflects depletion
  without manual refresh.

- Frontend: inbounds page now subscribes to the BroadcastInbounds 'inbounds'
  WS event (full-list pushes from add/del/update controllers were silently
  dropped). Fixes invalidate payload field (dataType -> type). Restart-
  panel modal switched from Promise-wrap to onOk-only so Cancel actually
  cancels.

- Node files trimmed of stale prose-comments; cron cadence dropped
  10s -> 5s to match the inbounds page UX.

- README badges and Go module path bumped v2 -> v3 to match module rename.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 16:25:23 +02:00
Qiaochu Hu 24cd271486 Fix overly permissive file permissions (os.ModePerm) (#4207)
Several file operations used os.ModePerm (0777) which makes files
world-writable and world-readable, violating the principle of least
privilege:

- database/db.go: InitDB directory creation → 0755
- xray/process.go: Xray config write → 0644
- xray/process.go: Crash report write → 0644
- web/service/server.go: Binary extraction → 0755

Also removes unused "io/fs" imports from the affected files.
2026-05-10 14:47:28 +02:00
Qiaochu Hu dee2525d5f Fix silently ignored errors in password migration seeder (#4206)
The runSeeders function in database/db.go had three database operations
whose errors were silently ignored:

1. Pluck("seeder_name", &seedersHistory) - if this fails, the seeder
   might re-run and double-hash already bcrypt'd passwords, corrupting
   them
2. Find(&users) - if this fails, no users get migrated but the seeder
   still marks itself as complete
3. Update("password", hashedPassword) - if this fails for a user, their
   password silently remains in the old format

All three now properly check and return errors with descriptive messages.
2026-05-10 14:46:42 +02:00
Qiaochu Hu 81b4ae5661 Fix silently ignored error when saving outbound test URL setting (#4209)
In the Xray settings update handler, the error from
SetXrayOutboundTestUrl was silently discarded. If the database write
failed, the user received a success toast ("Settings updated
successfully") but the outbound test URL was not actually saved.

Now properly checks the error and returns a failure response to the
user, consistent with how the preceding SaveXraySetting call is
handled.
2026-05-10 14:45:53 +02:00
Ali Fotouhi 9cbba130ab fix(xray): clear outbound test state on delete to prevent result bleed (#4205) 2026-05-10 12:03:00 +02:00
MHSanaei cf5767acd1 i18n: localize sidebar theme toggle, xray-status badge, and nodes menu
The sidebar theme submenu (Theme / Dark / Ultra dark) and the dashboard's
Xray status badge ("Xray is running" etc.) were hardcoded English strings.
Wire them through vue-i18n: ThemeSwitch.vue uses menu.theme/dark/ultraDark,
and XrayStatusCard.vue derives the badge text from the existing
pages.index.xrayStatus{Running,Stop,Error,Unknown} keys (status.js no
longer carries an English stateMsg field).

The "Nodes" menu item was already keyed as menu.nodes but only en-US and
fa-IR had a translation; add it to the other 11 languages, matching the
wording each file already uses for pages.nodes.title.
#4201
2026-05-10 11:56:30 +02:00
MHSanaei 444b05cac9 perf(frontend): code-split heavy components to improve LCP
Switch the inbounds-page modals, login page's theme switch, and the
Persian date picker to defineAsyncComponent. They're not needed on
first paint, so deferring them shrinks the initial bundle and lets
the LCP element render sooner.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 11:33:46 +02:00
MHSanaei f70e131dfe fix(nodes): bind form-encoded posts and skip node inbounds in central xray
The Node model only carried `json:` tags, so when the panel's axios
posted form-encoded bodies to /panel/api/nodes/add and /test, Gin's
form binder produced a zero-valued Node — empty Name, empty Address,
Port=0 — surfacing as "node name is required" and a probe URL of
"https://:0/...". Add `form:` tags so add/test bind correctly.

Also skip inbounds with NodeID set when building the central xray
config; otherwise the central panel tried to listen on ports owned by
node-managed inbounds and xray-core failed to start with a bind
collision.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-10 11:32:06 +02:00
Amirmohammad Sadat Shokouhi 14165fc54d avoid reset in QueryStatsRequest (#4202) 2026-05-10 10:59:42 +02:00
MHSanaei 7cd26a0583 v3 2026-05-10 02:13:42 +02:00
MHSanaei 267fb1c866 refactor(inbounds): reorder Inbound's Data tabs (client first, sub inline)
Show the per-client pane as the default tab and fold the subscription
URLs into its bottom (under a divider) so the modal has two tabs
instead of three. Inbound details move to the second tab and remain
the default fallback for protocol-only entries (HTTP/Mixed/Tunnel/
WireGuard) that have no per-client view.
2026-05-10 01:59:02 +02:00
MHSanaei 5ac88271af feat(inbounds): mobile card layout for inbounds and clients
Replace the cramped <a-table> on <768px with a stacked card list for
both inbounds and the per-client expanded rows. Each card surfaces
protocol, port, node, traffic, all-time traffic, client count and
expiry inline as labeled rows instead of hiding them behind popovers,
fixes the 0px gutter that made cards visually merge, and softens the
in-quota green from #52c41a to #389e0a (Ant green-7) so traffic tags
are no longer blinding on dark themes.
2026-05-10 01:46:48 +02:00
MHSanaei b776b33497 fix(ui): correct responsive breakpoints for add client form and bulk 2026-05-10 00:52:22 +02:00
MHSanaei 1478124712 fix(ui): correct responsive breakpoints for inbound form and settings
InboundFormModal forms specified label/wrapper cols only at md
(>=768), leaving 576-767 unset and breaking the grid in that range.
Move the breakpoint down to sm so the desktop 8/14 split applies
from 576 upward.

SettingListItem had its breakpoints inverted: at <992 no span was
set so the meta and control cols squeezed side-by-side, and at lg
(992-1199) they stacked. Switch to xs/lg so input stacks below the
text under 992 and sits beside it from 992 upward.
2026-05-10 00:43:25 +02:00
MHSanaei 9735d26b3d perf(xray): bound Xray-version request and extend cache
Replace the unbounded http.Get used by GetXrayVersions with a 10s-
timeout client so a slow or unreachable GitHub can't hang the Xray
Updates modal. Bump the controller cache from 60s to 15 minutes,
and on a request error fall back to the last successful list when
one is available.
2026-05-10 00:24:25 +02:00
MHSanaei 113a29733e feat(logs): mobile-friendly log modals with theme-aware colors
Both index-page log modals (panel logs and xray access logs) now
adapt to narrow viewports and dark / ultra-dark themes:

- Render through Vue templates instead of v-html — drops the manual
  escapeHtml helper and the regex-based string formatting; each line
  is parsed once into structured fields (date, time, level, body for
  panel logs; from / to / inbound / outbound / email for xray logs).
- Mobile: stacked cards per entry. Panel-log cards show time + a
  level badge above the wrapped message; xray-log cards show time
  and event tag above the From → To pair, with inbound / outbound /
  email as small meta pairs below. Long IPv6 / hostnames wrap
  instead of overflowing.
- Modal goes full-bleed on mobile (100vw, no rounded corners,
  pinned to viewport height) so cards get full width.
- Toolbar wraps cleanly when the row-count, level, syslog checkbox,
  and download button can't fit on one line.
- Theme-aware colour palette via CSS variables on .log-container —
  brighter shades on body.dark and [data-theme="ultra-dark"] so
  level text and blocked / proxy rows keep AA contrast against the
  navy and near-black surfaces.
- Cards render flush on the container surface (no separate card bg)
  so the colour story is identical to the desktop view.
2026-05-10 00:13:20 +02:00
MHSanaei 3505430e57 fix(docker): include web/translation in frontend and final stages
The Vite SPA reads locale JSON via a glob that resolves to
<repo>/web/translation/*.json, but the frontend build stage only
copied frontend/, so the production bundle shipped with no messages
and the Docker panel rendered untranslated keys. Copy the directory
into the frontend stage at the path the glob expects, and into the
final image so the Go disk fallback in locale.loadTranslationsFromDisk
also has somewhere to read from.
2026-05-09 23:30:54 +02:00
MHSanaei f68a14a3ca fix(xray): align DNS outbound to spec and repair item-list rules UI
DNS outbound now mirrors xray-core's documented shape: rewriteNetwork
/ rewriteAddress / rewritePort / userLevel replace the legacy network
/ address / port keys, and unset values are dropped on the wire. Old
configs are still accepted on read so saved configs migrate cleanly.

While there, fix two latent bugs in repeat-item editors (DNS rules,
Freedom noise, WireGuard peers):
- The "+" buttons pushed plain objects into arrays of class instances,
  so toJson() crashed on the next read and the JSON tab silently went
  blank. Push proper class instances instead.
- Each item heading lived outside any a-form-item, so the delete icon
  ignored the form's column grid and slumped left. Wrap the heading
  in a form-item with the standard offset wrapper-col and switch the
  flex to space-between so the icon sits at the right of the input
  column, in line with the fields below it.
2026-05-09 23:17:31 +02:00
MHSanaei 60e2af088d feat(xray): add loopback outbound protocol
#4185
Surface xray-core's loopback outbound in the Outbounds form so users
can re-route already-processed traffic back into a named inbound for
secondary routing (e.g. splitting TCP/UDP from one ingress). The
inboundTag field is an autocomplete over existing inbound tags, with
free-text fallback for inbounds defined outside the panel. Loopback
outbounds are excluded from the connectivity test since they have no
network endpoint.
2026-05-09 22:49:49 +02:00
MHSanaei 917f9b307e fix(xray): surface reverse tags in routing and balancer dropdowns
Outbound reverse tags now appear as inbound options in routing rules
(#4199), and inbound-client reverse tags appear as outbounds in the
balancer selector (#4187). Both represent virtual endpoints created by
xray-core that the dropdowns previously missed.
2026-05-09 22:03:01 +02:00
MHSanaei 61c84e8223 fix(panel): make webBasePath work end-to-end in dev and prod
- Vite dev server reads webBasePath from x-ui.db via node:sqlite and
  injects __X_UI_BASE_PATH__ on every HTML serve, mirroring dist.go.
  Single broad proxy regex catches backend routes whether the URL is
  prefixed or not, and the bypass serves login.html for the bare
  basePath URL so post-logout navigation lands on Vite's own page
  instead of the production dist HTML's hashed asset URLs.
- axios.defaults.baseURL is set from __X_UI_BASE_PATH__ at startup so
  HttpUtil calls reach the backend's basePath group instead of 404ing
  on every prefixed install. fetch() for the public CSRF endpoint
  prepends the prefix manually since it doesn't honor axios defaults.
- Logout/redirect responses set Cache-Control: no-store and the index
  handler's logged-in redirect uses an absolute base_path+panel/ URL,
  preventing browsers from replaying a stale cached 307 that bounced
  the user back to /panel/ after logout.
- ClearSession also issues a Path=/ deletion cookie when basePath is
  not "/", so a legacy cookie from an earlier basePath setting can't
  keep IsLogin returning true after logout.
- getPanelUpdateInfo no longer returns a translated error message on
  GitHub fetch failures, so HttpUtil's auto-popup stays quiet on
  offline / blocked environments.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 21:47:37 +02:00
MHSanaei 72d8ebd269 fix(x-ui.sh): pass silent flag to stop/start during IP SSL setup 2026-05-09 19:59:01 +02:00
MHSanaei b885a1f8a6 fix(index): improve mobile dashboard layout
- Move System History action from the 3X-UI card into the System Load
  card's #extra slot so the chart opener sits next to live load values.
- Fix card widths on mobile by switching :sm="24" to :xs="24"; the sm
  breakpoint only kicks in at >=576px, so phones in portrait had no
  span set and cards shrank to content width.
- Restore vertical spacing between cards (vertical gutter was 0 on
  mobile) and reduce content padding on small screens, reserving 64px
  top so the sidebar drawer handle no longer overlaps the StatusCard.
- Wrap the 3X-UI link tags in a flex container so version/Telegram/docs
  chips wrap with consistent spacing on narrow widths.
- Make Sparkline's viewBox track its actual rendered pixel width via
  ResizeObserver so X-axis time labels stop being squashed horizontally
  by preserveAspectRatio="none" on narrow containers.
- Make the SystemHistory modal width responsive (95vw on mobile, was a
  fixed 900px that overflowed phone viewports).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 19:03:09 +02:00
MHSanaei 439f4cf1e8 Build frontend for CodeQL; remove release analyze job
In the CodeQL workflow, add Node.js setup and a frontend build step for the Go matrix so vite emits web/dist before CodeQL's Go autobuild (the Go binary uses //go:embed all:dist and web/dist is .gitignored). In the release workflow, remove the separate Go analyze job (gofmt, go vet, staticcheck, tests) and drop its dependency from build jobs to simplify the release pipeline.
2026-05-09 18:01:41 +02:00
Sanaei bc00d37ad8 Vue3 migration (#4198)
* docs(migration): Phase 1 inventory — Vue 2 / AD-Vue 1 surface area

Captures the breakage surface for the Vue 3 + Ant Design Vue 4 + Vite
migration: 17,650 lines across 69 templates, 3,145 a-* component
instances across 63 files, with per-pattern counts and file lists.

Key findings:
- No Vue filters anywhere — dodges a major Vue 3 breaking change
- 358 v-model uses; AD-Vue 4 absorbs most, custom components don't
- 233 <template slot="X"> usages must become <template #X>
- 49 scopedSlots: { ... } column defs need new slots: { ... } shape
- a-icon is removed in AD-Vue 4 — every icon must be imported

Establishes the 8-phase order; Phase 2 (Vite toolchain) is next.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* build(frontend): Phase 2 — scaffold Vite + Vue 3 + AD-Vue 4

Adds a frontend/ directory that lives alongside the legacy web/html/
Vue 2 templates during the migration. Vite builds into ../web/dist/
so the Go binary will be able to embed the result via embed.FS once
Phase 4 starts moving real pages over.

- package.json pins Vue 3.5, Ant Design Vue 4.2, Vite 6, vue-i18n 10
- vite.config.js: dev server on :5173 with API proxy to the Go panel
  on :2053; build output to ../web/dist/
- src/App.vue is currently a smoke-test placeholder — delete once the
  first real page (login) lands in Phase 4
- node_modules and dist are already ignored at repo root

To verify locally:
  cd frontend && npm install && npm run dev

Pages will be migrated one at a time on the vue3-migration branch.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(frontend): Phase 3 — port utils, models, axios, websocket as ES modules

Ports the framework-agnostic JS from web/assets/js/ into frontend/src/
so Vue 3 pages can import what they need without relying on script-tag
globals.

- web/assets/js/util/index.js (927 lines, 21 classes) →
  frontend/src/utils/legacy.js + a barrel at utils/index.js. All
  classes are now named exports.
- Vue.prototype.$message in HttpUtil → direct import of `message`
  from ant-design-vue (Vue 3 has no Vue.prototype).
- RandomUtil.randomShadowsocksPassword previously defaulted to
  SSMethods.BLAKE3_AES_256_GCM from inbound.js, creating a circular
  import. Replaced with the literal string default.
- MediaQueryMixin (Vue 2 mixin) removed. Replaced by
  composables/useMediaQuery.js — Vue 3 composable returning reactive
  `isMobile`.
- axios-init.js wrapped as setupAxios(); Qs global → npm `qs`.
- websocket.js exported as WebSocketClient class; the implicit
  window.wsClient global is gone — pages instantiate it themselves.
- model/{inbound,outbound,dbinbound,setting,reality_targets}.js
  copied with `export` added on every top-level declaration. Imports
  between models and utils are wired up explicitly.
- subscription.js deferred to Phase 5 (it's a Vue 2 mount, not a util).
- App.vue smoke test exercises SizeFormatter / RandomUtil / Wireguard /
  useMediaQuery so the user can verify Phase 3 with `npm run dev`.

Run `cd frontend && npm install && npm run dev` — qs was added so a
fresh install is required.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 4 — port login.html to Vue 3 + AD-Vue 4 + Vite 8

First real page in the new toolchain. Multi-page Vite: each migrated
page is its own entry. login.html now lives at frontend/login.html with
a thin entrypoint at frontend/src/login.js mounting LoginPage.vue.

Vite 6 → Vite 8.0.11 (per user request). Requires Node 20.19+ or 22.12+.
@vitejs/plugin-vue bumped to ^6.0.6 (peers vite ^8). Ant Design Vue
stays on 4.2.6 — there is no AD-Vue 6.

Vue 2 → Vue 3 / AD-Vue 1 → AD-Vue 4 syntax changes hit on this page:
- new Vue({ el, delimiters, data, methods }) → createApp + <script setup>
- mounted() → onMounted()
- <template slot="X"> → <template #X>
- <a-icon slot="prefix" type="user"> → <template #prefix><UserOutlined />
  </template> with explicit @ant-design/icons-vue imports
- v-model.trim → v-model:value (AD-Vue 4 uses named v-model on inputs)

Three legacy features deferred so Phase 4 stays small:
- i18n (Phase 7 wires up vue-i18n)
- theme switcher (custom component pending Phase 5)
- headline word-cycle animation (purely aesthetic)

Run `cd frontend && npm install && npm run dev`, open
http://localhost:5173/login.html. With Go panel running on :2053 the
form submits real credentials via the configured proxy.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5a — theme system + Vite 8 + vue-i18n 11

Bumps Vite to 8.0.11 (npm install picked up 6.4.2 from the stale
lockfile; clean install resolves the new constraint). Bumps vue-i18n
to 11.1.4 since v10 was just EOL'd.

Migrates aThemeSwitch.html — the two-flavor theme picker + global
themeSwitcher object — into:

- composables/useTheme.js: single reactive `theme` state with
  toggleTheme / toggleUltra. Boot side-effect applies the stored theme
  to <body>/<html> before Vue renders; watchEffect persists changes
  back to localStorage.
- components/ThemeSwitch.vue: full menu version for the main panel.
- components/ThemeSwitchLogin.vue: login-popover version.

AD-Vue 1 → 4 changes hit on this component:
- <a-icon type="bulb" :theme="filled|outlined"> dropped — replaced by
  explicit BulbFilled / BulbOutlined imports from
  @ant-design/icons-vue, swapped via <component :is="BulbIcon">
- Vue.component('a-theme-switch', { ... }) global registration → SFC
  + per-page import
- this.$message.config(...) (Vue 2 instance method) → message.config(...)
  imported from ant-design-vue, called once in login.js at boot

Login page now surfaces a settings button → popover → theme picker.

Known gap: web/assets/css/custom.min.css isn't yet imported into the
new bundle, so toggling dark mode currently only re-themes AD-Vue's
own components, not the panel chrome. The body class is still toggled
so behavior is correct; visual fidelity returns when custom.css is
ported or directly imported.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5b — port four shared components to Vue 3

CustomStatistic.vue and SettingListItem.vue are mechanical
Vue.component → SFC ports.

AppSidebar.vue: AD-Vue 4 dropped <a-icon :type="dynamic">, so the
five sidebar icons (dashboard/user/setting/tool/logout) live in a
name→component map and render via <component :is>. The legacy
<a-drawer slot="handle"> hack is replaced with a sibling fixed-
position toggle button. Tab paths take basePath/requestUri as
props instead of pulling them from Go template scope.

TableSortable.vue: the biggest Vue 3 rewrite of this phase.

  - $listeners is gone — replaced by inheritAttrs: false +
    explicit attrs forwarding
  - scopedSlots: this.$scopedSlots collapsed into Vue 3's unified
    slots object — just iterate Object.keys(this.slots) and forward
  - Vue 2 h(tag, { props, on, scopedSlots }, children) →
    Vue 3 h(tag, { ...props, ...on }, slotsObject)
  - 'a-table' string → resolveComponent('a-table') so app.use(Antd)
    registration is honored
  - inject: ['sortable'] (Options API) → inject('sortable', null)
    (Composition API) inside the trigger child
  - beforeDestroy → beforeUnmount
  - customRow's return shape flattened (no nested props/on/class)

Two intentional skips, documented in the migration doc:

  - aClientTable.html — slot fragments, not a component. Migrates
    inline with inbounds.html (new Phase 5f).
  - aPersianDatepicker.html — wraps a Persian-only third-party
    lib; defer until settings.html lands.

Build verified with vite 8.0.11.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): anchor Vite dev proxy so /login.html isn't forwarded

The /login proxy entry was matching any path starting with /login —
including /login.html, which Vite is supposed to serve itself. Without
the Go backend running, this caused ECONNREFUSED noise on every page
load.

Switched to regex patterns anchored with ^...$ so only the bare backend
paths (/login, /logout, /getTwoFactorEnable) and explicit sub-routes
(/panel/*, /server/*) get proxied. Static .html files Vite serves
directly are no longer matched.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): real dark mode + silence dev proxy ECONNREFUSED noise

Two issues from running login.html against no Go backend:

1. Dark mode toggled the body class but didn't actually re-theme any
   AD-Vue components. The legacy panel relied on custom.min.css which
   we haven't ported. AD-Vue 4 ships its own dark algorithm — wrap
   LoginPage in <a-config-provider :theme="{ algorithm }"> driven by
   our useTheme state, and AD-Vue restyles every component for free.
   Page chrome (background, card, title) gets explicit .is-dark CSS
   since the algorithm only covers AD-Vue components.

2. Vite logged every failed proxy attempt loudly. When the Go panel
   isn't running locally that's pure noise. Added a configure()
   callback that swallows ECONNREFUSED specifically; real errors
   (timeouts, 5xx, anything else) still surface.

Both fixes are dev-experience only — production build is unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): use legacy panel palette for login page dark mode

Earlier dark mode used invented colors (#141a26 page bg, #1f2937 card)
that didn't match the rest of the panel. Replaced with the actual
values from web/assets/css/custom.min.css:

  light          dark             ultra-dark
  bg #c7ebe2     bg #222d42       bg #0f2d32
  card #fff      card #151f31     card #0c0e12
  title #008771  title #fff/.92   title #fff/.92

Drove everything off CSS custom properties on .login-app so the
.is-dark / .is-ultra class swap is a few var overrides instead of
duplicating selectors. Also restored the legacy card metrics
(2rem radius, 4rem 3rem padding, 2rem title) so the new page
matches the old panel's geometry, not just its colors.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): match legacy wave layout + recolor for dark mode

The wave SVG had inline fill="#c7ebe2" (mint) on the bottom wave, so
in dark/ultra-dark mode it rendered as a pale-white blob against the
dark page. Stripped the inline fills, drove them off CSS variables
that swap with .is-dark / .is-ultra:

  light:      green tints + #c7ebe2 (mint) on the bottom wave
  dark:       #222d42 across all four waves
  ultra-dark: #0f2d32

The wave was also positioned wrong — anchored to the top 200px of
the viewport with absolute positioning. Restored the legacy layout:
  - .waves-header is fixed to the top of the viewport with z-index -1
    so the form floats over it
  - .waves-inner-header pushes the wave SVG down to ~50vh with a
    50vh-tall solid block of the page color
  - .waves SVG itself is 15vh tall, sitting at the bottom of that block

Net effect: top half is solid-colored, then a wavy edge transitions
into the rest of the page, with the form centered on top — matching
the legacy panel exactly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): bring wave-header to front so the wave actually shows

Two layering bugs were hiding the wave entirely:

1. .ant-layout-content had background: var(--bg-page) which painted an
   opaque rectangle covering the full content area — including the
   fixed wave-header behind it. Made the layout/content transparent
   and moved the bg paint up to .login-app (the outer ant-layout).

2. .waves-header had z-index: -1 which on its own was fine, but with
   .ant-layout-content opaque on top it was doubly buried. Promoted
   the wave-header to z-index: 0 and gave the form .login-row
   z-index: 1, so the form sits above the wave and the wave sits
   above the page-bg.

Also set --bg-page to the legacy mint (#c7ebe2) for light mode so the
bottom half of the page below the wave matches the legacy panel
(was white). Dark mode stays at the surface-100/login-wave palette.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): match legacy wave animation timings + dark page bg

Two reasons the bottom wave looked static in dark/ultra-dark:

1. Animation durations were 7s/10s/13s/20s. Legacy uses 4s/7s/10s/13s.
   The 20s on the bottom wave was so slow that against the low dark-
   mode contrast it read as motionless. Restored the legacy timings.

2. --bg-page in dark mode was #151f31 (card color / surface-100), but
   the legacy .under uses surface-200 (#222d42) — that's the color of
   the bottom half of the page, the same as the wave fill, so the
   wave appears to flow into the page rather than meeting a hard edge.
   Now it does.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): restore Hello/Welcome headline cycle on login

Earlier I deferred the legacy headline word-cycling animation as
"purely aesthetic". Restored it: the title now alternates between
'Hello' and 'Welcome' every 2 seconds, matching the legacy panel.

The legacy implementation toggled .is-visible / .is-hidden classes on
two <b> elements via setTimeout chains and DOM querying. Replaced
with a reactive ref + Vue 3 <Transition mode="out-in"> so the fade
between words is declarative — no manual DOM manipulation, and the
interval is properly cleaned up in onBeforeUnmount.

The earlier "Welcome to 3x-ui" string was wrong on two counts: it
should be just "Welcome", and it should be one of two cycling words
with "Hello" preceding it.

Ultra-dark palette already matched legacy after the prior wave timing
fix; no additional changes needed there beyond the animation speeds
that now also apply to ultra-dark via the shared CSS rules.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): correct dark login bg + give ultra-dark wave real contrast

Two related fixes:

1. Default-dark wave-header bg was wrong. I had #0a2227, but that's
   the *ultra-dark* override; default dark uses --dark-color-background
   = #0a1222. Now the dark-mode top half is the legacy purple-blue
   instead of teal.

2. Ultra-dark wave fill is intentionally near-identical to its bg in
   the legacy palette (#0f2d32 vs #0a2227, ~5/11/11 RGB delta), which
   makes the wave look static even though the animation is running.
   Bumped --wave-fill / --wave-fill-bottom to #1f4d52 in ultra-dark
   only — far enough above the bg that the motion reads, while
   staying within the same teal hue family.

Also corrected ultra-dark --bg-page back to #0f2d32 (was briefly
#0c0e12, which is the card color, not the page color).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): drop ultra-dark bottom-wave seam line

Last fix made the wave fill #1f4d52 in ultra-dark for both top-three
waves and the bottom wave, which gave visible motion but exposed a
hard horizontal line where the bottom wave's flat lower edge met the
page bg (#0f2d32). The user noticed it as "the wave at the bottom
not moving its like a line" — they were seeing the SVG's clipped
bottom edge, not the wave itself.

Solution: only the top three waves get the brighter fill (those carry
the visible motion). The bottom wave reverts to #0f2d32 = --bg-page,
so its flat bottom edge merges seamlessly into the page below. Net
effect: motion is still visible (from waves 2 and 3), and there's no
seam line at the bottom of the SVG.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5c-i — index.html dashboard shell

Replaces the smoke-test App.vue with a real IndexPage shell so the
/index.html route now boots the actual dashboard layout in Vue 3:

- a-config-provider drives AD-Vue 4's dark algorithm from useTheme
  (same pattern as LoginPage)
- AppSidebar (Phase 5b component) is wired in with basePath +
  requestUri props
- a-spin loading state with placeholder card while we build out the
  rest of the page
- Page palette mirrors the legacy: light #f0f2f5, dark #0a1222
  (--dark-color-background), ultra-dark #21242a

The 1,805-line legacy index.html is too big for one commit. Split
into five sub-phases on the todo list: ii) status cards + /server/status
polling, iii) xray status card, iv) logs/backup/panel-update modals,
v) custom-geo section.

frontend/src/App.vue and frontend/src/main.js (smoke-test scaffold)
are removed — both purposes now served by IndexPage and index.js.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5c-ii — live status cards on the dashboard

Adds the CPU / memory / swap / disk dashboard cards to IndexPage,
backed by a useStatus() composable that polls /panel/api/server/status
every 2 s and a Status / CurTotal model ported from the legacy inline
classes in index.html.

- models/status.js — Status & CurTotal classes (CurTotal exposes
  reactive .percent and .color computed-style getters; Status maps
  the API payload + xray state to color/message strings)
- composables/useStatus.js — 2s polling with shallowRef so each fetch
  swaps the whole Status object atomically. WebSocket integration
  intentionally deferred — the legacy panel falls back to this same
  2s polling when its websocket drops, so we ship the proven path
  first and add WS on top in a later sub-phase.
- pages/index/StatusCard.vue — four a-progress dashboard widgets in
  a 2x2 grid (mobile collapses to a 1x4). CPU widget exposes a
  history button; the modal it opens is part of 5c-iv.
- IndexPage now consumes both, plus useMediaQuery so the layout
  responds to viewport changes.

AD-Vue 4 changes: <a-icon type="area-chart"|"history"> dropped in
favor of explicit AreaChartOutlined / HistoryOutlined imports.
<a-tooltip slot="title"> → <template #title>.

i18n strings still hardcoded English (Phase 7 wires up vue-i18n).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5c-iii — xray status card + stop/restart controls

XrayStatusCard.vue renders the right-hand card on the dashboard:

- Title with mobile-only version tag (matches the legacy collapse)
- Animated badge for the running/stop/error states. The pulsing dot
  comes from xray-pulse keyframes (renamed from runningAnimation in
  legacy custom.min.css). Color rings on the badge use the legacy's
  per-state border-color overrides on .ant-badge-status-processing.
- Error state replaces the badge with a popover that surfaces the
  multi-line errorMsg + a logs shortcut.
- Action row at the bottom: optional logs (when ipLimitEnable),
  stop, restart, and version switch.

IndexPage now wires:
- POST /panel/api/server/stopXrayService and /restartXrayService,
  followed by a refresh() so the status card reflects the new state
  without waiting for the next poll tick
- POST /panel/setting/defaultSettings to read ipLimitEnable
- Stub handlers for the panel-logs / xray-logs / version-switch /
  cpu-history modals — those land in 5c-iv

AD-Vue 4 changes hit on this card:
- <a-icon type="bars|poweroff|reload|tool"> → explicit
  BarsOutlined / PoweroffOutlined / ReloadOutlined / ToolOutlined
- <span slot="title|content"> → <template #title|#content>
- The .xray-*-animation classes ship as global <style> (not scoped)
  so they pierce AD-Vue's internal .ant-badge-status-* DOM.

i18n still hardcoded English; Phase 7 wires vue-i18n.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5c-iv (a) — panel update / logs / backup modals

Adds three of the six dashboard modals plus a Quick Actions card
that surfaces them. The remaining three (xray logs, version picker,
CPU history sparkline) ship in 5c-iv-b.

- PanelUpdateModal.vue — current vs latest version, "update now"
  button. Confirm dialog → POST /panel/api/server/updatePanel,
  then poll /server/status for up to 90s until the new panel
  answers, then reload.
- LogModal.vue — panel logs viewer. Filters: rows (10-500), level
  (debug/info/notice/warning/error), syslog toggle. Auto-fetches
  on open and on every filter change. Color-coded timestamps and
  levels via inline span styles. Download button writes the raw
  log to x-ui.log via FileManager.downloadTextFile.
- BackupModal.vue — db export (window.location to /getDb) and
  import (FormData upload to /importDB, then panel restart + reload).
- Quick Actions card surfaces Logs / Backup / Update buttons and
  shows an orange update badge (extra slot) when an update is
  available.

Modal-busy pattern: long-running operations (update, import) emit
a `busy` event with a tip; IndexPage flips its a-spin overlay so the
user sees a loading message while the panel is restarting.

AD-Vue 4 changes:
- v-model on <a-modal> renamed to v-model:open
- v-model on <a-input>/<a-select>/<a-checkbox> uses the named
  v-model:value / v-model:checked pattern
- <a-icon type="..."> dropped — explicit Ant icon imports
  (BarsOutlined, CloudServerOutlined, CloudDownloadOutlined,
  DownloadOutlined, UploadOutlined, SyncOutlined)
- Modal.confirm() replaces this.$confirm() since setup() has no `this`

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5c-iv (b) — cpu-history / xray-logs / xray-version modals

Wires up the three remaining dashboard buttons that were stubbed in
5c-iv (a): the CPU history button on StatusCard, the xray-logs button
in XrayStatusCard's error popover and ipLimitEnable action, and the
"Switch xray" button in XrayStatusCard's action footer.

- Sparkline.vue: shared SVG line chart (composition-API port of the
  inline Vue 2 component). Per-instance gradient id avoids defs
  collisions between sparklines on the same page.
- CpuHistoryModal.vue: bucket dropdown (2m/30m/1h/2h/3h/5h) drives
  GET /panel/api/server/cpuHistory/{bucket}; renders via Sparkline.
- XrayLogModal.vue: rows + filter + direct/blocked/proxy checkboxes;
  POST /panel/api/server/xraylogs/{rows} returns access-log entries
  rendered as a colored HTML table; download button serializes to text.
- VersionModal.vue: collapse with Xray panel (radio list of versions
  from getXrayVersion, install via installXray/{version}) and Geofiles
  panel (per-file reload + Update all). CustomGeo collapse panel is
  Phase 5c-v.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5c-v — custom-geo section in VersionModal

Adds the third collapse panel ("Custom geo") that lets users register
external geosite/geoip files referenced by routing rules via
ext:<filename>:tag. Backend endpoints are unchanged.

- CustomGeoSection.vue: bordered table over /panel/api/custom-geo/list
  with per-row edit, download (refetch), and delete actions, plus an
  Add button and Update-all. Lazy-loads the list when the parent
  collapse opens this panel — closed panels don't fetch.
- CustomGeoFormModal.vue: shared add/edit form with the same alias
  regex (^[a-z0-9_-]+$) and URL validation as legacy. Type and alias
  are immutable when editing — backend rejects changes anyway.
- ext:<filename>:tag value is click-to-copy via ClipboardManager.
- Relative time is computed inline (no moment dep); tooltip shows the
  absolute timestamp.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5d-i — settings page shell + dirty tracking

Adds the settings entry as a new Vite multi-page input. Lays down the
shared page chrome (sidebar, save bar, restart, security alert) and the
AllSetting fetch/dirty-poll lifecycle so 5d-ii through 5d-vi can drop
in tab partials without re-implementing it.

- settings.html + src/settings.js: third Vite entry; mounts SettingsPage.
- SettingsPage.vue: page chrome with the legacy two-button save/restart
  bar, conf-alerts banner, and 5 a-tabs (4 always-visible + the formats
  tab gated on subJsonEnable || subClashEnable). Each tab body is an
  a-empty placeholder until 5d-ii…vi fill them in.
- useAllSetting.js composable: POST /panel/setting/all on mount, mirrors
  the legacy 1s busy-loop dirty check via setInterval, and exposes
  fetchAll/saveAll. saveDisabled flips off as soon as the user diverges
  from the server snapshot.
- restartPanel rebuilds the URL (host/port/scheme/base path) from the
  saved settings so users land on the new endpoint after a port or
  cert change.
- models/setting.js: adopts the @/utils alias and a leading file-level
  doc — semantics unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5d-ii — settings General tab

Ports the panel/general partial (the largest single tab) — six
collapse panels: General, Notifications, Certificates, External
traffic webhook, Date and time, LDAP.

- GeneralTab.vue receives the reactive AllSetting via props and binds
  fields directly with v-model:value; SettingsPage stays the sole
  fetch/save owner.
- remarkModel/remarkSeparator surfaced as computed v-models that
  read+write the underlying single-string field (legacy stores them
  packed as <separator><orderedKeys>, e.g. "-ieo").
- LDAP inbound-tags select binds to a CSV ↔ array computed; inbound
  options come from /panel/api/inbounds/list on mount.
- Language select stays cookie-based via LanguageManager and reloads
  on change — same UX as legacy.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5d-iii — settings Security tab + 2FA modal

Ports the panel/security partial: change-credentials form and 2FA
toggle. The 2FA modal is a new shared component since enabling 2FA,
disabling 2FA, and changing credentials all funnel through it with
slightly different copy.

- TwoFactorModal.vue: 'set' flow renders a QR code + manual key + a
  6-digit verifier; 'confirm' flow renders just the verifier. The
  parent passes a confirm(success) callback that fires only when the
  entered code matches the live TOTP value (otpauth lib).
- SecurityTab.vue: holds the local user form (oldUsername/oldPassword/
  new*), POSTs /panel/setting/updateUser, and on success force-redirects
  to logout. When 2FA is on, the credentials change goes through the
  confirm-modal first.
- toggleTwoFactor leaves the switch read-only (the v-bound :checked
  matches AllSetting) and only flips after the modal succeeds, so
  cancelling out leaves state unchanged.
- Adds otpauth ^9.5.1 dep (qrious was already present).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5d-iv — settings Telegram tab

Ports the panel/telegram partial: bot enable/token/chatId/lang in the
General panel, schedule/backup/login/CPU-threshold in Notifications,
and proxy/API-server overrides in the third panel. All bindings live
on the shared AllSetting reactive — no fetch/save logic in this tab.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5d-v — settings Subscription general tab

Ports the subscription/general partial — four collapse panels covering
the master enable switches, presentation/template fields, certs, and
update interval.

- Sub path goes through a strip-on-input + normalize-on-blur computed:
  legacy stripped `:` and `*` and ensured the value starts and ends
  with a single `/` — same here.
- Both `subEnableRouting` and the announce/profile/title/support URLs
  are bound directly on AllSetting.
- The "Subscription URI override" placeholder mirrors the legacy
  pattern for the manual full-URL form.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5d-vi — settings Subscription formats tab

Ports the subscription/json partial — paths/URIs for the JSON and
Clash formats plus the four packed-JSON sub-fields: fragment, noises,
mux, and direct routing rules.

- subJsonFragment / subJsonMux / subJsonNoises / subJsonRules are each
  a JSON string on the wire; the tab exposes their fields as computed
  v-models that read+write the underlying JSON. Toggling a top-level
  switch off resets the field to "" (matches legacy semantics).
- Direct routing rules surface the IP and domain entries of the seed
  rule array as multi-select tag inputs; setting/removing tags
  edits the rules array in place rather than rebuilding it from
  scratch, so manually-added rules are preserved.
- Tab is gated on subJsonEnable || subClashEnable in the parent (only
  rendered when the user actually opted into one of those formats).

This closes Phase 5d — full settings page parity with the legacy panel
across all five tabs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): route /panel/<route> to migrated pages in dev

The sidebar links to production-style URLs like /panel/settings, but
in dev that gets proxied to the legacy Go template — which fails
because we haven't loaded the legacy asset chain. Add a proxy bypass
so /panel and /panel/settings are served from index.html / settings.html
on the Vite dev server itself. Unmigrated routes (inbounds, xray)
still proxy to Go.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(csrf): expose token endpoint for SPA pages and fetch it from axios

The legacy panel pages got their CSRF token from a <meta name="csrf-token">
tag rendered by Go. SPA pages built by Vite don't have that, so every
unsafe (POST/PUT/DELETE) request from them was hitting CSRFMiddleware
with no token and getting 403 — visible as the settings page being
stuck on "Loading…" because POST /panel/setting/all failed.

- web/controller/xui.go: GET /panel/csrf-token returns the session
  token. Lives under the xui group so checkLogin still gates it; the
  CSRFMiddleware on the same group is a no-op for GET.
- frontend/src/api/axios-init.js: cache the token at module scope and
  lazy-fetch it when a non-safe request needs one. Seed from the meta
  tag first when present (legacy compat). On a 403 response, drop the
  cache and retry once — handles the case where a server restart
  rotated the token after the SPA loaded.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): keep sidebar links absolute when basePath is empty

The dashboard sidebar built tab keys as basePath + 'panel/...'. In dev
the window-injected basePath is '' so the resulting key was a relative
path like 'panel/settings'. When the browser resolved that against the
current /panel/settings URL it produced /panel/panel/settings — visible
as broken navigation between Dashboard and Settings.

Force a leading slash so the keys are always absolute regardless of
whether the host injected a basePath.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-i — inbounds page shell + list fetch

Adds the inbounds entry as a fourth Vite multi-page input and wires
/panel/inbounds through the dev proxy bypass. Lays down the page
chrome (sidebar, summary statistics card, refresh button) and the
fetch lifecycle composable so 5f-ii onward can drop in the table
columns and the modals without re-implementing it.

- inbounds.html + src/inbounds.js: fourth Vite entry; mounts InboundsPage.
- InboundsPage.vue: sidebar + summary card (totals over up/down,
  all-time, inbound count, client tags) + a basic table with enable/
  remark/port/protocol/traffic/expiry columns. Row actions, popovers,
  search/filter, auto-refresh, and the WebSocket delta path are all
  deferred to subsequent 5f subphases.
- useInbounds.js composable: GET /panel/api/inbounds/list +
  POST /panel/api/inbounds/onlines + POST /panel/api/inbounds/lastOnline +
  POST /panel/setting/defaultSettings, then computes the
  per-inbound clientCount roll-ups (active/deactive/depleted/expiring/
  online/comments) the table popovers consume.
- models/dbinbound.js + models/inbound.js: switched the legacy-utils
  import to the @/utils alias for consistency with the rest of the
  app. Semantics unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-ii — inbound list table + search/filter + auto-refresh

Fleshes out the inbound list with the full column set, search & filter
toolbar, row enable toggle wired to /panel/api/inbounds/setEnable/:id,
and a per-row action dropdown that emits events the parent will route
to modals as those land in 5f-iii through 5f-vii.

- InboundList.vue (new): toolbar (Add inbound + General actions
  dropdown + Refresh + auto-refresh popover), search-or-filter switch
  with the legacy radio buttons (Active/Disabled/Depleted/Depleting/
  Online), and a a-table with desktop and mobile column variants.
  Cells use AD-Vue 4's #bodyCell slot — protocol/clients/traffic/
  allTime/expiry/info cells render the same popovers and tags as
  legacy. Row enable switch is optimistic with rollback on POST
  failure.
- visibleInbounds computed mirrors the legacy search and filter
  projection: deep search through dbInbound + clients, or filter
  reduces inbound.settings.clients to the selected bucket so the
  table only shows matching client rows.
- Auto-refresh interval is read/written to localStorage with the
  same keys (`isRefreshEnabled`, `refreshInterval`) as the legacy
  panel. WebSocket delta updates are still deferred.
- Action menu emits event payloads {key, dbInbound}; the parent
  currently shows a "coming in later 5f subphase" toast for each.
  Modals (edit/qr/clone/delete/reset/info/clients) land in
  5f-iii through 5f-vii.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(inbounds): wrap popover-table rows in <tbody>

Vue's template compiler warned that <tr> can't be a direct child of
<table> per the HTML spec; the browser silently inserts a <tbody>
wrapper but Vue's SSR/hydration path doesn't, which can cause
hydration mismatches. Add explicit <tbody> in both popover tables
(traffic + mobile-info).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-iii — inbound add/edit modal + delete/clone/reset

Wires up the inbound CRUD flows. The protocol-specific and transport-
specific forms are still ahead in 5f-iii-b — for now the modal exposes
those as JSON textareas so users can both edit existing inbounds without
losing settings and create new ones from default templates.

- InboundFormModal.vue: tabbed modal with a full Basics tab (enable,
  remark, protocol, listen, port, total GB, traffic reset, expiry
  date) and three JSON-edit tabs (Settings, Stream, Sniffing). Add
  mode stamps a fresh template per protocol via
  Inbound.Settings.getSettings(protocol); changing the protocol in
  add mode restamps the JSON. Edit mode pretty-prints the existing
  JSON so the user sees the same fields they save back.
- POST /panel/api/inbounds/add or /panel/api/inbounds/update/:id on
  submit; on success the parent refreshes the list and the modal
  closes. Malformed JSON in any of the three textareas surfaces a
  message.error and aborts the save without losing user input.
- InboundsPage.vue: wires the row action menu to real handlers —
  edit (opens the modal in edit mode), delete, reset-traffic,
  clone, reset-clients, del-depleted-clients all go through
  Modal.confirm and refresh on success. General actions menu wires
  reset-inbounds / reset-clients / del-depleted-clients the same way.
  Remaining actions (qrcode/info/import/export/copyClients) still
  toast as "coming soon" — those land in 5f-iv and 5f-v.
- Adds dayjs ^1.11.20 dep for the a-date-picker v-model interop.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-iv — client add/edit + bulk-add modals

Wires per-inbound client management. Both flows go through the same
addClient/updateClient endpoints as legacy; the modals just funnel
the form state into the right shape (`{id, settings: '{"clients": [...]}'}`).

- ClientFormModal.vue: protocol-aware single-client editor — email/
  password/id/auth/security/flow/subId/tgId/comment/ipLimit/totalGB/
  expiry/renewal fields are shown/hidden per protocol like legacy.
  Edit mode displays the per-client traffic stats with a reset
  button; IP-limit log is read on click and clearable. Random
  helpers (sync icon next to each label) regenerate UUID/email/
  password/sub-id values.
- ClientBulkModal.vue: 1–500 clients in one POST, with the legacy
  five email-generation modes (Random / +Prefix / +Num / +Postfix /
  Pure-Prefix-Num-Postfix). Builds clients via the protocol-aware
  factory and concatenates their toString() output into a single
  settings.clients JSON array.
- InboundsPage.vue: opens both modals from the row action menu
  (`addClient` / `addBulkClient`). They both refresh the inbound list
  on success.
- Outstanding row actions still toast as "coming soon": qrcode,
  showInfo, copyClients, clipboard. Those land in 5f-v / 5f-vi.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-v — inbound info + QR-code modals

Wires the row "info" and "qrcode" actions and ports the legacy
inbound_info_modal end-to-end. The info modal handles every protocol
the legacy panel did:
  • multi-user (VMess/VLess/Trojan/SS-multi/Hysteria) — per-client
    table + share links + per-link QR;
  • SS single-user — share link + QR;
  • WireGuard — full peer table with downloadable peer-N.conf and a
    wg:// share link per peer;
  • Mixed/HTTP/Tunnel — connection-detail tables.

- QrPanel.vue: shared link card (header tag, copy button, optional
  download button, optional QR canvas, monospace footer with the
  raw value). Per-instance QRious instances are repainted on
  value/size change.
- InboundInfoModal.vue: full info modal. Subscription URL block keys
  off subSettings.subURI/subJsonURI; IP-log lazy-loads on open and
  surfaces refresh + clear; tg-id, last-online, depleted/enabled tags
  all match legacy.
- QrCodeModal.vue: lighter modal used for the row "qrcode" action on
  SS-single and WireGuard inbounds (just the QRs, no info table).
- InboundsPage.vue: wires both flows. checkFallback() reproduces the
  legacy logic — when an inbound listens on a unix-socket fallback
  (`@<name>`), the link generator is pointed at the root inbound that
  owns the listen address so QRs/links carry the public host:port +
  the right TLS state. Multi-client navigation (focusing a specific
  client's links) is deferred to 5f-vi where the per-inbound expand-
  row table will pass the email through.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-vi — per-inbound client expand-row table

Each multi-user inbound row in the list now expands to show its
client roster, mirroring the legacy aClientTable component.

- ClientRowTable.vue: inner a-table with full desktop column set
  (action icons / enable / online / client-with-status-dot / traffic
  with progress bar / all-time / expiry with reset cycle) and a
  collapsed mobile variant (single dropdown menu + popover info).
  Self-contained: stats are looked up via a per-inbound email->stats
  Map; per-client confirms (reset/delete) live on the row.
- The component emits typed events (edit/qrcode/info/reset-traffic/
  delete/toggle-enable) — InboundsPage routes them back to the
  existing client and info modals (with `findClientIndex` so the
  modal opens focused on the right client).
- InboundList.vue: hooks ClientRowTable into the a-table's
  expandedRowRender slot; row-class-name `hide-expand-icon` and a
  scoped CSS rule hide the chevron for non-multi-user inbounds
  (HTTP/Mixed/Tunnel/WireGuard/SS-single) so they keep looking flat.
- toggle-enable-client routes through updateClient with the same
  `{id, settings: '{"clients": [...]}'}` shape as the other modals,
  so backend parsing stays single-pathed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-iii-b — replace inbound modal JSON textareas with structured forms

Rewrites InboundFormModal to look like the legacy panel: structured
forms for the common case, with a compact "Advanced (JSON)" fallback
for the rare bits we don't yet have UI for.

Tabs:
  • Basics — enable/remark/protocol/listen/port/total/trafficReset/expiry
  • Protocol — protocol-aware:
      VMess/VLess/Trojan/SS-multi/Hysteria in add mode embed an inline
        first-client form (email + ID/password/auth, security, flow,
        subId, comment, total GB, expiry);
      edit mode shows a clients-count summary table;
      VLess: decryption/encryption inputs;
      SS: method dropdown that re-randomizes password and propagates
        method change to the multi-user array (matches legacy
        SSMethodChange);
      HTTP/Mixed: accounts table with add/remove rows + Mixed
        auth/udp/ip toggles;
      Tunnel: address/port/network/followRedirect;
      WireGuard: secretKey/pubKey (regen via Wireguard.generateKeypair)
        + per-peer fields with PSK regen + allowedIPs add/remove +
        keepAlive.
  • Stream — only when canEnableStream(); transport selector with
      structured forms for TCP (proxy-protocol, http camouflage),
      WS (host/path/heartbeat/headers), gRPC (serviceName, multiMode),
      HTTPUpgrade (host/path). KCP/XHTTP fall back to the Advanced tab
      with an alert banner. Security selector with TLS (sni/alpn/
      fingerprint) and Reality (target/serverNames/keypair-gen via
      /panel/api/server/getNewX25519Cert / shortIds / fingerprint).
  • Sniffing — enabled/destOverride/metadataOnly/routeOnly/
      ipsExcluded/domainsExcluded as structured fields.
  • Advanced (JSON) — raw streamSettings + sniffing JSON for users
      reaching KCP/XHTTP/sockopt/finalmask/full TLS cert arrays. The
      stream JSON is auto-synced from the live model whenever the
      structured fields change.

State source of truth is a deeply-reactive Inbound + DBInbound pair
cloned on open; submit serializes via inbound.settings.toString() +
inbound.stream.toString() so the wire shape matches the legacy panel
byte-for-byte. streamNetworkChange semantics (clear flow when
TLS/Reality unavailable, reset finalmask.udp when not KCP) are
preserved.

Vision Seed for VLess + finer-grained TCP HTTP camouflage + the full
TLS cert/ECH editor will land in 5f-iii-c.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 5f-vii — shared text/prompt modals + remaining export/import wiring

Wires up the last batch of inbound row + general actions that were
toasting "coming soon": export-inbound-links, export-subs (per-inbound
and global), export-all-links, import-inbound, and the clipboard JSON
peek. Two small shared components back them — both can be reused by
the xray page later.

- TextModal.vue (shared): read-only multi-line viewer with a copy
  button and an optional download button when fileName is set.
  Replaces the legacy txtModal which the inbounds page used for every
  link export.
- PromptModal.vue (shared): generic title + input/textarea + confirm
  callback, with the legacy keybindings (Enter submits in single-line
  mode; Ctrl+S submits in textarea mode). Used here for import-inbound
  but also by xray-config edits in Phase 6.
- InboundsPage.vue: drops the toast stubs for `import`/`export`/`subs`
  on the general-actions menu and `export`/`subs`/`clipboard` on the
  per-row menu, routing each through openText / openPrompt + the
  appropriate model helper (genInboundLinks, etc.). The copyClients
  cross-inbound modal stays toast-stubbed — that's its own dedicated
  legacy modal worth its own commit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 6-i — xray page scaffold + Advanced JSON tab

The fifth and last legacy page comes online. Tabs are scaffolded with
a-empty placeholders for the structured editors (Basics / Routing /
Outbounds / Balancers / DNS) so navigation is stable; the
Advanced (JSON) tab is fully functional and lets power users edit
the raw xraySetting tree exactly like the legacy CodeMirror pane.

- xray.html + src/xray.js: fifth Vite multi-page entry, mounted as
  XrayPage; vite.config.js routes /panel/xray and /panel/xray/ to it
  through the dev proxy bypass alongside the other pages.
- XrayPage.vue: page chrome with the Save / Restart-xray bar, restart-
  output popover (surfaces /panel/xray/getXrayResult content when
  startup fails), 6 a-tabs, and a textarea-backed Advanced JSON editor.
  CodeMirror is intentionally not pulled in — the textarea works for
  every modern browser and keeps the bundle slim while structured
  editors land in 6-ii through 6-v.
- useXraySetting.js composable: POST /panel/xray/ on mount, mirrors
  the settings-page 1s busy-loop dirty check for both xraySetting
  and outboundTestUrl, and exposes saveAll + restartXray. The dirty
  flag relies on string equality of the pretty-printed JSON, so
  reformat-only edits don't enable Save.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 6-ii — xray Basics tab structured editor

Replaces the placeholder on the Basics tab with a structured form for
the most-touched fields of the xray template — outbound + routing
strategy, log levels, traffic stat counters, and the "basic routing"
shortcuts (block torrent / IPs / domains, direct IPs / domains, IPv4
forced, WARP / NordVPN routing).

- useXraySetting.js: hoists a parsed `templateSettings` reactive
  alongside the JSON string, with two cooperating watches that keep
  them in sync. Editing structured fields stringifies into xraySetting
  for the dirty-poll + Advanced JSON tab; editing the JSON re-parses
  into templateSettings only when valid, so structured tabs stay
  readable mid-edit.
- BasicsTab.vue: collapse panels mirror the legacy partial — General,
  Statistics, Logs, Basic routing. Every input is a computed v-model
  reading/writing into templateSettings; the routing-rule shortcuts
  funnel through ruleGetter/ruleSetter which match the legacy
  templateRuleGetter/templateRuleSetter behavior (replace-first,
  drop-duplicates, pop-the-rule-when-empty). Direct/IPv4 setters
  also call syncOutbound() to provision/prune the matching outbound.
- XrayPage.vue: imports BasicsTab + derives `warpExist`/`nordExist`
  from the parsed templateSettings. WARP/NordVPN provisioning modals
  are still placeholders that toast — those land in 6-v with the
  routing/outbound editors.

Default tab flips back to Basics so users land on the structured
editor.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 6-iii — xray Routing tab + rule modal

Replaces the Routing tab placeholder with a full editor for
templateSettings.routing.rules:

- RoutingTab.vue: a-table over the parsed rules with the legacy six-
  column layout (action / source / network / destination / inbound /
  outbound) and the same "lead value + N more" pill renderer for
  multi-value criteria. Mobile drops source/network/destination for
  readability. Per-row dropdown handles edit / move-up / move-down /
  delete; the array-mutation reordering replaces the legacy jQuery
  Sortable drag handle without pulling in a sortable lib.
- RuleFormModal.vue: full form mirroring xray_rule_modal.html —
  CSV inputs for sourceIP/sourcePort/vlessRoute/ip/domain/user/port,
  Network select, Protocol multi-select, Attrs key/value pairs,
  inbound-tag multi-select sourced from
  templateSettings.inbounds + parent inboundTags + dnsTag,
  outbound-tag single-select sourced from templateSettings.outbounds
  + clientReverseTags, and balancerTag from
  templateSettings.routing.balancers. Submit serializes via the
  same shape the legacy `getResult` produces (CSV → array, drop
  empty fields).
- XrayPage.vue: imports RoutingTab and exposes inboundTags +
  clientReverseTags from useXraySetting so the modal can populate
  its tag pools.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 6-iv — xray Outbounds tab + outbound modal

Replaces the Outbounds tab placeholder with a full table + add/edit
flow. The 1.3k-line legacy outbound modal is condensed to a tabbed
modal with structured Basics fields (tag/protocol/sendThrough/domain
strategy) and JSON tabs for the protocol-specific settings + stream
trees — same approach the Inbound modal uses, and a power user can
still edit the same trees via the page-level Advanced (JSON) tab.

- useXraySetting.js: adds fetchOutboundsTraffic +
  resetOutboundsTraffic + testOutbound. Test states are tracked per
  outbound index so the row's Test button can show loading + the
  Test-result column can render the response delay / status / error.
- OutboundsTab.vue: full table (action / identity / address / traffic
  / test result / test) plus a card-list mobile variant with the
  same row dropdown (set-first / edit / move up/down / reset traffic
  / delete). outboundAddresses() reproduces the legacy
  findOutboundAddress logic so each protocol's host:port list is
  rendered consistently. Add/edit go through OutboundFormModal,
  delete goes through Modal.confirm, reset traffic posts to
  /panel/xray/resetOutboundsTraffic with the row's tag (or
  "-alltags-" from the toolbar).
- OutboundFormModal.vue: tag/protocol/sendThrough/domainStrategy on
  the Basics tab; settings + streamSettings as raw JSON on their
  respective tabs. Tag-collision check happens client-side before
  emitting; malformed JSON aborts the save with a message.error.
- XrayPage.vue: imports OutboundsTab and wires the test action to
  the composable's testOutbound helper.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 6-v — xray Balancers tab + DNS placeholder

Brings Balancers to full parity with the legacy panel and adds a
DNS tab placeholder that exposes the full dns/fakedns trees as JSON
so users can edit them without falling through to Advanced.

- BalancerFormModal.vue: tag (with duplicate-tag warning across
  other balancers), strategy (random/roundRobin/leastLoad/leastPing),
  selector tag-mode multi-select sourced from existing outbound
  tags + free-form additions, fallback. Disable-on-invalid is
  driven by the duplicateTag + emptySelector computed flags.
- BalancersTab.vue: empty state with a single "Add balancer" CTA;
  populated state shows the legacy 4-column table (action / tag /
  strategy / selector / fallback) with per-row edit + delete in a
  dropdown. On submit the wire shape preserves the
  `strategy: { type }` nesting only when the strategy is non-default,
  matching the legacy emit. Tag renames also chase across
  routing.rules.balancerTag references so existing rules don't dangle.
- DnsTab.vue: master enable switch + raw JSON for `dns` and
  `fakedns`. Legacy had a dedicated server-by-server editor + a
  fakedns row editor; both are big enough to deserve their own
  commits, and the JSON path supports every field today.

WARP / NordVPN provisioning modals still toast as "coming soon" —
those are third-party API integrations worth their own commits.
The xray page now has structured editors for Basics / Routing /
Outbounds / Balancers and JSON editors for DNS / Advanced — every
xray tab the legacy panel offered is functional.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(server): Phase 8 — cut HTML routes over to web/dist/

Production cutover. Every user-facing HTML route now serves the
Vue-3-built bundle from web/dist/ instead of rendering the legacy
Go template; the long-hashed Vite assets are served at /assets/ from
the same embedded filesystem. The legacy templates in web/html/ and
the legacy static tree in web/assets/ are kept on disk for now in
case a quick revert is needed, but nothing the binary serves
references them.

What changed:
- web.go: a new //go:embed dist/* feeds the controller package via
  a SetDistFS hand-off before controller construction. The static
  /assets/ route is rebound: in dev to web/dist/assets/ on disk so
  Vite's incremental rebuilds show up live; in prod to the embedded
  dist via wrapDistFS (rooted one level deeper than wrapAssetsFS).
- controller/dist.go: serveDistPage helper used by every HTML
  handler. Reads dist/<name> from the embedded FS and applies two
  transforms before sending:
    1. injects <script>window.__X_UI_BASE_PATH__="..."</script>
       just before </head> so AppSidebar links resolve under the
       panel's basePath.
    2. when basePath != "/", rewrites Vite's absolute /assets/ URLs
       to <basePath>assets/ so installs running under a custom URL
       prefix load the bundle where the static handler lives.
  HTML responses go out with no-cache so panel upgrades reach
  users on the next refresh; hashed JS/CSS stays cacheable.
- controller/index.go: IndexController.index now serves
  dist/login.html for logged-out callers (the redirect for logged-in
  users is unchanged).
- controller/xui.go: XUIController.{index,inbounds,settings,xraySettings}
  each become a one-line wrapper around serveDistPage.

Smoke checklist for the maintainer:
- run `cd frontend && npm run build` to refresh web/dist/ before
  building the Go binary (the embed snapshot is taken at compile
  time);
- visit /panel/, /panel/inbounds, /panel/settings, /panel/xray and
  confirm each loads its Vue page;
- log out and log back in to verify the login flow;
- confirm the sidebar links navigate correctly under your install's
  basePath;
- POST flows (e.g. saving settings) still need the CSRF token —
  that endpoint (/panel/csrf-token, added earlier) is unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 6-vi — WARP + NordVPN provisioning modals

Replaces the toast stubs on the Basics tab and Outbounds toolbar
with the legacy WARP + NordVPN provisioning flows. Both modals now
stage their wireguard outbounds back into templateSettings.outbounds
through the same event channels OutboundsTab uses, so the existing
add / reset / delete / refresh-traffic surface keeps working.

- WarpModal.vue: empty state shows a single Create button that
  generates a wireguard keypair locally (Wireguard.generateKeypair)
  and posts it to /panel/xray/warp/reg; populated state surfaces
  the access_token / device_id / license_key / private_key, lets
  the user upgrade to WARP+ via /panel/xray/warp/license, refreshes
  the account info from /panel/xray/warp/config (plan / quota /
  usage in human-readable bytes), and stages a wireguard outbound
  with the WARP-specific reserved-byte encoding pulled from
  client_id. Add / Reset / Delete go through events the parent
  routes back to templateSettings.outbounds.
- NordModal.vue: dual-tab login (NordVPN access token →
  /panel/xray/nord/reg, or paste a NordLynx private key →
  /panel/xray/nord/setKey). Once authenticated, country / city /
  server selectors fetch from /panel/xray/nord/{countries,servers},
  servers sort by load ascending, the lowest-load server in the
  current city auto-selects. Reset emits oldTag/newTag so the
  parent renames matching routing rules in place; logout emits a
  remove-routing-rules event with prefix `nord-` to purge any
  dangling references.
- XrayPage.vue: holds warpOpen / nordOpen flags, ensures the
  outbounds array exists before mutating it, and wires the modal
  events (add-outbound / reset-outbound / remove-outbound /
  remove-routing-rules) to in-place edits of templateSettings.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): Phase 7 — vue-i18n wired up + login page translated

Sets up vue-i18n on top of the panel's existing TOML translation
files. The Go side stays the source of truth — translators continue
to edit web/translation/*.toml; a sync script snapshots those files
into per-locale JSON the Vue bundle imports. The login page is
translated end-to-end as a worked example; remaining pages can be
converted incrementally without infrastructure churn.

What's in the box:
- scripts/sync-locales.mjs: small TOML→JSON converter that walks
  web/translation/*.toml and writes frontend/src/locales/<code>.json.
  Handles the narrow subset of TOML the panel uses (flat key/value
  pairs + dotted [section.subsection] heads). Wired as a `prebuild`
  + `predev` script so production builds always include the latest
  strings without a manual step.
- src/i18n/index.js: createI18n() in composition mode with all 13
  locales emitted as their own Vite chunks. The active locale (read
  from the same `lang` cookie LanguageManager has always managed)
  plus the en-US fallback are eagerly loaded; the rest are
  dynamically importable via a loadLocale(code) helper. This keeps
  the per-page bundle the user actually downloads small — only ~30
  KB of strings end up in the initial payload, vs ~220 KB if all
  13 were eager.
- All five page entries (index/login/settings/inbounds/xray) wire
  the i18n plugin into createApp via .use(i18n).
- LoginPage.vue: t(...) replaces hardcoded English on the username
  / password / 2FA placeholders, the submit button label, and the
  Settings popover title. The Hello/Welcome headline cycle stays
  hardcoded — those are stylistic, not labels.

The 'Hello'/'Welcome' cycle stays in English deliberately; the rest
of the migration's components still ship hardcoded English and will
be converted page by page in follow-up commits.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* i18n(frontend): translate page chrome — sidebar, save bars, tabs, summary cards

Replaces hardcoded English with t() calls in the components every
user sees on every page load. The translations themselves come from
the existing TOML files via the sync script — no new strings, no
new locale keys.

Per component:
- AppSidebar.vue: 5 menu titles (dashboard / inbounds / settings /
  xray / logout). Computed so the sidebar re-renders when the
  cookie-driven locale flips on reload.
- IndexPage.vue: Quick actions card title + Logs / Backup / Up-to-
  date / Update buttons.
- StatusCard.vue: CPU / Memory / Swap / Storage labels +
  logical-processors / frequency tooltips.
- XrayStatusCard.vue: card title + error popover header + Stop /
  Restart / Switch xray action labels (kept the v-prefix version
  string as-is — it's content, not a label).
- SettingsPage.vue: 5 tab titles + Save / Restart-panel buttons +
  unsaved-changes warning.
- XrayPage.vue: 6 tab titles + Save / Restart-xray buttons +
  unsaved-changes warning.
- InboundsPage.vue: 5 summary-stat card titles.
- InboundList.vue: 10 column titles (computed for live locale),
  Add inbound / General actions buttons + every dropdown menu item,
  search placeholder, filter radio labels, popover titles
  (disabled / depleted / depleting / online), traffic + info
  popover row labels.

Total: ~75 strings localised across 8 files. The remaining English
labels live in the per-tab settings forms, the form modals
(Inbound / Client / Outbound / Rule / Balancer / WARP / Nord), and
the per-row table cell helpers — all incremental work that doesn't
touch infrastructure.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* i18n(frontend): translate every remaining English string on the index page

Closes the index page's i18n coverage. Combined with the page-chrome
commit, every label users see on the dashboard is now sourced from
the TOML translation files.

Per file:
- IndexPage.vue: loading-spinner tip (initial + dynamic).
- BackupModal.vue: modal title, both list-item titles + descriptions
  ("Back up" / "Restore"), in-flight busy tips ("Importing database…"
  / "Restarting panel…").
- PanelUpdateModal.vue: modal title, update-available alert,
  current/latest version row labels, "Up to date" tag + label,
  primary action button. Modal.confirm now uses the translated
  panelUpdateDialog / panelUpdateDialogDesc with #version#
  substitution; success toast uses panelUpdateStartedPopover.
- LogModal.vue: title slot ("Logs"). The Debug/Info/Notice/Warning/
  Error log-level options stay literal — they're xray's wire values,
  not user-facing labels (matches the existing settings-page choice).
- XrayLogModal.vue: title + Filter label. Direct/Blocked/Proxy stay
  literal for the same reason.
- VersionModal.vue: modal title + xray-switch alert + per-file
  tooltip + "Update all" button + custom-geo collapse header. The
  Modal.confirm flows for switchXrayVersion + updateGeofile use
  translated dialog/desc with #version# / #filename# substitution.
- CpuHistoryModal.vue: title slot.
- CustomGeoSection.vue: routing-hint alert, Add / Update-all buttons,
  every column title (computed for live locale), copy/edit/download/
  delete tooltips, copy toast, delete-confirm modal, empty-state
  text.
- CustomGeoFormModal.vue: add/edit titles, OK/cancel labels, Type/
  Alias/URL field labels, alias placeholder, all three validation
  toasts.

Total: ~50 strings localised across 8 index-page files. The Hello /
Welcome login headline cycle and a handful of literal xray wire
values (Direct/Blocked/Proxy/log levels) are intentionally kept
hardcoded.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* i18n(frontend): Phase 7-c — translate settings, inbounds modals, xray tabs

Continues the page-by-page translation pass started in cb37dd55 — runs
every user-visible string on settings (General/Security/Telegram/Sub),
inbounds (Client/QR/Info modals), and xray (Routing/Balancer/Rule/Warp/
Nord/Basics/Outbounds tabs) through useI18n. Updates the TOML→JSON sync
script to escape `@` (vue-i18n parses it as a linked-format prefix) and
refreshes all 13 locale files.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): Phase 9 — restore index dashboard, fix login/CSRF, port legacy styles

- Index dashboard regains the 8 cards that were lost in the SPA port
  (3X-UI panel info, Operation Hours, System Load, Usage, Overall Speed,
  Total Data, IP Addresses, Connection Stats), plus a Config button that
  shows the live xray config.json. Version display falls back through
  panelUpdateInfo → window.__X_UI_CUR_VER__ → '?' so dev mode isn't blank.
- Xray config no longer hangs on load: useXraySetting surfaces failures
  instead of leaving a perpetual spinner, and the Vite dev proxy stops
  hijacking POST requests to migrated routes (only GETs get bypassed).
- Inbound page no longer throws __asyncLoader/emitsOptions errors —
  inbound.js was missing imports (NumberFormatter, SizeFormatter,
  Wireguard) and InboundList kept emitting after unmount.
- Login round-trip works after logout: a public /csrf-token endpoint
  bootstraps the SPA before authentication, axios caches the token
  module-level, and the dev 401 handler navigates to /login.html
  instead of reloading the dashboard into a redirect loop.
- legacy.css mirrors the legacy panel's surface/text variables so dark
  and ultra-dark themes match main; every SPA entry imports it.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): rebuild xray DNS section to match main branch

DnsTab now exposes every field the legacy panel did — top-level toggles
(tag, hosts, queryStrategy, disableCache/queryConcurrency, fallback
strategy, client subnet), the servers table with per-row strategy and
domain/expectIP/unexpectedIP overrides, and the Fake DNS pool. The new
DnsServerModal covers the full add/edit flow and collapses to a bare
string when the user only sets an address — matching the wire shape
the legacy form emits for plain DNS entries like "8.8.8.8".

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): rebuild xray outbound modal with structured per-protocol forms

Replaces the JSON textareas with the same shape the legacy panel uses:
all 11 outbound protocols (vmess/vless/trojan/shadowsocks/socks/http/
mixed/wireguard/tun/dns/loopback/blackhole/freedom) get dedicated
fields, every transport (TCP/KCP/WS/gRPC/HTTPUpgrade/XHTTP) gets its
own panel, and TLS/Reality/sockopt/Mux are configured through the same
controls as the inbound side. Brings the SPA outbound editor to parity
with main so users no longer have to drop into raw JSON.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): bring inbound modal to full parity with main branch

Switches the default protocol on add to VLESS, fixes a crash when adding
a Mixed account (the constructor is SocksAccount, not MixedAccount),
and fills in the fields the SPA was previously delegating to the
Advanced JSON tab:
- TLS: cipher suites, min/max version, reject SNI / disable system root /
  session resumption switches, the certificate array with per-row
  Path-or-Content toggle (Set Default pulls from /panel/setting/
  defaultSettings), One Time Loading, Usage / Build Chain, plus ECH
  key/config with a Get New ECH Cert button.
- Reality: xver, target/SNI sync icons (uses getRandomRealityTarget),
  max time diff, min/max client version, short IDs randomizer, SpiderX,
  mldsa65 seed/verify with Get New Seed.
- Stream: full structured forms for every transport — TCP HTTP
  camouflage gets its request/response editor, mKCP gets MTU/TTI/uplink/
  downlink/CWND/maxSendingWindow, WebSocket / gRPC (now with Authority) /
  HTTPUpgrade get headers + proxy-protocol toggles, XHTTP gets the
  full SplitHTTPConfig surface (mode-aware fields, padding obfs,
  session/sequence placement, uplink data, no-SSE).
- New External Proxy section and a structured Sockopt block (mark,
  TCP keepalive/timeout/clamp, fast open, MPTCP, penetrate, V6Only,
  domain strategy, congestion, TProxy, dialer/interface, trusted XFF).
- VLESS gets the legacy X25519 / ML-KEM-768 buttons that fetch fresh
  decryption/encryption blocks via /panel/api/server/getNewVlessEnc.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): add FinalMask UI (TCP/UDP masks + QUIC params) to inbound and outbound

Mirrors web/html/form/stream/stream_finalmask.html as a shared
FinalMaskForm component used by both modals — they share the same
StreamSettings shape (addTcpMask/addUdpMask/finalmask/enableQuicParams)
so a single template handles both. Surfaces:
- TCP masks for raw/tcp/httpupgrade/ws/grpc/xhttp networks: fragment,
  sudoku, and header-custom (with the 2D clients/servers groups, each
  row supporting array/str/hex/base64 packets and a randomize button
  for base64).
- UDP masks for hysteria protocol or kcp network: hysteria gets just
  salamander; kcp gets the full type list (mkcp variants, header-*,
  xdns/xicmp, header-custom with flat client/server lists, and noise).
  Switching to xdns shrinks the kcp MTU to 900 to match the legacy
  panel's behavior.
- QUIC Params for hysteria or xhttp: congestion (incl. brutal up/down
  fields), debug, UDP hop ports/interval, idle/keepalive timeouts,
  path-MTU discovery toggle, and the four receive-window tunables.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): remove duplicate Outbound test URL from xray Advanced tab

The Basics tab already exposes this field through BasicsTab —
duplicating it on the Advanced tab let two inputs race the same
ref and only added clutter.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): unify theming on vanilla AD-Vue light/dark/ultra-dark

The legacy panel CSS (custom.min.css ported as legacy.css) tinted every
non-primary button teal-green via .dark .ant-btn:not(.ant-btn-primary)
overrides while AD-Vue 4's darkAlgorithm kept primary buttons blue —
producing the mixed blue/green button look on dark mode. Drop legacy.css
entirely and let AD-Vue 4's algorithms own the palette.

Centralize antdThemeConfig in useTheme.js so every page resolves to the
same source of truth (light = defaultAlgorithm, dark = darkAlgorithm,
ultra-dark = darkAlgorithm + deeper colorBgBase/Layout/Container/
Elevated tokens). Each page's <a-config-provider> now imports the
shared computed instead of defining its own copy.

Drops the 67 KB legacy CSS chunk; per-page CSS bundles fall to ≤5.9 KB.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): restore computed import in Settings + Xray pages

When 5f1aba28 dropped the local antdThemeConfig computed (now shared
from useTheme), it also stripped `computed` from the import list — but
both pages still call computed() elsewhere (confAlerts, advanced-tab
helpers). Re-adds it.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): retheme dashboard gauges to AD-Vue blue and shrink them

- StatusCard's CPU/RAM/Swap/Storage dashboards rendered at AD-Vue's
  default 120px width which made the percent text balloon to ~36px.
  Drop to 90px (70px on mobile) so the gauge fits the rest of the card.
- The CurTotal.color thresholds still hardcoded the legacy teal/orange
  palette (#008771 / #f37b24 / #cf3c3c). Switch to AD-Vue's primary /
  warning / danger tokens (#1677ff / #faad14 / #ff4d4f) so the gauges
  match the rest of the panel under both light and dark themes.
- XrayStatusCard's running-animation badge ring also still pointed at
  the deleted --color-primary-100 var; hardcode the new primary blue.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* i18n: shorten backupTitle to "Backup & Restore" across all 13 locales

The backup modal header was the second-longest title in the dashboard
on every locale ("Database Backup & Restore" / "Резервне копіювання
та відновлення бази даних" / etc). Drop the "Database / Veritabanı /
数据库" qualifier — the modal already lives under the "Database"
column, so the shorter form reads cleaner on narrow viewports.

Updated both the .toml source-of-truth files and the synced .json
locales (re-running scripts/sync-locales.mjs).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* i18n: collapse two translation databases into a single web/translation/<lang>.json set

The Vue SPA had been reading from frontend/src/locales/*.json while the
Go binary still loaded web/translation/translate.*.toml — and a
sync-locales.mjs pre-build step kept the two in lockstep, with TOML as
the source of truth. Now that go-i18n v2.6.1 already flattens nested
JSON via recGetMessages/addChildMessages, both runtimes can share one
file per locale.

- Move the 13 nested-JSON locale files to web/translation/<lang>.json
  so they live alongside the Go //go:embed translation/* directive.
- Switch web/locale/locale.go from toml.Unmarshal to json.Unmarshal
  (and drop the pelletier/go-toml import — it's now indirect-only).
  Confirmed via a smoke test that pages.index.cpu, subscription.title,
  tgbot.commands.help, and menu.settings all resolve in en-US, fa-IR,
  ru-RU, and zh-CN.
- Repoint Vue's i18n loader at the new path (../../../web/translation/
  *.json glob) and drop the moved-here pathDelimiter comment that no
  longer applies.
- Delete the 13 legacy translate.*.toml files and the sync-locales.mjs
  script + its npm pre-script hooks (predev/prebuild/i18n:sync). The
  Telegram bot and subscription page still get their messages because
  they were reading the same MessageIDs the JSON files now produce.
- Update copilot-instructions.md so the next contributor knows where
  the canonical translation files live.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): redesign expand-row + retheme client visuals

When you expanded an inbound row, the nested <a-table> inside
ClientRowTable burst out of the parent's scroll-x box — its
.ant-spin-container ended up wider than the parent's narrow
.ant-table-cell, so the child looked oversized while the parent looked
squeezed. Replace the nested table with a CSS-grid layout that owns
its sizing, sits flush inside the expanded cell, and collapses to a
3-column layout on mobile (action menu, client identity, info popover).

While in there, fix three other client-row visuals:
- The Unicode infinity glyph (U+221E) renders as an "m"-shaped
  character in some system fonts (Windows Segoe UI in particular).
  Add a shared <InfinityIcon /> SVG component (legacy panel's path)
  and use it in ClientRowTable, InboundList, and InboundInfoModal —
  desktop and mobile cells.
- The "unlimited quota" traffic bar passed :percent="100" with no
  stroke-color, so AD-Vue auto-coloured it success-green. Pin it to
  the AD-Vue purple token (#722ed1) so it reads as the no-limit
  sentinel rather than another usage state.
- ColorUtils + the in-row statsExpColor still hardcoded the legacy
  teal/orange/red/purple palette (#008771 / #f37b24 / #cf3c3c /
  #7a316f). Map them onto AD-Vue 4's success/warning/danger/purple
  tokens (#52c41a / #faad14 / #ff4d4f / #722ed1) so badges, tags,
  and progress bars all match the rest of the panel.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): darken light-theme page bg so cards stand out

The light-theme --bg-page was #f0f2f5 — close enough to AD-Vue's #fff
card background that the cards faded into the page. Bump it to #e6e8ec
(a more visibly distinct gray) so cards lift cleanly off the surface.
Dark and ultra-dark stay where they were.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): shrink dashboard percent text and surface the unfinished arc

Two follow-up tweaks to the dashboard gauges:
- AD-Vue scales the percent text from the SVG, not from :width, so
  the 90px gauges still rendered the number at ~27px. Pin
  .ant-progress-text to 14px via :deep() and trim the gauge to 70px
  (60px on mobile) so the whole card stays compact.
- The default trail (rgba(0,0,0,0.06) / rgba(255,255,255,0.08)) was
  invisible on the light-theme card. Pass an explicit
  rgba(128,128,128,0.25) trail-color so the unfinished portion is
  visible under both light and dark themes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): migrate subpage.html to Vue 3 SPA

The subscription info page was the last page still rendered by Go
templates. Move it to the Vite multi-page setup so the whole panel
loads through one toolchain.

Frontend: SubPage.vue mounts at /sub/<id>?html=1 and reads window.__SUB_PAGE_DATA__
for the parsed view-model (traffic / quota / expiry + rendered share
links). Fix descriptions borders against the light-theme card by
painting the row divider on each cell's bottom edge — AD-Vue's <tr>
border doesn't render reliably under border-collapse:collapse.

Backend: serveSubPage reads dist/subpage.html, injects
window.__X_UI_BASE_PATH__ + window.__SUB_PAGE_DATA__ before </head>,
and rewrites Vite's absolute /assets/ URLs when the panel runs under
a URL prefix. Drop the legacy template-FuncMap wiring and switch the
sub server's static mount from web/assets to web/dist/assets.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): inbound modal QR + tabs + restored TLS fallbacks

Per-client QR action: the qr icon on the expand-row table opened the
big info modal instead of the QR modal. Route it to QrCodeModal and
extend that modal with a `client` prop so genAllLinks() produces the
per-client share URLs (and per-peer remarks for WireGuard).

Inbound's Data redesign: split the dense single-page view into three
tabs — Inbound, Client, Subscription. Drop every QR rendering from
this modal (QrCodeModal is the QR home now). Each row in the Inbound
tab is one label/value pair instead of the legacy 2-column grid, and
long values like the VLESS encryption blob render as a wrapping code
block with a copy button so they can't blow out the dialog. The
Subscription tab renders sub URL + JSON URL as clickable anchors that
open in a new tab.

Restored TLS fallbacks UI: the model already exposed
VLESSSettings.Fallback / TrojanSettings.Fallback with addFallback /
delFallback / fallbackToJson, but the form modal never surfaced them
during the Vue 3 migration. Re-add the legacy form (SNI, ALPN, Path,
Destination, PROXY) on the protocol tab, gated on TCP transport plus
(for VLESS) encryption=none — same conditions as main.

Column widths: Protocol 70→130 and All-time Traffic 60→95 in the
inbound list; All-time Traffic 90→130 in the client expand-row, so
the header text fits and tags don't get squeezed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): navy dark theme + rounded inbound/client corners

Dark theme picks up a refined navy palette (page #0a1426, cards
#142340, sider #0d1d33) so the sidebar blends with the rest of the
surface; ultra-dark stays neutral black. Resolves the previous mismatch
where AD-Vue 4 hardcoded #001529 / #002140 for the sider, trigger and
dark Menu items via Layout.colorBgHeader / colorBgTrigger and Menu's
colorItemBg — overrides go through the component-token map now.

Round the inbound table's outer corners (header start/end + last row
end) and wrap the client expand-row grid in a 1px / 8px-radius border
so the list reads as a contained block instead of a flush rectangle.

Linter-driven whitespace cleanup across inbounds/*.vue rolled into the
same commit since it can't be split out cleanly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): xray tab fixes — modal close, tag validation, full XHTTP, reset to default

Modal close: BalancersTab / OutboundsTab / RoutingTab confirmDelete used
arrow expressions that returned splice's removed-items array. AD-Vue 4
treats truthy non-thenables from onOk as "still pending" and never closes
the dialog (see ActionButton.js:103-106), so the confirm modal stayed
open. Wrap the body so onOk returns undefined and AD-Vue auto-closes.

Tag validation: outbound + balancer modals only flipped between
warning/success on duplicate, leaving the empty case as a green ✓.
Split into a 3-state computed — error (empty) / warning (duplicate) /
success — and wire a help message so the input clearly explains why
the OK button is disabled.

Reset to default: re-add the legacy "Reset to Default" panel at the
bottom of BasicsTab. Calls /panel/setting/getDefaultJsonConfig and
overwrites templateSettings; the existing watch re-stringifies so the
JSON tab + dirty-poll see the new state.

Restored Basics option lists from main: IPs (4→10, +Vietnam/Spain/
Indonesia/Ukraine/Türkiye/Brazil), DomainsOptions (4→10, +regex
entries), BlockDomainsOptions (5→17, +Malware/Phishing/Adult/regex),
ServicesOptions (Reddit/Speedtest in, off-template Microsoft out).

Outbound form parity with main:
  • Reverse Sniffing UI for VLESS — toggle + destOverride checkboxes
    (HTTP/TLS/QUIC/FAKEDNS) + Metadata/Route Only + IPs/Domains
    excluded multi-selects, gated on reverseTag being set.
  • Full XHTTP transport — request headers list, Max Upload Size /
    Min Upload Interval (packet-up), Padding Obfs Mode + sub-fields,
    Uplink HTTP Method, Session/Sequence/UplinkData placement +
    keys, No gRPC Header (stream-up/stream-one), expanded XMUX with
    Max Concurrency/Connections/Reuse/Request/Reusable/Keep-alive.

Strip a-divider from the outbound form per request — replaced with
plain section/item heading divs so the labels and per-row delete
icons stay but the horizontal rule is gone.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): xray Advanced tab parity + finalmask gating

Advanced tab was a single textarea bound to the full xraySetting blob.
Restore the legacy 4-way view: a radio group toggles between All /
Inbounds / Outbounds / Routing Rules, and the textarea reads/writes
the matching slice through templateSettings. Added the legacy header
("Advanced Xray Configuration Template" + description) so the page
introduces itself like main.

Outbound finalmask leaked into protocols that don't have a stream
(Freedom / Blackhole / DNS / Socks / HTTP / Wireguard) because the
v-if only checked outbound.stream. Gate the whole FinalMaskForm on
outbound.canEnableStream() to match main.

Drop the leading divider inside FinalMaskForm — its parent already
provides separation, so the rule above "TCP Masks" was redundant.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): inbound Advanced tab live mirror + QR exact-fit sizing

Advanced tab in the inbound modal showed stale state. The watch only
refreshed advancedJson.stream, so toggling the Sniffing switch in the
Sniffing tab left the Advanced JSON showing the prior value. And
encryption — stored on inbound.settings.encryption, not on stream —
never appeared at all because Advanced only exposed stream + sniffing.

Split the watch into three (stream / sniffing / settings) and add a
settings textarea so encryption / clients / fallbacks live alongside
the existing two views. The submit() path now reads settings from
the JSON tab too (falling back to inbound.settings.toString()) so
power-user edits in Advanced override the structured form on save.

QR canvas: when a longer share-URL bumps the QR matrix size, QRious
falls back to floor(canvasSize / matrixWidth) and centers the pattern,
leaving a white margin (e.g. matrix=41, size=180 → 8px gap). Pre-pick
the QR version from the URL byte length and set canvas size to a
multiple of matrixWidth × pixelSize so the pattern always fills it
edge-to-edge — no white margin even after toggling encryption on.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): inbound stream tidy-up + QR sizing + dev proxy

Stream tab clean-up: drop the seven a-divider rules in the inbound
form's Stream tab — replace the labelled ones (Request / Response /
Security) with a section-heading div that matches the outbound modal,
delete the empty rules above TLS sub-blocks / External Proxy /
Sockopt. Empty header-list form-items also leaked margin space below
each "Add header" button across TCP / WS / HTTPUpgrade / XHTTP — gate
each on headers.length > 0 so they vanish until the user adds one.

QR panel: drop the link text under the canvas (the user already has
a copy button on the header). Pin the canvas display size to a fixed
240px square via :style + image-rendering: pixelated/crisp-edges so
a dense WireGuard config QR and its sparser link share the same
on-screen footprint without blurring.

Dev proxy: Node's AggregateError wraps connection failures whenever
DNS returns more than one address (::1 + 127.0.0.1) and the code
lands on the inner errors, not the outer. The existing handler only
checked err.code so the ECONNREFUSED stack still spammed the log
when the Go backend was down. Walk err.errors too, print one
friendly line ("backend not reachable — start the Go server"), then
stay quiet for the rest of the session.

Vendor splitting + chunk-size warning: split node_modules into
stable vendor-* chunks so each page only ships the deps it uses and
the browser caches them across versions. ant-design-vue stays as a
single chunk because its components share internals; raise the
chunk-size warning to 1500kB so the build stays quiet (its 1.4MB
minified gzips to ~410kB on the wire).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): info-modal cleanup + 2FA QR + outbound link import

- 2FA QR: matrix-snap canvas + opaque background to drop white margin
- Inbound info modal: stack Mixed/HTTP/Tunnel as info-rows, hide tab
  strip when only the Inbound tab applies
- Add inline VLESS Reverse tag input on first-client form
- Hide Protocol tab for TUN (no form yet)
- Outbound link converter: route through Outbound.fromLink so
  vless/trojan/ss/hysteria(2) imports work alongside vmess; fix stray
  implicit global in fromLink

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): jalali calendar + drop legacy moment-jalali

- Wire Calendar Type setting to a real Jalali datepicker via
  vue3-persian-datetime-picker, gated by useDatepicker composable
- DateTimePicker wrapper swaps between AD-Vue and Persian picker; keeps
  dayjs v-model contract so existing forms/setters work unchanged
- Theme picker popup explicitly per body.dark / data-theme=ultra-dark
  (AD-Vue 4 doesn't expose CSS vars, so var() fallbacks defaulted to
  white); fix invisible disabled days, SVG arrow fills, popup clipping
  via append-to="body"
- Replace stray moment() calls in dbinbound/inbound models with dayjs;
  the legacy global was undefined under ESM and broke the inbounds list
  whenever any inbound had expiryTime > 0
- Remove legacy moment-jalali / persian-datepicker / aPersianDatepicker
  assets — replaced by the Vue 3 picker

Note: dark/ultra background of the date popup still renders white in
some cases — pending follow-up.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): jalali popup theming + full-month layout

- Re-prefix popup selectors with .vpd-wrapper (popup root that travels
  with appendTo='body'), not .vpd-main (which stays at the input);
  paints the popup's dark/ultra background again
- Drop the 1px border on .vpd-content — with box-sizing: border-box
  it ate 2px from the day-row width, wrapping the 7th cell of every
  row and hiding days 18-31 of months that needed a 5th week

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat: render dates in Jalali when Calendar Type is jalalian

- IntlUtil.formatDate accepts an optional calendar arg; appends the
  BCP-47 -u-ca-persian extension so Intl renders Jalali across all UI
  languages, not just fa-IR
- Plumb the panel's datepicker setting into the SubPage via the Go
  injection (window.__SUB_PAGE_DATA__.datepicker)
- Panel pages (inbound list/info, client row, xray log) read the same
  setting through the useDatepicker composable so the whole panel
  stays consistent

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(frontend): ultra-dark page tint + mobile-friendly inbound view

- Drop --bg-page from #21242a (lighter than the cards) to #050505 in
  ultra-dark across index/sub/settings/inbounds/xray, so cards
  consistently elevate over the page
- Hide the inline sider's children + collapse-trigger and zero its
  width below 768px; the floating drawer-handle remains the menu
  trigger
- Inbounds page mobile pass: tighten content-area + card padding;
  flex-wrap the filter bar instead of stacking; shrink table cell
  padding so all 4 mobile columns fit; bump expand / action / info
  icon hit targets
- Per-client expand row on mobile: soft-tinted rounded cards instead
  of hairline borders, larger action / info touch targets, more
  legible email typography, bigger status badge dot

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore: remove legacy template + asset trees and dead Go template engine

- Delete web/html/ entirely (page templates, form/, modals/, component/,
  common/, settings/) — every route is served from web/dist/ now via
  serveDistPage; nothing in the binary referenced these
- Delete web/assets/ entirely (jQuery-era ant-design-vue, axios, moment,
  codemirror, qrcode/qs/uri/vue/otpauth, custom CSS, Vazirmatn font);
  Vite bundles all of this into web/dist/assets
- Drop the Gin HTML template wiring: remove //go:embed assets +
  //go:embed html/*, the assetsFS/htmlFS vars, the wrapAssetsFS adapter,
  EmbeddedHTML / EmbeddedAssets exports, getHtmlFiles / getHtmlTemplate,
  the i18nWebFunc/funcMap and SetFuncMap call, and the dev/prod
  template-engine branch — only StaticFS for /assets/ is needed now
- Remove dead html()/getContext() helpers and unused imports from
  web/controller/util.go (no c.HTML(...) callers remain)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(frontend): inbound expand chevron position + cpu history layout

- Push the inbound table's expand chevron away from the left edge with
  margin-inline + cell padding so it isn't flush against the corner
- Move "Timeframe: …" caption above the chart (was below); restore
  the line that the previous edit removed
- Fix x-axis time labels being clipped at the bottom of the cpu chart
  — the offset (paddingTop+drawHeight+22 = 222) exceeded the SVG
  viewBox height (220); dropped to +14 so labels sit at y=214 with
  room for descenders
- Move the SVG axis text colors out of <style scoped> into a global
  block — Vue's scoped CSS doesn't always hash-attribute SVG <text>
  descendants, so the dark-mode overrides via :global() weren't
  matching; bumped opacity 0.55 → 0.85 for legibility on navy/black

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(login): language picker in settings popover + fluid card sizing

- Add language select alongside the theme switch (mirrors SubPage)
- Bind headline to pages.login.hello / pages.login.title so the
  "Hello / Welcome" cycle re-translates with the active locale
- Replace AD-Vue 5-breakpoint grid with clamp() sizing so the card
  scales smoothly instead of jumping ~33% at each breakpoint
- Pin horizontal padding so input width stays stable on large viewports

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(frontend): organize entry HTML + bootstrap JS into folders

- Move entry HTML files: frontend/*.html -> frontend/html/*.html
- Move per-page bootstrap modules: src/{index,login,settings,inbounds,xray,subpage}.js -> src/entries/
- Update vite.config rollup inputs and dev-mode MIGRATED_ROUTES to /html/<page>.html
- Build output now lands at web/dist/html/<page>.html
- serveDistPage and subController updated to read from dist/html/

Cleans up the flat frontend/ root which previously interleaved 6 HTML
files with package.json, README, src/, etc. The src/ root similarly
gets rid of 6 entry .js files mixed in alongside api/, components/,
models/, etc.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* chore: remove obsolete vue3 phase1 inventory doc

The migration is well past phase 1 — the inventory doc has rotted
and the live state lives in the codebase plus the plan files.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(frontend): merge utils/legacy.js into utils/index.js

The barrel was a placeholder for an eventual split that hasn't
happened. Collapsing the two files removes one layer of indirection
and the misleading "legacy" name (the contents are still actively
used by the migrated SPA).

- Move all 930 lines from utils/legacy.js into utils/index.js
- Delete utils/legacy.js
- Update direct import in models/outbound.js to '@/utils'
- Drop a stale legacy.js reference in InboundFormModal comment

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* revert(frontend): keep entry HTML files at frontend/ root

The earlier move to frontend/html/ made dev-mode URLs ugly
(http://localhost:5173/html/index.html instead of plain /). The folder
didn't add real value — it just hid 6 files behind a non-conventional
layout. Reverting that piece while keeping src/entries/ (which is a
genuine separation between page bootstrap and the rest of src/).

- HTML files back at frontend/<page>.html
- Vite rollupOptions.input + MIGRATED_ROUTES restored to flat paths
- Build output is web/dist/<page>.html again
- web/controller/dist.go and sub/subController.go read from dist/<name>

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* build(frontend): bump eslint to 10 + add flat config + clean lint warnings

- Upgrade eslint 9.39 -> 10.3 and eslint-plugin-vue 9.33 -> 10.9
- Add eslint.config.js (flat config required by ESLint 10) with
  vue3-recommended rules, sensible defaults, and exemptions for the
  project's existing formatting style
- Drop --ext from the lint script (removed in ESLint 10)
- vue/no-mutating-props is left off because the form-modal pattern
  ports straight from Vue 2 (parent passes a reactive object, child
  mutates it); a real fix is an architectural rewire, separate task

Lint warning cleanup:
- utils/index.js: var -> let/const in the X25519 routines, replace
  obj.hasOwnProperty(...) with Object.prototype.hasOwnProperty.call(...)
- Remove unused imports (reactive, ref, Inbound) in ClientFormModal,
  InboundInfoModal, QrCodeModal, DnsServerModal, OutboundFormModal,
  SubPage; remove unused locals (isClientOnline, ONLINE_GRACE_MS,
  fetchAll, isSocks, isHTTP, _antdAlgorithm)
- XrayStatusCard: declare 'open-logs' on defineEmits (was emitted but
  not declared)
- RuleFormModal: rename v-for var t -> tag (shadowed useI18n's t)
- Drop stale eslint-disable directives (no-new, no-unused-vars)
- OutboundsTab/InboundList: drop redundant initial null assigns
- InboundInfoModal/OutboundFormModal: explicit eslint-disable for the
  intentional local-ref-shadows-prop pattern in modal drafts

`npm run lint` now passes with 0 errors and 0 warnings.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(inbounds): one client identity across multiple inbounds via subId

Lets the operator add the same email under the same subId to several
inbounds. Xray reports traffic per email, so a single client_traffics
row acts as the shared accumulator — no aggregation overhead, quota and
expiry stay consistent.

- Email validation allows duplicates only when subId matches
- AddClientStat upserts via OnConflict DoNothing (idempotent on rerun)
- Stat/IP rows survive client deletion when a sibling inbound still
  references the email
- enrichClientStats tops up GORM-preloaded stats with rows whose
  inbound_id points at a sibling, so every panel view sees usage
- disableInvalidClients cascades enable=false and syncs the row's
  total/expiry into every sibling JSON when the shared identity expires
- DelDepletedClients removes the depleted client from all referencing
  inbounds, batched
- Subscription services dedupe traffic by email so shared quota is
  counted once

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs(frontend): rewrite README for multi-page Vue 3 layout

Reflects the current state — embedded build, per-route HTML entries,
ESLint 10 flat config, src/ layout, and the steps to add a new page.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* build(frontend): drop deprecated rimraf/glob/inflight transitive deps

vue3-persian-datetime-picker pinned moment-jalaali to ^0.9.4, which
pulled rimraf@3 → glob@7 → inflight@1. inflight in particular leaks
memory and is unmaintained. Override moment-jalaali to ^0.10.4 (same
runtime API, dropped the legacy build deps) so npm install no longer
warns and the dep tree is 12 packages lighter.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(nodes): multi-node panel orchestration (CRUD, deployment, traffic sync, sub per-node)

- Node model + service + controller (/panel/api/nodes/*) with bearer-token apiToken auth
- Heartbeat job @every 10s; status/latency/xrayVersion surfaced in Nodes UI
- Runtime abstraction (Local + Remote) so inbound/client mutations target the
  inbound's owning node instead of always hitting the local xray
- Inbounds gain optional NodeID; tag-based correlation with remote panel (no
  RemoteInboundID column needed)
- NodeTrafficSyncJob @every 10s pulls absolute counters + online/lastOnline
  from each enabled+online node and writes them into central DB; 30s reset
  grace window prevents post-reset overwrite
- Reset propagation to nodes (best-effort) on client/inbound/all reset paths
- Subscription server uses node.Address for inbounds with NodeID, falling back
  to existing host resolution for local inbounds
- Frontend: Nodes page, "Deploy to" select in inbound form, Node column on
  inbound list, hostOverride threaded through genAllLinks/QR/Info modals

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(stats): system history modal + per-node CPU/Mem trends across all locales

Backend
- web/service/metric_history.go: generic in-memory ring buffer with two
  singletons — system-wide (cpu/mem/netUp/netDown/online/load1/5/15)
  and per-node (cpu/mem) keyed by node id
- ServerService.AppendStatusSample writes all 8 metrics every 2s on the
  same tick; AppendCpuSample/AggregateCpuHistory kept for back-compat
- NodeService.UpdateHeartbeat appends cpu/mem only on online ticks so
  offline gaps render as missing data, not phantom dips
- New routes: GET /panel/api/server/history/:metric/:bucket and
  GET /panel/api/nodes/history/:id/:metric/:bucket, both whitelisted

Frontend
- Sparkline component generalized: arbitrary value range (auto-scale
  when valueMax=null), pluggable yFormatter/tooltipFormatter for B/s,
  client counts, load averages
- SystemHistoryModal replaces CpuHistoryModal with tabs for every
  metric; opened from a tag on the 3X-UI card next to Documentation
- NodeHistoryPanel: expandable row on the Nodes table showing per-node
  CPU and Mem trends, refreshed every 15s

Localization
- Backfill systemHistoryTitle / trendLast2Min / pages.inbounds.{node,
  deployTo, localPanel} and the entire pages.nodes block (51 keys
  including statusValues + toasts) into all 11 non-en/fa locales:
  ar-EG, es-ES, id-ID, ja-JP, pt-BR, ru-RU, tr-TR, uk-UA, vi-VN,
  zh-CN, zh-TW

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(embed): include underscore-prefixed Vite chunks in dist FS

go:embed silently excludes files whose names start with `_` or `.`,
so the `_plugin-vue_export-helper-<hash>.js` chunk that Vite/rolldown
emits for @vitejs/plugin-vue was missing from the production binary.
First import at runtime hit a 404 and the SPA failed to mount — blank
page on every page load, no error in the server logs because the
asset 404 was just a static-handler miss.

Switched the directive to `//go:embed all:dist` which keeps the same
root layout but disables the underscore/dot exclusion rule. Dev mode
was unaffected (it serves dist/assets/ from disk, not the embedded FS).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* ci: build frontend bundle before Go compile in release.yml + Dockerfile

Phase 8 cut all panel HTML routes over to web/dist/ and embedded the
Vite bundle into the Go binary via //go:embed all:dist. web/dist/ is
.gitignored, so on a fresh CI checkout it doesn't exist — every Go
build since Phase 8 has been failing with "pattern dist: no matching
files found" or producing a binary that 404s on first asset request.

release.yml: add a setup-node@v4 + npm ci + npm run build trio before
the existing go build step in both the Linux matrix job (7 arches)
and the Windows job. npm cache is keyed on frontend/package-lock.json.

Dockerfile: add a node:22-alpine frontend stage that runs npm ci +
npm run build and emits to /src/web/dist (via vite.config.js's outDir).
The golang builder stage then COPY --from=frontend /src/web/dist into
./web/dist before the go build, so embed.FS sees the bundle.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(ws): live updates on inbounds/xray/nodes pages, drop polling + manual refresh

Replaces the legacy polling + manual-refresh model with WebSocket pushes
across the three live-data pages. The hub already broadcast traffic /
client_stats / outbounds; this wires the frontend to consume them and
adds a new `nodes` channel for the heartbeat job's snapshot.

Frontend
- new useWebSocket composable: page-scoped singleton WebSocketClient,
  lifecycle-managed on/off, leaves disconnect to page-unload
- inbounds: useInbounds gains applyTrafficEvent / applyClientStatsEvent
  / applyInvalidate that merge counters and online/lastOnline in place;
  InboundsPage subscribes; InboundList drops the auto-refresh popover,
  the refresh button, and the now-unused refreshing prop
- xray outbounds: useXraySetting gains applyOutboundsEvent; XrayPage
  subscribes; OutboundsTab drops the refresh button + emit
- nodes: useNodes gains applyNodesEvent and stops the 5s
  setInterval/visibilitychange polling; NodesPage subscribes;
  NodeList drops the refresh button and ReloadOutlined import

Backend
- web/websocket: new MessageTypeNodes + BroadcastNodes notifier
- node_heartbeat_job: after wg.Wait(), reload the table once and
  BroadcastNodes(updated). Gated on websocket.HasClients() so a panel
  with no open browser doesn't spend the DB read

Bug fixes spotted in this pass
- websocket.js #buildUrl defaulted basePath to '' when the global was
  missing (dev mode), producing `ws://host:portws` and a SyntaxError
  on the WebSocket constructor. Fall back to '/' and ensure leading
  slash.
- vite.config.js: forward /ws to ws://localhost:2053 with ws:true so
  dev (5173) reaches the Go backend's WebSocket
- NodeFormModal: a-input-password's visibilityToggle is Boolean in
  AntD Vue 4; the v3-era object form (`{ visible, 'onUpdate:visible' }`)
  triggered a Vue prop-type warning. Drop the override (default true
  shows the eye icon and toggles internally) and remove the orphaned
  tokenVisible ref

Translations
- pages.inbounds.autoRefresh / autoRefreshInterval: removed from all
  13 locales (UI gone)
- pages.nodes.refresh: removed from all 13 locales (UI gone)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(inbounds): hide Node column when no nodes are defined

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:47:35 +02:00
MHSanaei 12c10dbd98 feat(custom-geo): refresh index UI
Split the single ext-snippet column into Alias / URL / Routing /
Last-updated, with the alias surfaced next to a colored type tag,
the URL ellipsized with a tooltip + open-in-new-tab, and the
ext:file.dat:tag snippet click-to-copy via ClipboardManager.

Switch Last-updated to a relative time ("2 hours ago") with the
absolute timestamp on hover, add a friendly empty state, and show
a result toast when "Update All" finishes with partial failures.

customGeoEmpty translated for all 13 locales.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 10:09:33 +02:00
MHSanaei 2fd2cd0af1 fix(panel): silence update-check WARN spam when offline
The panel polls api.github.com on every page load. When the host has no
internet (DNS fails, GitHub blocked, etc.) jsonMsg's auto-WARN logging
floods the log with the same error every poll.

Bypass jsonMsg for getPanelUpdateInfo: log the error at Debug level and
return Success:false with the existing localized message so the frontend
popover behavior is unchanged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 09:51:05 +02:00
MHSanaei 37fb48ffff Axios v1.16.0 2026-05-08 09:41:56 +02:00
MHSanaei d8198f543b fix(warp): harden API client and frontend, bump to v0a4005
Backend:
- check HTTP status on every Cloudflare API call so error bodies don't
  get parsed as success
- replace unchecked type assertions with comma-ok form (no more panics
  when Cloudflare returns an error response)
- return real errors when license/id/token fields are missing instead
  of swallowing the failure
- guard SetWarpLicense against an empty errors array
- 15s timeout on the shared http.Client
- build all request bodies and persisted state with json.Marshal
- bump API path to v0a4005 and CF-Client-Version to a-6.30-3596 to
  match the current Cloudflare WARP client

Frontend (warp_modal.html):
- remove stray </a-form-item> closing tag
- declare config/peer with const and null-check before dereferencing
- guard addOutbound/resetOutbound against missing warpOutbound
- rename getResolved -> getReserved (the array it builds is "reserved")

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 09:29:42 +02:00
MHSanaei f2bc4938b7 Reality: remove tesla.com because of blocking
#4175
2026-05-08 00:59:09 +02:00
MHSanaei 7f703f927e fix(scripts): harden server-IP detection with multi-provider + manual fallback
Try six IPv4 providers in turn, accept only HTTP 200 + IPv4-shaped body,
and prompt the user to enter their IP if every provider fails.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 00:51:28 +02:00
MHSanaei f2c79b57fa Bump Go to 1.26.3
Raise module Go version to 1.26.3 and upgrade dependencies including github.com/valyala/fasthttp to v1.71.0 and google.golang.org/genproto/googleapis/rpc to a newer revision. go.sum was updated by module tooling to reflect these changes.
2026-05-08 00:19:05 +02:00
MHSanaei c394938f01 refactor(websocket): split controller into service + thin controller
Move per-connection lifecycle out of the controller and into a new
service.WebSocketService. The controller is now HTTP-layer only:
authenticate, validate origin, upgrade, and hand the connection off.

- web/service/websocket.go (new): owns the read/write pumps, hub
  registration, and connection lifetime. Pump constants are prefixed
  (wsWriteWait, wsPongWait, wsPingPeriod, wsClientReadLimit) to avoid
  collisions in the larger service package namespace.
- web/controller/websocket.go: trimmed to the upgrader, same-origin
  check, auth gate, and hand-off to the service.
- web/web.go: wires controller.NewWebSocketController(service.NewWebSocketService(hub)).

The hub package (web/websocket) stays as low-level fan-out
infrastructure. Behavior is unchanged — this is a structural cleanup
to align with the rest of the codebase's controller/service split.

Also includes a small range-int modernization in login_limiter_test.go
that gopls flagged.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 00:00:44 +02:00
MHSanaei b84b58ef21 fix(websocket): guard stale events and disconnect race in JS client
Two subtle race conditions in the browser WebSocket client:

1. Stale-event clobber. When connect() is called while the old socket is
   in CLOSING state, the readyState guard falls through and a new socket
   is assigned to this.ws. The old socket's queued close event then
   nulls out this.ws, silently breaking send() until the next reconnect.
   Same risk for delayed open/error/message handlers.

2. Reconnect-after-disconnect. clearTimeout() does not cancel a callback
   that has already fired but whose macrotask has not yet run. If
   disconnect() lands in that window, the queued reconnect callback
   still calls #openSocket() and resurrects the connection.

Every event handler now bails out if this.ws no longer points at the
socket that fired the event, and the reconnect timer callback re-checks
shouldReconnect before opening a new socket.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 00:00:10 +02:00
Farhad H. P. Shirvan 10ebc6cbdc Implement CSRF protection and security hardening across the application (#4179)
* Implement CSRF protection and security hardening across the application

- Added CSRF token handling in axios requests and HTML templates.
- Introduced CSRF middleware to validate tokens for unsafe HTTP methods.
- Implemented login limiter to prevent brute-force attacks.
- Enhanced security headers in middleware for improved response security.
- Updated login notification to include safe metadata without passwords.
- Added tests for CSRF middleware and login limiter functionality.

* fix
2026-05-07 23:36:11 +02:00
Harry NG a1b2382877 chore: fix shadowrocketUrl client (#4183) 2026-05-07 20:59:10 +02:00
MHSanaei 59c55dfc92 fix(panel-update): poll for restart, fix dark-mode version label
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 20:55:22 +02:00
MHSanaei 28a3dddb60 refactor(fallbacks): share template, tighter UX, cleaner JSON
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 20:27:34 +02:00
MHSanaei 39bf31bd56 fix(tun): use single mtu number per Xray spec
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 19:50:47 +02:00
MHSanaei 42b2ebc00b refactor(xhttp): split fields by direction, expand outbound coverage
Audit panel xhttp config against xray-core's runtime paths and split
fields per direction so each side carries only what it actually uses:

- Bidirectional (must match): host, path, mode, all xPadding*,
  session*/seq*, uplinkData*/Key, scMaxEachPostBytes
- Server-only (inbound): noSSEHeader, scMaxBufferedPosts,
  scStreamUpServerSecs, serverMaxHeaderBytes
- Client-only (outbound): uplinkHTTPMethod, uplinkChunkSize,
  noGRPCHeader, scMinPostsIntervalMs, xmux

The inbound previously held client-only fields and the outbound was
missing every must-match field beyond host/path/mode — meaning a
panel-built outbound couldn't connect to an inbound with a custom
xPaddingKey/sessionKey/etc.

Headers stay on the inbound for URL-share purposes only; xray's
listener ignores them at runtime, but they travel through the share
link's `extra` blob so the client picks them up.

Renames the URL helpers (applyXhttpPadding* -> applyXhttpExtra*) since
the blob now carries more than padding, and folds path/host/mode into
the helper so each link generator's xhttp branch is one line.

Adds two enforcement points for xray's "uplinkHTTPMethod=GET only in
packet-up" rule: the GET option is disabled when mode != packet-up,
and a watcher on the outbound modal auto-clears GET when the user
switches modes.

Hides the XMUX block behind an `enableXmux` switch on the outbound
form (mirrors the QUIC Params toggle) so the section doesn't clutter
the form by default; fromJson auto-flips it on for outbounds with
saved xmux config.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 19:26:40 +02:00
MHSanaei 3b64a62137 refactor(vless): drop selectedAuth, expose two explicit auth buttons
selectedAuth was UI-only metadata (Xray never reads it) and entirely
redundant with the encryption string itself — the dropdown only
controlled which block from `xray vlessenc` to apply. Replace it with
two explicit buttons ("X25519" and "ML-KEM-768") so the user picks
the auth mode in one click instead of dropdown + Get-New-Keys.

- VLESSSettings drops the field from constructor, fromJson, and toJson;
  legacy `selectedAuth` values still in DB will be silently shed on the
  next save.
- getNewVlessEnc(authLabel) now takes the label as a parameter; clear
  resets only decryption/encryption.
- Fallbacks visibility now keys on encryption === "none" (the same
  thing the dropdown was effectively gating on).
- Info modal drops the redundant Authentication tag and colours the
  encryption tag red when it's "none", green otherwise.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 15:08:06 +02:00
MHSanaei 79a7e7a5b5 fix(vless): scope testseed to xtls-rprx-vision flow
testseed is only meaningful for the exact xtls-rprx-vision flow, but the
panel was emitting it for any non-empty flow (including the UDP variant)
and keeping it on the inbound after the flow was cleared via the client
modal. Tighten the gate end-to-end:

- VLESSSettings.toJson (inbound + outbound) now only emits testseed when
  the flow is exactly xtls-rprx-vision and the array is 4 positive ints;
  default state is empty so unmodified inbounds omit the field entirely.
- canEnableVisionSeed drops the udp443 variant per spec.
- Form adds a tooltip + theme-aware help text and an inline error when
  the user partially fills the four inputs; submit is blocked in that
  state. Reset clears to empty (= use server defaults).
- UpdateInboundClient strips a now-orphaned testseed when the spliced
  client no longer leaves any XRV flow in the inbound.
- MigrationRequirements cleans up legacy rows where testseed lingered
  after flow changes or was saved for non-XRV flows by older versions.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 14:44:33 +02:00
MHSanaei 3349dcbc13 fix(fail2ban): fix banning regression and Docker zero-jail issue
- DockerEntrypoint.sh: create jail.d/filter.d/action.d config files
  before starting fail2ban so Docker containers no longer start with
  0 active jails (fixes #4134)

- x-ui.sh create_iplimit_jails: lower maxretry from 2 to 1 so
  fail2ban bans on the first log entry; with maxretry=2 and the
  partitionLiveIps logic the second occurrence could arrive after the
  32 s findtime window, silently preventing any ban (fixes #4163)

- x-ui.sh: fix datepattern (%%Y -> %Y) so fail2ban parses the Go
  log timestamp correctly instead of looking for a literal %%Y string

- x-ui.sh / DockerEntrypoint.sh: fix date command in actionban /
  actionunban echo (%%Y -> %Y) so the ban log records actual dates

- check_client_ip_job.go: replace log.SetOutput / log.SetFlags on
  the global standard-library logger with a local log.New instance,
  eliminating the dangling closed-file-handle between calls and
  stopping unrelated stdlib log output from polluting 3xipl.log

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-07 13:53:34 +02:00
MHSanaei ad30298700 Exclude virtual interfaces from network stats
Switch net.IOCounters to per-interface mode and aggregate traffic while excluding loopback and common virtual/tunnel interfaces. Adds isVirtualInterface helper to filter interfaces by exact names and prefixes (docker, veth, tun, wg, tailscale, etc.), sums BytesSent/BytesRecv across valid interfaces, and assigns the totals to status.NetTraffic. Removes the previous warning branch when no counters were found and preserves NetIO rate calculations using lastStatus.
2026-05-06 17:28:41 +02:00
MHSanaei 9be11e109e fix design 2026-05-06 17:12:08 +02:00
MHSanaei 7117d19fd1 fix: filter view in mobile 2026-05-06 14:45:46 +02:00
MHSanaei c88627a839 outbound: mobile style 2026-05-06 13:27:40 +02:00
MHSanaei c718e7ca5b fix(inbounds): remove stale reverse outbound tags after client deletion 2026-05-06 11:43:21 +02:00
pwnnex 6a483fa987 inbound: check transport in port conflict, allow tcp and udp on same port (#4169)
the panel rejected configurations like vless reality on tcp/443 and
hysteria2 on udp/443 even though those are independent sockets in
linux. the old checkPortExist looked only at port + listen.

inboundTransports now classifies each inbound by L4 transport:
hysteria/hysteria2/wireguard are udp; streamSettings.network=kcp is
udp; shadowsocks reads settings.network ("tcp"/"udp"/"tcp,udp");
mixed (socks/http) adds udp when settings.udp is true; everything
else is tcp. checkPortConflict pulls every row on the same port and
only flags a conflict when transport masks overlap. the listen-
overlap rule (specific addr vs any-addr on the same port) is kept.

inbounds.tag has a unique DB constraint and the controller derives
tags from port ("inbound-443"). without disambiguation a second
inbound on the same port would still hit a unique-constraint error.
generateInboundTag keeps the historical "inbound-<port>" shape when
the base tag is free, so existing routing rules survive the upgrade
unchanged, and appends "-tcp"/"-udp" only when the base is already
taken.

closes #4103.
2026-05-06 11:41:21 +02:00
MHSanaei 47163c1418 Skip 26.5.3 and bump Xray version cutoff
In GetXrayVersions, explicitly ignore the tag "26.5.3" and raise the minimum accepted Xray release from 26.3.10 to 26.4.25. This excludes a specific problematic release and updates the version parsing logic to only include >26 or 26.4.25+ releases.
2026-05-06 10:13:55 +02:00
MHSanaei 09f4f09b84 fix design 2026-05-06 10:06:56 +02:00
MHSanaei 3313086071 fix: Swap left/right classes for client table cells
Swap tr-table-rt and tr-table-lt on the size and totalGB elements in aClientTable.html so the size display and the total GB display are positioned correctly (size on the left, total on the right). This is a UI alignment fix with no functional logic changes.
2026-05-06 09:12:25 +02:00
MHSanaei 03d8ad4d5a Revert "Xray Core v26.5.3" buggy version(vless reverse doesn't work)
This reverts commit 74e97fec4c.
2026-05-06 08:52:36 +02:00
MHSanaei a8dff126c7 outbound: reverse Sniffing 2026-05-06 08:17:27 +02:00
MHSanaei 74e97fec4c Xray Core v26.5.3 2026-05-06 07:07:48 +02:00
MHSanaei 50603fd430 fix: get client reverse tag in the outbound 2026-05-06 00:50:40 +02:00
MHSanaei 8bea0fde2b v2.9.4 2026-05-05 21:31:24 +02:00
MHSanaei b2d32f588f new: vless reverse
legacy reverse removed
2026-05-05 21:00:03 +02:00
lolka1333 8177f6dc66 ws/inbounds: realtime fixes + perf for 10k+ client inbounds (#4123)
* ws/inbounds: realtime fixes + perf for 10k+ client inbounds

- hub: dedup, throttle, panic-restart, deadlock fix, race tests
- client: backoff cap + slow-retry instead of giving up
- broadcast: delta-only payload, count-based invalidate fallback
- filter: fix empty online list (Inbound has no .id, use dbInbound.toInbound)
- perf: O(N²)→O(N) traffic merge, bulk delete, /setEnable endpoint
- traffic: monotonic all_time + UI clamp + propagate in delta handler
- session: persist on update/logout (fixes logout-after-password-change)
- ui: protocol tags flex, traffic bar normalize

* Remove hub_test.go file

* fix: ws hub, inbound service, and frontend correctness

- propagate DelInbound error on disable path in SetInboundEnable
- skip empty emails in updateClientTraffics to avoid constraint violations
- use consistent IN ? clause, drop redundant ErrRecordNotFound guards
- Hub.Unregister: direct removeClient fallback when channel is full
- applyClientStatsDelta: O(1) email lookup via per-inbound Map cache
- WS payload size check: Blob.size instead of .length for real byte count

* fix: chunk large IN ? queries and fix IPv6 same-origin check

* fix: chunk large IN ? queries and fix IPv6 same-origin check

* fix: unify clientStats cache, throttle clarity, hub constants

* fix(ui): align traffic/expiry cell columns across all rows

* style(ui): redesign outbounds table for visual consistency

* style(ui): redesign routing table for visual consistency

* fix:

* fix:

* fix:

* fix:

* fix:

* fix: font

* refactor: simplify outbound tone functions for consistency and maintainability

---------

Co-authored-by: lolka1333 <test123@gmail.com>
2026-05-05 17:27:49 +02:00
MHSanaei 77d94b25d0 Add 'active' filter option to inbounds 2026-05-04 23:33:48 +02:00
MHSanaei 32b7ada549 subpage: enabled state
Track and surface a subscription's enabled state from backend to frontend so the UI can show inactive subscriptions and use it in active-state logic.

Changes:
- sub/subService.go: track hasEnabledClient, set traffic.Enable, add Enabled to PageData and populate it in BuildPageData.
- sub/subController.go: include enabled in the page context.
- web/html/settings/panel/subscription/subpage.html: emit data-enabled attribute and render an "inactive" tag when disabled.
- web/assets/js/subscription.js: read data-enabled and include it in isActive() checks.

This ensures subscriptions with no enabled clients are marked inactive in the UI and excluded from being considered active.
2026-05-04 23:27:57 +02:00
MHSanaei 6099a07ff0 feat: add configurable auto-restart on client auto-disable
Add a configurable option to restart Xray when clients are auto-disabled and persist disable actions.

Changes include:
- New setting restartXrayOnClientDisable (default true), getters/setters in SettingService, UI toggle in general settings, and translations for multiple locales.
- AddTraffic signature updated to return a third bool (clientsDisabled). disableInvalidClients now calls Xray API to remove users, marks client_traffics.enable=false, updates inbound.Settings JSON so clients appear disabled in stored settings, and returns appropriate counts/errors.
- XrayTrafficJob now checks the clientsDisabled flag and restarts Xray when the setting is enabled (with fallback to mark Xray as needing restart on failure).
- XrayService.GetXrayConfig call adjusted to ignore AddTraffic returns.
- Subscription generation (subService/subJson/subClash) no longer filters clients by their enable flag when matching subId.
- Minor fixes: check_client_ip_job now checks scanner.Err and improved API error handling/logging.

These changes ensure auto-disabled clients are propagated to Xray and the stored inbound settings, and provide an option to restart Xray automatically after auto-disable events.
2026-05-04 23:19:25 +02:00
MHSanaei e9806832ec reality: remove apple, icloud 2026-05-04 19:49:28 +02:00
MHSanaei 15ebf3df10 fix: client count for Hysteria
#4143
2026-05-04 17:49:53 +02:00
MHSanaei d44b70682c Update QUIC params defaults and UI validations
#4142
Adjust QUIC parameter defaults and tighten form validation across inbound/outbound components.

- Set default brutalUp/brutalDown to 65537 and only include them in JSON when congestion is 'brutal' or 'force-brutal'.
- Change keepAlivePeriod defaults (inbound QUIC -> 5s, Hysteria stream -> 2s) and enforce minimums in the UI.
- Expose and serialize additional QUIC fields in outbound QuicParams: init/max stream windows, init/max connection windows, maxIdleTimeout, disablePathMTUDiscovery, maxIncomingStreams.
- Add UI min/placeholder constraints: stream/connection receive windows min=16384 and updated placeholders to show defaults, brutal fields min=65537, maxIncomingStreams min=8 (placeholders updated), keepAlive min adjusted.
- Add Wireguard and Hysteria entries to Protocols.

Touched files: web/assets/js/model/inbound.js, web/assets/js/model/outbound.js, web/html/form/outbound.html, web/html/form/stream/stream_finalmask.html.
2026-05-04 17:42:55 +02:00
MHSanaei fb75e3d7c7 Check scanner error in GetXrayLogs
Add a check for scanner.Err() after scanning log lines and return nil if an error occurred. This prevents further processing of potentially incomplete or invalid log entries when the scanner encountered an error.
2026-05-04 17:02:00 +02:00
MHSanaei e9979b6774 API: Check client existence
#3706
2026-05-04 17:00:09 +02:00
MHSanaei 2b83dc047b Bump Go module dependency versions 2026-05-04 16:40:50 +02:00
MHSanaei c90f8a05bf fix(security): sanitize remote IP headers and escape log viewer output
#4135
2026-05-04 16:39:29 +02:00
MHSanaei 9f96ef83ec Freedom outbound: Add finalRules 2026-05-04 15:54:31 +02:00
MHSanaei e19061d513 TLS: Remove ECH Force Query 2026-05-04 13:20:24 +02:00
MHSanaei 51e2fb6dbf translate update
#4117
2026-04-28 19:17:11 +02:00
Farhad H. P. Shirvan f21ed92296 feat: add panel update functionality via web GUI (#4117)
* feat: add panel update functionality via web GUI

* feat: enhance panel update notifications in web GUI

* feat: implement panel update modal and enhance translation strings

* fix design
2026-04-28 18:46:55 +02:00
pwnnex 22de983752 xray-setting: pin api routing rule to index 0 on save (#4124)
when the admin adds a custom outbound (eg vless cascade to a second
server) and a routing rule sending all inbound traffic to it, that
catch-all gets evaluated before the existing api->api rule, so the
panel's internal stats inbound's traffic ends up on the cascade
outbound. the grpc stats query then can't see anything, GetTraffic
returns no inbound/user counters, and every client appears offline
with zero traffic even though the actual proxy path works fine.

before save, find the api rule and move it to the front of
routing.rules. if it's missing entirely, insert a default. other
rules keep their relative order.

closes #4113. probably also fixes the long-standing #2818 where the
documented workaround was "manually move the api rule to the top".
2026-04-28 17:49:39 +02:00
MHSanaei 0b5c239f98 v2.9.3 2026-04-27 15:31:32 +02:00
MHSanaei 03393c9f52 Minor changes 2026-04-27 15:02:43 +02:00
MHSanaei b56db67759 fix: handle Init error in GetXrayTraffic to prevent nil pointer panic
#3969
2026-04-27 14:11:28 +02:00
MHSanaei 6d05702d00 TCP Masks 2026-04-27 03:06:41 +02:00
MHSanaei 9791b05a4e kcp: noise, header-custom, sudoku 2026-04-27 01:28:06 +02:00
MHSanaei 0aca2d3b3d sub: kcp finalmask 2026-04-26 23:04:47 +02:00
MHSanaei 8529f4f0cf kcp: mtu and tti
Add KCP-specific fields mtu and tti to inbound stream handling in web/assets/js/model/inbound.js. The changes add obj.mtu/obj.tti when serializing the kcp stream and set params for mtu and tti in the various KCP parameter-building branches so these values are preserved and transmitted where KCP is used.
2026-04-26 21:32:50 +02:00
MHSanaei abc5cf3439 Increase KCP maxSendingWindow to 2MiB 2026-04-26 20:49:02 +02:00
MHSanaei a7e7788e29 Bump Xray release to v26.4.25 2026-04-26 20:45:00 +02:00
MHSanaei 8620344925 Replace with-block with explicit settings 2026-04-26 20:37:03 +02:00
MHSanaei 47e229e323 Default to dark theme when unset 2026-04-26 20:16:27 +02:00
MHSanaei 4521beab7c wireguard: link 2026-04-26 20:06:24 +02:00
MHSanaei a62c637632 DNS outbound: Add rules 2026-04-26 17:34:31 +02:00
dependabot[bot] 35609b7b13 Bump github.com/Azure/go-ntlmssp (#4094)
Bumps the go_modules group with 1 update in the / directory: [github.com/Azure/go-ntlmssp](https://github.com/Azure/go-ntlmssp).


Updates `github.com/Azure/go-ntlmssp` from 0.1.0 to 0.1.1
- [Release notes](https://github.com/Azure/go-ntlmssp/releases)
- [Commits](https://github.com/Azure/go-ntlmssp/compare/v0.1.0...v0.1.1)

---
updated-dependencies:
- dependency-name: github.com/Azure/go-ntlmssp
  dependency-version: 0.1.1
  dependency-type: indirect
  dependency-group: go_modules
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-24 10:41:11 +02:00
pwnnex a4b1b3d06d Merge pull request #4092 from pwnnex/fix/iplimit-live-only-slot-count
iplimit: dont count idle db-only ips toward the per-client limit (#4091)
2026-04-23 21:36:37 +03:00
pwnnex 5f7c7c5f3d iplimit: dont count idle db-only ips toward the per-client limit
after #4083 the staleness window is 30 minutes, which still lets an ip
that stopped connecting a few minutes ago sit in the db blob and keep
the protected slot on the ascending sort. the ip that is actually
connecting right now gets classified as excess and sent to fail2ban,
and never lands in inbound_client_ips.ips so the panel doesnt show it
until you clear the log by hand.

only count ips observed in the current scan toward the limit. db-only
entries stay in the blob for display but dont participate in the ban
decision. live subset still uses the "protect oldest, ban newcomer"
rule.

closes #4091. followup to #4077.
2026-04-23 21:11:45 +03:00
Rs.Nest 6bcaf61c44 Feature: Copy clients between inbounds (#4087)
* feat: copy clients between inbounds

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* fix: copy clients modal not opening

* revert: undo install.sh/deploy.sh changes; i18n: add copy-clients translations for all languages

---------

Co-authored-by: Нестеров Руслан <r.nesterov@comagic.dev>
2026-04-23 15:19:07 +02:00
MHSanaei ff25072690 SS: remove unsupported cipher method 2026-04-22 21:44:39 +02:00
pwnnex 530c1597b8 Merge pull request #4086 from pwnnex/fix/hysteria2-protocol-aliases
hysteria: accept "hysteria2" as a protocol string (#4081)
2026-04-22 16:02:05 +00:00
pwnnex c8e16d8c41 Merge pull request #4085 from pwnnex/fix/iplimit-install-nftables
x-ui.sh: bundle nftables when installing fail2ban
2026-04-22 15:58:00 +00:00
pwnnex 17f67ef3a5 sub: dont panic on bad externalProxy entry in genHysteriaLink
The externalProxy fanout from #4073 did `int(ep["port"].(float64))`
with no ok-check. If any entry is missing port or has the wrong
type it panics, and since this runs in the /sub/<id> handler the
whole subscription returns 500. Skip malformed entries instead.
2026-04-22 18:55:27 +03:00
pwnnex eb4791a1cd hysteria: also accept "hysteria2" protocol string
UI stores v1 and v2 both as "hysteria" with settings.version, but
inbounds that came in from imports / manual SQL can carry the
literal "hysteria2" string and get silently dropped everywhere we
switch on protocol.

Add Hysteria2 constant + IsHysteria helper, use it in the places
that gate on protocol (sub SQL, getLink, genHysteriaLink, clash
buildProxy, json gen, inbound.go validation, xray AddUser).

Existing "hysteria" inbounds are untouched.

closes #4081
2026-04-22 18:55:09 +03:00
pwnnex 71ac920436 x-ui.sh: install nftables alongside fail2ban in install_iplimit
On fresh Debian 12+, Ubuntu 24+ and recent RHEL-family minimal images
the fail2ban package ships with `banaction = nftables-multiport` as
the default in /etc/fail2ban/jail.conf but does not pull in the
`nftables` package as a dependency. The first SSH brute-force attempt
hits the default sshd jail and fail2ban logs

    stderr: /bin/sh: 1: nft: not found
    returned 127 -- HINT on 127: "Command not found"

repeatedly, which users mistake for a 3x-ui regression (see the
discussion on #4083). The 3x-ipl jail itself is unaffected — it uses
an iptables-based action configured in create_iplimit_jails — so this
is only stray noise, but noisy enough to look like a real failure on
first install.

Add `nftables` to the package list in every branch of install_iplimit
so new installs end up with a working default sshd jail out of the
box. Existing installs where `nftables` is already present are a
no-op.
2026-04-22 18:50:42 +03:00
pwnnex e6d0c33937 Merge pull request #4083 from pwnnex/fix/iplimit-stale-db-evict
Fix IP Limit continuous ban loop after a legitimate ban expires (#4077)
2026-04-22 14:09:55 +00:00
pwnnex eef2d311f4 Fix IP Limit continuous ban loop from stale DB entries (#4077)
After 60abeaa flipped the excess-IP selector to "oldest wins,
newest loses" (to protect the original/current connections), the
per-client IP table in `inbound_client_ips.ips` never evicted IPs
that stopped connecting. Their stored timestamp stayed ancient, so
on every subsequent run they counted as the "oldest protected"
slot(s) and whichever IP was actually using the config now was
classified as "new excess" and re-banned via fail2ban.

This is exactly the #4077 scenario: two IPs connect once and get
recorded, the ban lifts after the configured duration, the lone
legitimate IP that reconnects gets banned again, and again, and
again — a permanent 3xipl.log loop with no real abuser anywhere.

Fix: when merging the persisted `old` list with the freshly
observed `new` log lines, drop entries whose last-seen timestamp
is older than `ipStaleAfterSeconds` (30 minutes). A client that's
actually still active refreshes its timestamp any time xray emits
a new `accepted` line for a fresh TCP, so the cutoff is far above
even idle streaming sessions; a client that's genuinely gone falls
out of the table in bounded time and frees its slot.

Extracted the merge into `mergeClientIps` so it can be exercised
by unit tests without spinning up the full DB-backed job.

Tests cover:
- stale old entry is dropped (the #4077 regression)
- fresh old entries are still carried forward (access-log rotation
  is still backed by the persisted table)
- newer timestamp wins when the same IP appears in both lists
- a clock-skewed old `new` entry can't resurrect a stale IP
- a zero cutoff never over-evicts

Closes #4077
2026-04-22 16:53:32 +03:00
331 changed files with 47132 additions and 65993 deletions
+6 -3
View File
@@ -92,9 +92,12 @@ func (a *InboundController) getInbounds(c *gin.Context) {
- Use `config.GetLogLevel()`, `config.GetDBPath()` helpers
### Internationalization
- Translation files: `web/translation/translate.*.toml`
- Access via `I18nWeb(c, "pages.login.loginAgain")` in controllers
- Use `locale.I18nType` enum (Web, Api, etc.)
- Translation files: `web/translation/<lang>.json` (one nested-namespace file per locale,
e.g. `en-US.json`). Vue SPA imports these via `import.meta.glob` from `frontend/src/i18n/`,
and the Go binary embeds the same files via `web/web.go`'s `//go:embed translation/*`.
- Access from Go via `locale.I18n(locale.Web, "pages.login.loginAgain")` (see
`web/locale/locale.go`); access from Vue via `useI18n()` and `t('pages.login.loginAgain')`.
- Use `locale.I18nType` enum (Web, Bot).
## External Dependencies & Integration
+18
View File
@@ -35,6 +35,24 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v6
# The Go binary embeds web/dist/ via //go:embed all:dist (web/web.go).
# web/dist/ is .gitignored, so CodeQL's autobuild for Go will fail with
# "pattern all:dist: no matching files found" unless vite emits it first.
- name: Setup Node.js
if: matrix.language == 'go'
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Build frontend bundle
if: matrix.language == 'go'
run: |
npm ci
npm run build
working-directory: frontend
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
-2
View File
@@ -36,8 +36,6 @@ jobs:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
with:
install: true
- name: Login to Docker Hub
uses: docker/login-action@v4
+36 -41
View File
@@ -21,45 +21,7 @@ on:
pull_request:
jobs:
analyze:
name: Analyze Go code
permissions:
contents: read
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Set up Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
cache: true
- name: Check formatting
run: |
unformatted=$(gofmt -l .)
if [ -n "$unformatted" ]; then
echo "These files are not gofmt-formatted:"
echo "$unformatted"
exit 1
fi
- name: Run go vet
run: go vet ./...
- name: Run staticcheck
uses: dominikh/staticcheck-action@v1
with:
version: "latest"
install-go: false
- name: Run tests
run: go test -race -shuffle=on ./...
build:
needs: analyze
permissions:
contents: write
strategy:
@@ -83,6 +45,23 @@ jobs:
go-version-file: go.mod
check-latest: true
# Frontend dist must be built BEFORE go build — Go's //go:embed
# all:dist directive in web/web.go requires web/dist/ to exist
# at compile time. web/dist/ is .gitignored, so on a fresh CI
# checkout it doesn't exist until vite emits it.
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Build frontend bundle
run: |
npm ci
npm run build
working-directory: frontend
- name: Build 3X-UI
run: |
export CGO_ENABLED=1
@@ -126,7 +105,7 @@ jobs:
cd x-ui/bin
# Download dependencies
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.4.17/"
Xray_URL="https://github.com/XTLS/Xray-core/releases/download/v26.4.25/"
if [ "${{ matrix.platform }}" == "amd64" ]; then
wget -q ${Xray_URL}Xray-linux-64.zip
unzip Xray-linux-64.zip
@@ -191,7 +170,6 @@ jobs:
# =================================
build-windows:
name: Build for Windows
needs: analyze
permissions:
contents: write
strategy:
@@ -209,6 +187,23 @@ jobs:
go-version-file: go.mod
check-latest: true
# Frontend dist must be built BEFORE go build — see comment on the
# Linux job above. This step is identical except npm runs on the
# Windows runner here.
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '22'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Build frontend bundle
shell: pwsh
run: |
npm ci
npm run build
working-directory: frontend
- name: Install MSYS2
uses: msys2/setup-msys2@v2
with:
@@ -244,7 +239,7 @@ jobs:
cd x-ui\bin
# Download Xray for Windows
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.4.17/"
$Xray_URL = "https://github.com/XTLS/Xray-core/releases/download/v26.4.25/"
Invoke-WebRequest -Uri "${Xray_URL}Xray-windows-64.zip" -OutFile "Xray-windows-64.zip"
Expand-Archive -Path "Xray-windows-64.zip" -DestinationPath .
Remove-Item "Xray-windows-64.zip"
+3
View File
@@ -1,6 +1,7 @@
# Ignore editor and IDE settings
.idea/
.vscode/
.claude/
.cache/
.sync*
@@ -32,6 +33,8 @@ Thumbs.db
# Ignore Go build files
*.exe
x-ui.db
x-ui.db-shm
x-ui.db-wal
# Ignore Docker specific files
docker-compose.override.yml
+56 -2
View File
@@ -1,7 +1,61 @@
#!/bin/sh
# Start fail2ban
[ $XUI_ENABLE_FAIL2BAN == "true" ] && fail2ban-client -x start
# Start fail2ban with the 3x-ipl jail
if [ "$XUI_ENABLE_FAIL2BAN" = "true" ]; then
LOG_FOLDER="${XUI_LOG_FOLDER:-/var/log/x-ui}"
mkdir -p "$LOG_FOLDER"
touch "$LOG_FOLDER/3xipl.log" "$LOG_FOLDER/3xipl-banned.log"
mkdir -p /etc/fail2ban/jail.d /etc/fail2ban/filter.d /etc/fail2ban/action.d
cat > /etc/fail2ban/jail.d/3x-ipl.conf << EOF
[3x-ipl]
enabled=true
backend=auto
filter=3x-ipl
action=3x-ipl
logpath=$LOG_FOLDER/3xipl.log
maxretry=1
findtime=32
bantime=30m
EOF
cat > /etc/fail2ban/filter.d/3x-ipl.conf << 'EOF'
[Definition]
datepattern = ^%Y/%m/%d %H:%M:%S
failregex = \[LIMIT_IP\]\s*Email\s*=\s*<F-USER>.+</F-USER>\s*\|\|\s*Disconnecting OLD IP\s*=\s*<ADDR>\s*\|\|\s*Timestamp\s*=\s*\d+
ignoreregex =
EOF
cat > /etc/fail2ban/action.d/3x-ipl.conf << EOF
[INCLUDES]
before = iptables-allports.conf
[Definition]
actionstart = <iptables> -N f2b-<name>
<iptables> -A f2b-<name> -j <returntype>
<iptables> -I <chain> -p <protocol> -j f2b-<name>
actionstop = <iptables> -D <chain> -p <protocol> -j f2b-<name>
<actionflush>
<iptables> -X f2b-<name>
actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>
echo "\$(date +"%Y/%m/%d %H:%M:%S") BAN [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> $LOG_FOLDER/3xipl-banned.log
actionunban = <iptables> -D f2b-<name> -s <ip> -j <blocktype>
echo "\$(date +"%Y/%m/%d %H:%M:%S") UNBAN [Email] = <F-USER> [IP] = <ip> unbanned." >> $LOG_FOLDER/3xipl-banned.log
[Init]
name = default
protocol = tcp
chain = INPUT
EOF
fail2ban-client -x start
fi
# Run x-ui
exec /app/x-ui
+2 -2
View File
@@ -27,7 +27,7 @@ case $1 in
esac
mkdir -p build/bin
cd build/bin
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.4.17/Xray-linux-${ARCH}.zip"
curl -sfLRO "https://github.com/XTLS/Xray-core/releases/download/v26.4.25/Xray-linux-${ARCH}.zip"
unzip "Xray-linux-${ARCH}.zip"
rm -f "Xray-linux-${ARCH}.zip" geoip.dat geosite.dat
mv xray "xray-linux-${FNAME}"
@@ -37,4 +37,4 @@ curl -sfLRo geoip_IR.dat https://github.com/chocolate4u/Iran-v2ray-rules/release
curl -sfLRo geosite_IR.dat https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat
curl -sfLRo geoip_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat
curl -sfLRo geosite_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat
cd ../../
cd ../../
+13
View File
@@ -1,3 +1,14 @@
# ========================================================
# Stage: Frontend (Vite)
# ========================================================
FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend
WORKDIR /src/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
COPY web/translation /src/web/translation
RUN npm run build
# ========================================================
# Stage: Builder
# ========================================================
@@ -12,6 +23,7 @@ RUN apk --no-cache --update add \
unzip
COPY . .
COPY --from=frontend /src/web/dist ./web/dist
ENV CGO_ENABLED=1
ENV CGO_CFLAGS="-D_LARGEFILE64_SOURCE"
@@ -36,6 +48,7 @@ RUN apk add --no-cache --update \
COPY --from=builder /app/build/ /app/
COPY --from=builder /app/DockerEntrypoint.sh /app/
COPY --from=builder /app/x-ui.sh /usr/bin/x-ui
COPY --from=builder /app/web/translation /app/web/translation
# Configure fail2ban
+2 -2
View File
@@ -12,8 +12,8 @@
[![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
[![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
**3X-UI** — لوحة تحكم متقدمة مفتوحة المصدر تعتمد على الويب مصممة لإدارة خادم Xray-core. توفر واجهة سهلة الاستخدام لتكوين ومراقبة بروتوكولات VPN والوكيل المختلفة.
+2 -2
View File
@@ -12,8 +12,8 @@
[![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
[![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
**3X-UI** — panel de control avanzado basado en web de código abierto diseñado para gestionar el servidor Xray-core. Ofrece una interfaz fácil de usar para configurar y monitorear varios protocolos VPN y proxy.
+2 -2
View File
@@ -12,8 +12,8 @@
[![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
[![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
**3X-UI** — یک پنل کنترل پیشرفته مبتنی بر وب با کد باز که برای مدیریت سرور Xray-core طراحی شده است. این پنل یک رابط کاربری آسان برای پیکربندی و نظارت بر پروتکل‌های مختلف VPN و پراکسی ارائه می‌دهد.
+2 -2
View File
@@ -12,8 +12,8 @@
[![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
[![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
**3X-UI** — advanced, open-source web-based control panel designed for managing Xray-core server. It offers a user-friendly interface for configuring and monitoring various VPN and proxy protocols.
+2 -2
View File
@@ -12,8 +12,8 @@
[![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
[![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
**3X-UI** — продвинутая панель управления с открытым исходным кодом на основе веб-интерфейса, разработанная для управления сервером Xray-core. Предоставляет удобный интерфейс для настройки и мониторинга различных VPN и прокси-протоколов.
+2 -2
View File
@@ -12,8 +12,8 @@
[![GO Version](https://img.shields.io/github/go-mod/go-version/mhsanaei/3x-ui.svg)](#)
[![Downloads](https://img.shields.io/github/downloads/mhsanaei/3x-ui/total.svg)](https://github.com/MHSanaei/3x-ui/releases/latest)
[![License](https://img.shields.io/badge/license-GPL%20V3-blue.svg?longCache=true)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v2.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v2)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v2)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v2)
[![Go Reference](https://pkg.go.dev/badge/github.com/mhsanaei/3x-ui/v3.svg)](https://pkg.go.dev/github.com/mhsanaei/3x-ui/v3)
[![Go Report Card](https://goreportcard.com/badge/github.com/mhsanaei/3x-ui/v3)](https://goreportcard.com/report/github.com/mhsanaei/3x-ui/v3)
**3X-UI** — 一个基于网页的高级开源控制面板,专为管理 Xray-core 服务器而设计。它提供了用户友好的界面,用于配置和监控各种 VPN 和代理协议。
+1 -1
View File
@@ -1 +1 @@
2.9.2
3.0.0
+38 -10
View File
@@ -6,16 +6,16 @@ import (
"bytes"
"errors"
"io"
"io/fs"
"log"
"os"
"path"
"slices"
"time"
"github.com/mhsanaei/3x-ui/v2/config"
"github.com/mhsanaei/3x-ui/v2/database/model"
"github.com/mhsanaei/3x-ui/v2/util/crypto"
"github.com/mhsanaei/3x-ui/v2/xray"
"github.com/mhsanaei/3x-ui/v3/config"
"github.com/mhsanaei/3x-ui/v3/database/model"
"github.com/mhsanaei/3x-ui/v3/util/crypto"
"github.com/mhsanaei/3x-ui/v3/xray"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
@@ -39,6 +39,7 @@ func initModels() error {
&xray.ClientTraffic{},
&model.HistoryOfSeeders{},
&model.CustomGeoResource{},
&model.Node{},
}
for _, model := range models {
if err := db.AutoMigrate(model); err != nil {
@@ -88,11 +89,17 @@ func runSeeders(isUsersEmpty bool) error {
return db.Create(hashSeeder).Error
} else {
var seedersHistory []string
db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory)
if err := db.Model(&model.HistoryOfSeeders{}).Pluck("seeder_name", &seedersHistory).Error; err != nil {
log.Printf("Error fetching seeder history: %v", err)
return err
}
if !slices.Contains(seedersHistory, "UserPasswordHash") && !isUsersEmpty {
var users []model.User
db.Find(&users)
if err := db.Find(&users).Error; err != nil {
log.Printf("Error fetching users for password migration: %v", err)
return err
}
for _, user := range users {
hashedPassword, err := crypto.HashPasswordAsBcrypt(user.Password)
@@ -100,7 +107,10 @@ func runSeeders(isUsersEmpty bool) error {
log.Printf("Error hashing password for user '%s': %v", user.Username, err)
return err
}
db.Model(&user).Update("password", hashedPassword)
if err := db.Model(&user).Update("password", hashedPassword).Error; err != nil {
log.Printf("Error updating password for user '%s': %v", user.Username, err)
return err
}
}
hashSeeder := &model.HistoryOfSeeders{
@@ -123,7 +133,7 @@ func isTableEmpty(tableName string) (bool, error) {
// InitDB sets up the database connection, migrates models, and runs seeders.
func InitDB(dbPath string) error {
dir := path.Dir(dbPath)
err := os.MkdirAll(dir, fs.ModePerm)
err := os.MkdirAll(dir, 0755)
if err != nil {
return err
}
@@ -139,11 +149,29 @@ func InitDB(dbPath string) error {
c := &gorm.Config{
Logger: gormLogger,
}
db, err = gorm.Open(sqlite.Open(dbPath), c)
dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=10000&_synchronous=NORMAL&_txlock=immediate"
db, err = gorm.Open(sqlite.Open(dsn), c)
if err != nil {
return err
}
sqlDB, err := db.DB()
if err != nil {
return err
}
if _, err := sqlDB.Exec("PRAGMA journal_mode=WAL"); err != nil {
return err
}
if _, err := sqlDB.Exec("PRAGMA busy_timeout=10000"); err != nil {
return err
}
if _, err := sqlDB.Exec("PRAGMA synchronous=NORMAL"); err != nil {
return err
}
sqlDB.SetMaxOpenConns(8)
sqlDB.SetMaxIdleConns(4)
sqlDB.SetConnMaxLifetime(time.Hour)
if err := initModels(); err != nil {
return err
}
+73 -19
View File
@@ -4,8 +4,8 @@ package model
import (
"fmt"
"github.com/mhsanaei/3x-ui/v2/util/json_util"
"github.com/mhsanaei/3x-ui/v2/xray"
"github.com/mhsanaei/3x-ui/v3/util/json_util"
"github.com/mhsanaei/3x-ui/v3/xray"
)
// Protocol represents the protocol type for Xray inbounds.
@@ -21,9 +21,21 @@ const (
Shadowsocks Protocol = "shadowsocks"
Mixed Protocol = "mixed"
WireGuard Protocol = "wireguard"
Hysteria Protocol = "hysteria"
// UI stores Hysteria v1 and v2 both as "hysteria" and uses
// settings.version to discriminate. Imports from outside the panel
// can carry the literal "hysteria2" string, so IsHysteria below
// accepts both.
Hysteria Protocol = "hysteria"
Hysteria2 Protocol = "hysteria2"
)
// IsHysteria returns true for both "hysteria" and "hysteria2".
// Use instead of a bare ==model.Hysteria check: a v2 inbound stored
// with the literal v2 string would otherwise fall through (#4081).
func IsHysteria(p Protocol) bool {
return p == Hysteria || p == Hysteria2
}
// User represents a user account in the 3x-ui panel.
type User struct {
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
@@ -54,6 +66,12 @@ type Inbound struct {
StreamSettings string `json:"streamSettings" form:"streamSettings"`
Tag string `json:"tag" form:"tag" gorm:"unique"`
Sniffing string `json:"sniffing" form:"sniffing"`
// NodeID points at the remote panel (Node) where this inbound's xray
// actually runs. NULL means the inbound runs on the local xray (the
// pre-multi-node behaviour). Existing rows migrate to NULL with no
// backfill.
NodeID *int `json:"nodeId,omitempty" form:"nodeId" gorm:"index"`
}
// OutboundTraffics tracks traffic statistics for Xray outbound connections.
@@ -105,6 +123,37 @@ type Setting struct {
Value string `json:"value" form:"value"`
}
// Node represents a remote 3x-ui panel registered with the central panel.
// The central panel polls each node's existing /panel/api/server/status
// endpoint over HTTP using the per-node ApiToken to populate the runtime
// status fields below.
type Node struct {
Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"`
Name string `json:"name" form:"name" gorm:"uniqueIndex"`
Remark string `json:"remark" form:"remark"`
Scheme string `json:"scheme" form:"scheme"`
Address string `json:"address" form:"address"`
Port int `json:"port" form:"port"`
BasePath string `json:"basePath" form:"basePath"`
ApiToken string `json:"apiToken" form:"apiToken"`
Enable bool `json:"enable" form:"enable" gorm:"default:true"`
// Heartbeat-updated fields. UpdatedAt advances on every probe even when
// the row is otherwise unchanged so the UI's "last seen" tooltip is
// truthful without us having to read LastHeartbeat separately.
Status string `json:"status" gorm:"default:unknown"` // online|offline|unknown
LastHeartbeat int64 `json:"lastHeartbeat"` // unix seconds, 0 = never
LatencyMs int `json:"latencyMs"`
XrayVersion string `json:"xrayVersion"`
CpuPct float64 `json:"cpuPct"`
MemPct float64 `json:"memPct"`
UptimeSecs uint64 `json:"uptimeSecs"`
LastError string `json:"lastError"`
CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime"`
UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime"`
}
type CustomGeoResource struct {
Id int `json:"id" gorm:"primaryKey;autoIncrement"`
Type string `json:"type" gorm:"not null;uniqueIndex:idx_custom_geo_type_alias;column:geo_type"`
@@ -117,22 +166,27 @@ type CustomGeoResource struct {
UpdatedAt int64 `json:"updatedAt" gorm:"autoUpdateTime;column:updated_at"`
}
type ClientReverse struct {
Tag string `json:"tag"`
}
// Client represents a client configuration for Xray inbounds with traffic limits and settings.
type Client struct {
ID string `json:"id,omitempty"` // Unique client identifier
Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
Password string `json:"password,omitempty"` // Client password
Flow string `json:"flow,omitempty"` // Flow control (XTLS)
Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
Email string `json:"email"` // Client email identifier
LimitIP int `json:"limitIp"` // IP limit for this client
TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
SubID string `json:"subId" form:"subId"` // Subscription identifier
Comment string `json:"comment" form:"comment"` // Client comment
Reset int `json:"reset" form:"reset"` // Reset period in days
CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
ID string `json:"id,omitempty"` // Unique client identifier
Security string `json:"security"` // Security method (e.g., "auto", "aes-128-gcm")
Password string `json:"password,omitempty"` // Client password
Flow string `json:"flow,omitempty"` // Flow control (XTLS)
Reverse *ClientReverse `json:"reverse,omitempty"` // VLESS simple reverse proxy settings
Auth string `json:"auth,omitempty"` // Auth password (Hysteria)
Email string `json:"email"` // Client email identifier
LimitIP int `json:"limitIp"` // IP limit for this client
TotalGB int64 `json:"totalGB" form:"totalGB"` // Total traffic limit in GB
ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` // Expiration timestamp
Enable bool `json:"enable" form:"enable"` // Whether the client is enabled
TgID int64 `json:"tgId" form:"tgId"` // Telegram user ID for notifications
SubID string `json:"subId" form:"subId"` // Subscription identifier
Comment string `json:"comment" form:"comment"` // Client comment
Reset int `json:"reset" form:"reset"` // Reset period in days
CreatedAt int64 `json:"created_at,omitempty"` // Creation timestamp
UpdatedAt int64 `json:"updated_at,omitempty"` // Last update timestamp
}
+22
View File
@@ -0,0 +1,22 @@
package model
import "testing"
func TestIsHysteria(t *testing.T) {
cases := []struct {
in Protocol
want bool
}{
{Hysteria, true},
{Hysteria2, true},
{VLESS, false},
{Shadowsocks, false},
{Protocol(""), false},
{Protocol("hysteria3"), false},
}
for _, c := range cases {
if got := IsHysteria(c.in); got != c.want {
t.Errorf("IsHysteria(%q) = %v, want %v", c.in, got, c.want)
}
}
}
+3
View File
@@ -0,0 +1,3 @@
node_modules/
.vite/
*.log
+75
View File
@@ -0,0 +1,75 @@
# 3x-ui frontend
Vue 3 + Ant Design Vue 4 + Vite. Multi-page app — one HTML entry per
panel route — built into `../web/dist/` and embedded into the Go binary
via `embed.FS`.
## Dev
```sh
npm install
npm run dev
```
Vite serves on `http://localhost:5173/`. API calls and `/panel/*` routes
proxy to the Go panel at `http://localhost:2053/`, so start the Go panel
first (`go run main.go`) and then Vite.
The proxy auto-rewrites `/panel`, `/panel/settings`, `/panel/inbounds`,
`/panel/xray` to the matching Vite-served HTML in dev mode (see
`MIGRATED_ROUTES` in `vite.config.js`), so the sidebar's
production-style links work without round-tripping through Go.
## Production build
```sh
npm run build
```
Outputs to `../web/dist/` (HTML at the root, hashed JS/CSS under
`assets/`). The Go binary embeds this directory at compile time and
`web/controller/dist.go` serves the per-page HTML.
## Lint
```sh
npm run lint
```
ESLint 10 with `eslint.config.js` (flat config) — `vue3-recommended`
plus a few rule overrides for the project's formatting style.
## Layout
```
frontend/
├── *.html # Vite entry HTML, one per panel route
├── eslint.config.js
├── vite.config.js
└── src/
├── entries/ # Per-page bootstrap (createApp + mount)
├── pages/ # One folder per route, each with the page
│ ├── index/ # component + helpers + sub-components
│ ├── login/
│ ├── inbounds/
│ ├── xray/
│ ├── settings/
│ └── sub/
├── components/ # Cross-page Vue components
├── composables/ # Reusable reactive logic (useTheme, …)
├── api/ # Axios setup, CSRF interceptor
├── i18n/ # vue-i18n init (locales live in web/translation/)
├── models/ # Inbound, Outbound, Status, … domain classes
└── utils/ # HttpUtil, ObjectUtil, LanguageManager, …
```
## Adding a new page
1. Add `frontend/<page>.html` referencing `/src/entries/<page>.js`.
2. Add `src/entries/<page>.js` that imports the page component and
mounts it.
3. Add the page component under `src/pages/<page>/`.
4. Register the entry in `rollupOptions.input` in `vite.config.js`.
5. If the page is reachable from the sidebar at `/panel/<route>`, add
it to `MIGRATED_ROUTES` so the dev proxy serves the Vite HTML.
6. Wire the Go controller to `serveDistPage(c, "<page>.html")`.
+61
View File
@@ -0,0 +1,61 @@
import js from '@eslint/js';
import vue from 'eslint-plugin-vue';
import vueParser from 'vue-eslint-parser';
import globals from 'globals';
export default [
{ ignores: ['node_modules/**', '../web/dist/**'] },
js.configs.recommended,
...vue.configs['flat/recommended'],
{
files: ['**/*.{js,vue}'],
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
parser: vueParser,
parserOptions: {
ecmaFeatures: { jsx: false },
},
globals: {
...globals.browser,
...globals.node,
// Legacy script tags inject a couple of helpers on window before
// the SPA boots; declared here so no-undef stops flagging them.
getRandomRealityTarget: 'readonly',
},
},
rules: {
'no-unused-vars': ['warn', {
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
}],
'no-empty': ['error', { allowEmptyCatch: true }],
'no-case-declarations': 'off',
// Stylistic rules from vue/recommended that don't match the
// existing codebase formatting. Disable rather than churn the
// whole tree to satisfy them.
'vue/multi-word-component-names': 'off',
'vue/no-v-html': 'off',
'vue/html-self-closing': 'off',
'vue/max-attributes-per-line': 'off',
'vue/singleline-html-element-content-newline': 'off',
'vue/multiline-html-element-content-newline': 'off',
'vue/html-indent': 'off',
'vue/html-closing-bracket-newline': 'off',
'vue/attributes-order': 'off',
'vue/first-attribute-linebreak': 'off',
'vue/one-component-per-file': 'off',
'vue/order-in-components': 'off',
'vue/attribute-hyphenation': 'off',
'vue/v-on-event-hyphenation': 'off',
// Pervasive in form components ported from the Vue 2 codebase
// (parent passes a reactive object; child mutates it in place).
// Properly fixing this means rewiring those components to emit
// updates — a meaningful architectural change, separate task.
'vue/no-mutating-props': 'off',
},
},
];
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3x-ui · Inbounds</title>
</head>
<body>
<div id="message"></div>
<div id="app"></div>
<script type="module" src="/src/entries/inbounds.js"></script>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3x-ui</title>
</head>
<body>
<div id="message"></div>
<div id="app"></div>
<script type="module" src="/src/entries/index.js"></script>
</body>
</html>
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="robots" content="noindex,nofollow" />
<title>3x-ui — Sign in</title>
</head>
<body>
<div id="message"></div>
<div id="app"></div>
<script type="module" src="/src/entries/login.js"></script>
</body>
</html>
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3x-ui · Nodes</title>
</head>
<body>
<div id="message"></div>
<div id="app"></div>
<script type="module" src="/src/entries/nodes.js"></script>
</body>
</html>
+2785
View File
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "3x-ui-frontend",
"private": true,
"version": "0.0.1",
"type": "module",
"description": "3x-ui panel frontend (Vue 3 + Ant Design Vue 4 + Vite 8).",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"lint": "eslint src"
},
"dependencies": {
"@ant-design/icons-vue": "^7.0.1",
"ant-design-vue": "^4.2.6",
"axios": "^1.7.9",
"dayjs": "^1.11.20",
"moment": "^2.30.1",
"otpauth": "^9.5.1",
"qrious": "^4.0.2",
"qs": "^6.13.1",
"vue": "^3.5.13",
"vue-i18n": "^11.1.4",
"vue3-persian-datetime-picker": "^1.2.2"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@vitejs/plugin-vue": "^6.0.6",
"eslint": "^10.3.0",
"eslint-plugin-vue": "^10.9.1",
"globals": "^17.6.0",
"vite": "^8.0.11",
"vue-eslint-parser": "^10.4.0"
},
"overrides": {
"moment-jalaali": "^0.10.4"
}
}
+13
View File
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3x-ui · Settings</title>
</head>
<body>
<div id="message"></div>
<div id="app"></div>
<script type="module" src="/src/entries/settings.js"></script>
</body>
</html>
+126
View File
@@ -0,0 +1,126 @@
import axios from 'axios';
import qs from 'qs';
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
// Public CSRF endpoint — works pre-login (the panel-scoped
// /panel/csrf-token sits behind checkLogin and would 401 a fresh
// login page that hasn't authenticated yet).
const CSRF_TOKEN_PATH = '/csrf-token';
// Cached session CSRF token. The legacy panel injects it via a
// <meta name="csrf-token"> tag rendered by Go; the new SPA pages
// fetch it once from /panel/csrf-token instead. Module-level so
// every axios POST sees the latest value.
let csrfToken = null;
let csrfFetchPromise = null;
function readMetaToken() {
return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || null;
}
// Fetch the token via a bare fetch() (not axios) so the call doesn't
// recurse through this same interceptor.
async function fetchCsrfToken() {
try {
const basePath = window.__X_UI_BASE_PATH__;
const url = (typeof basePath === 'string' && basePath !== '' && basePath !== '/'
? basePath.replace(/\/$/, '') + CSRF_TOKEN_PATH
: CSRF_TOKEN_PATH);
const res = await fetch(url, {
method: 'GET',
credentials: 'same-origin',
headers: { 'X-Requested-With': 'XMLHttpRequest' },
});
if (!res.ok) return null;
const json = await res.json();
return json?.success && typeof json.obj === 'string' ? json.obj : null;
} catch (_e) {
return null;
}
}
async function ensureCsrfToken() {
if (csrfToken) return csrfToken;
const meta = readMetaToken();
if (meta) {
csrfToken = meta;
return csrfToken;
}
if (!csrfFetchPromise) csrfFetchPromise = fetchCsrfToken();
const fetched = await csrfFetchPromise;
csrfFetchPromise = null;
if (fetched) csrfToken = fetched;
return csrfToken;
}
// Apply the panel's axios defaults + interceptors. Call once at app
// startup before any HTTP call goes out.
export function setupAxios() {
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
const basePath = window.__X_UI_BASE_PATH__;
if (typeof basePath === 'string' && basePath !== '' && basePath !== '/') {
axios.defaults.baseURL = basePath;
}
// Seed the cache from the meta tag if a server-rendered page injected
// one — saves a round trip on legacy templates that still embed it.
csrfToken = readMetaToken();
axios.interceptors.request.use(
async (config) => {
config.headers = config.headers || {};
const method = (config.method || 'get').toUpperCase();
if (!SAFE_METHODS.has(method)) {
const token = await ensureCsrfToken();
if (token) config.headers['X-CSRF-Token'] = token;
}
if (config.data instanceof FormData) {
config.headers['Content-Type'] = 'multipart/form-data';
} else {
config.data = qs.stringify(config.data, { arrayFormat: 'repeat' });
}
return config;
},
(error) => Promise.reject(error),
);
axios.interceptors.response.use(
(response) => response,
async (error) => {
const status = error.response?.status;
if (status === 401) {
// 401 → session is gone. In production, the panel routes
// are gated by Go's checkLogin which redirects to base_path
// serving the login page; a reload is enough. In dev, Vite
// serves /index.html directly at "/", so a reload would put
// the user right back on the dashboard and the interceptor
// would loop. Navigate to the dev login entry instead.
if (import.meta.env.DEV) {
const basePath = window.__X_UI_BASE_PATH__ || '/';
window.location.href = `${basePath}login.html`;
} else {
window.location.reload();
}
return Promise.reject(error);
}
// 403 with a stale/missing CSRF token: drop the cache, re-fetch, retry once.
const cfg = error.config;
if (status === 403 && cfg && !cfg.__csrfRetried) {
csrfToken = null;
cfg.__csrfRetried = true;
const token = await ensureCsrfToken();
if (token) {
cfg.headers = cfg.headers || {};
cfg.headers['X-CSRF-Token'] = token;
// axios re-stringifies on retry, so unwind our qs.stringify before
// letting the same request flow through the interceptor again.
if (typeof cfg.data === 'string') cfg.data = qs.parse(cfg.data);
return axios(cfg);
}
}
return Promise.reject(error);
},
);
}
+231
View File
@@ -0,0 +1,231 @@
/**
* WebSocket client for real-time panel updates.
*
* Public API (kept stable for index.html / inbounds.html / xray.html):
* - connect() — open the connection (idempotent)
* - disconnect() — close and stop reconnecting
* - on(event, callback) — subscribe to event
* - off(event, callback) — unsubscribe
* - send(data) — send JSON to the server
* - isConnected — boolean, current state
* - reconnectAttempts — number, attempts since last success
* - maxReconnectAttempts — number, give-up threshold
*
* Built-in events:
* 'connected', 'disconnected', 'error', 'message',
* plus any server-emitted message type (status, traffic, client_stats, ...).
*/
export class WebSocketClient {
static #MAX_PAYLOAD_BYTES = 10 * 1024 * 1024; // 10 MB, mirrors hub maxMessageSize.
static #BASE_RECONNECT_MS = 1000;
static #MAX_RECONNECT_MS = 30_000;
// After exhausting maxReconnectAttempts we switch to a polite slow-retry
// cadence rather than giving up forever — a panel that recovers an hour
// later should reconnect without a manual page reload.
static #SLOW_RETRY_MS = 60_000;
constructor(basePath = '') {
this.basePath = basePath;
this.maxReconnectAttempts = 10;
this.reconnectAttempts = 0;
this.isConnected = false;
this.ws = null;
this.shouldReconnect = true;
this.reconnectTimer = null;
this.listeners = new Map(); // event → Set<callback>
}
// Open the connection. Safe to call repeatedly — no-op if already
// open/connecting. Re-enables reconnects if previously disabled. Cancels
// any pending reconnect timer so an external connect() can't race a
// delayed retry into spawning a second socket.
connect() {
if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) {
return;
}
this.shouldReconnect = true;
this.#cancelReconnect();
this.#openSocket();
}
// Close the connection and stop any pending reconnect attempt. Resets the
// attempt counter so a future connect() starts fresh from the small backoff.
disconnect() {
this.shouldReconnect = false;
this.#cancelReconnect();
this.reconnectAttempts = 0;
if (this.ws) {
try { this.ws.close(1000, 'client disconnect'); } catch { /* ignore */ }
this.ws = null;
}
this.isConnected = false;
}
// Subscribe to an event. Re-subscribing the same callback is a no-op.
on(event, callback) {
if (typeof callback !== 'function') return;
let set = this.listeners.get(event);
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
set.add(callback);
}
// Unsubscribe from an event.
off(event, callback) {
const set = this.listeners.get(event);
if (!set) return;
set.delete(callback);
if (set.size === 0) this.listeners.delete(event);
}
// Send JSON to the server. Drops silently if not connected — callers
// should rely on connect()/server pushes rather than client-initiated sends.
send(data) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
// ───── internals ─────
#openSocket() {
const url = this.#buildUrl();
let socket;
try {
socket = new WebSocket(url);
} catch (err) {
console.error('WebSocket: failed to construct connection', err);
this.#emit('error', err);
this.#scheduleReconnect();
return;
}
this.ws = socket;
// Every handler must check `this.ws !== socket` first. A previous socket
// can still fire events (especially `close`) after we've moved on to a
// new one — e.g. connect() called while the old socket is in CLOSING
// state. Without the guard, a stale close would null out the freshly
// opened socket and silently break send().
socket.addEventListener('open', () => {
if (this.ws !== socket) return;
this.isConnected = true;
this.reconnectAttempts = 0;
this.#emit('connected');
});
socket.addEventListener('message', (event) => {
if (this.ws !== socket) return;
this.#onMessage(event);
});
socket.addEventListener('error', (event) => {
if (this.ws !== socket) return;
// Browsers fire 'error' before 'close' on failure. We surface it for
// consumers (so polling fallbacks can engage) but don't log every blip
// — bad networks would flood the console otherwise.
this.#emit('error', event);
});
socket.addEventListener('close', () => {
if (this.ws !== socket) return;
this.isConnected = false;
this.ws = null;
this.#emit('disconnected');
if (this.shouldReconnect) this.#scheduleReconnect();
});
}
#buildUrl() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
// basePath comes from window.__X_UI_BASE_PATH__ which is only injected
// by the Go binary in production. In dev (Vite serves directly) the
// global is missing and basePath would be '' — without the fallback to
// '/' we'd build `ws://host:portws` (no separator) and the WebSocket
// constructor throws a SyntaxError.
let basePath = this.basePath || '/';
if (!basePath.startsWith('/')) basePath = '/' + basePath;
if (!basePath.endsWith('/')) basePath += '/';
return `${protocol}//${window.location.host}${basePath}ws`;
}
#onMessage(event) {
const data = event.data;
// Reject oversized payloads up front. We compare actual UTF-8 byte
// length (via Blob.size) against the limit — string.length counts
// UTF-16 code units, which can undercount real bytes by up to 4× for
// payloads with non-ASCII characters and bypass the cap.
if (typeof data === 'string') {
const byteLen = new Blob([data]).size;
if (byteLen > WebSocketClient.#MAX_PAYLOAD_BYTES) {
console.error(`WebSocket: payload too large (${byteLen} bytes), closing`);
try { this.ws?.close(1009, 'message too big'); } catch { /* ignore */ }
return;
}
}
let message;
try {
message = JSON.parse(data);
} catch (err) {
console.error('WebSocket: invalid JSON message', err);
return;
}
if (!message || typeof message !== 'object' || typeof message.type !== 'string') {
console.error('WebSocket: malformed message envelope');
return;
}
this.#emit(message.type, message.payload, message.time);
this.#emit('message', message);
}
#emit(event, ...args) {
const set = this.listeners.get(event);
if (!set) return;
for (const callback of set) {
try {
callback(...args);
} catch (err) {
console.error(`WebSocket: handler for "${event}" threw`, err);
}
}
}
#scheduleReconnect() {
if (!this.shouldReconnect) return;
this.#cancelReconnect();
let base;
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts += 1;
// Exponential backoff inside the active window.
const exp = WebSocketClient.#BASE_RECONNECT_MS * 2 ** (this.reconnectAttempts - 1);
base = Math.min(WebSocketClient.#MAX_RECONNECT_MS, exp);
} else {
// Active window exhausted — keep trying once a minute. The page-level
// polling fallback runs in parallel; this just brings WS back when the
// network recovers.
base = WebSocketClient.#SLOW_RETRY_MS;
}
// ±25% jitter so reloads after a panel restart don't reconnect in lockstep.
const delay = base * (0.75 + Math.random() * 0.5);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
// clearTimeout doesn't cancel a callback that has already fired but
// whose macrotask hasn't run yet — re-check shouldReconnect here so
// disconnect() called in that window can't be overridden.
if (!this.shouldReconnect) return;
this.#openSocket();
}, delay);
}
#cancelReconnect() {
if (this.reconnectTimer !== null) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
}
}
+163
View File
@@ -0,0 +1,163 @@
<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
DashboardOutlined,
UserOutlined,
SettingOutlined,
ToolOutlined,
ClusterOutlined,
LogoutOutlined,
CloseOutlined,
MenuFoldOutlined,
} from '@ant-design/icons-vue';
import { currentTheme } from '@/composables/useTheme.js';
import ThemeSwitch from '@/components/ThemeSwitch.vue';
const { t } = useI18n();
const SIDEBAR_COLLAPSED_KEY = 'isSidebarCollapsed';
const props = defineProps({
// Path prefix (e.g. /custom-base/) the panel is served under. Defaults
// to '' which means tab keys end up as '/panel/...'. Pages pass the
// value the Go backend gave them (in production via a meta tag).
basePath: { type: String, default: '' },
// Current request URI so the matching menu item highlights.
requestUri: { type: String, default: '' },
});
// AD-Vue 4 dropped <a-icon :type="x"> in favor of explicit icon
// imports — keep a small name-to-component map so tab definitions stay
// declarative.
const iconByName = {
dashboard: DashboardOutlined,
user: UserOutlined,
setting: SettingOutlined,
tool: ToolOutlined,
cluster: ClusterOutlined,
logout: LogoutOutlined,
};
// basePath comes from Go (`/` by default, `/myprefix/` when configured) so
// these concatenations land on absolute paths. In dev we synthesize the prop
// from a window global which can be empty — force a leading slash so the
// browser doesn't resolve the link relative to the current pathname (which
// would turn /panel/settings + 'panel/...' into /panel/panel/...).
const prefix = props.basePath?.startsWith('/') ? props.basePath : `/${props.basePath || ''}`;
// Labels are i18n-driven so the sidebar matches the locale picked
// in panel settings without a page reload of the sidebar component.
const tabs = computed(() => [
{ key: `${prefix}panel/`, icon: 'dashboard', title: t('menu.dashboard') },
{ key: `${prefix}panel/inbounds`, icon: 'user', title: t('menu.inbounds') },
{ key: `${prefix}panel/nodes`, icon: 'cluster', title: t('menu.nodes') },
{ key: `${prefix}panel/settings`, icon: 'setting', title: t('menu.settings') },
{ key: `${prefix}panel/xray`, icon: 'tool', title: t('menu.xray') },
{ key: `${prefix}logout`, icon: 'logout', title: t('logout') },
]);
const activeTab = ref([props.requestUri]);
const drawerOpen = ref(false);
const collapsed = ref(JSON.parse(localStorage.getItem(SIDEBAR_COLLAPSED_KEY) || 'false'));
function openLink(key) {
if (key.startsWith('http')) {
window.open(key);
} else {
window.location.href = key;
}
}
function onCollapse(isCollapsed, type) {
// Only persist explicit toggle clicks, not breakpoint-triggered collapses.
if (type === 'clickTrigger') {
localStorage.setItem(SIDEBAR_COLLAPSED_KEY, isCollapsed);
collapsed.value = isCollapsed;
}
}
function toggleDrawer() {
drawerOpen.value = !drawerOpen.value;
}
function closeDrawer() {
drawerOpen.value = false;
}
</script>
<template>
<div class="ant-sidebar">
<a-layout-sider :theme="currentTheme" collapsible :collapsed="collapsed" breakpoint="md" @collapse="onCollapse">
<ThemeSwitch />
<a-menu :theme="currentTheme" mode="inline" :selected-keys="activeTab" @click="({ key }) => openLink(key)">
<a-menu-item v-for="tab in tabs" :key="tab.key">
<component :is="iconByName[tab.icon]" />
<span>{{ tab.title }}</span>
</a-menu-item>
</a-menu>
</a-layout-sider>
<a-drawer placement="left" :closable="false" :open="drawerOpen" :wrap-class-name="currentTheme"
:wrap-style="{ padding: 0 }" :style="{ height: '100%' }" @close="closeDrawer">
<ThemeSwitch />
<a-menu :theme="currentTheme" mode="inline" :selected-keys="activeTab" @click="({ key }) => openLink(key)">
<a-menu-item v-for="tab in tabs" :key="tab.key">
<component :is="iconByName[tab.icon]" />
<span>{{ tab.title }}</span>
</a-menu-item>
</a-menu>
</a-drawer>
<button class="drawer-handle" type="button" @click="toggleDrawer">
<CloseOutlined v-if="drawerOpen" />
<MenuFoldOutlined v-else />
</button>
</div>
</template>
<style scoped>
.ant-sidebar>.ant-layout-sider {
height: 100%;
}
.drawer-handle {
position: fixed;
top: 16px;
left: 16px;
z-index: 1100;
background: rgba(0, 0, 0, 0.55);
color: #fff;
border: none;
width: 36px;
height: 36px;
border-radius: 50%;
cursor: pointer;
display: none;
align-items: center;
justify-content: center;
}
@media (max-width: 768px) {
.drawer-handle {
display: inline-flex;
}
/* On mobile the drawer is the menu — hide the inline sider's content
* + the collapse trigger so the sider stops taking layout space and
* leaves no remnant button next to the page. */
.ant-sidebar>.ant-layout-sider :deep(.ant-layout-sider-children),
.ant-sidebar>.ant-layout-sider :deep(.ant-layout-sider-trigger) {
display: none;
}
.ant-sidebar>.ant-layout-sider {
flex: 0 0 0 !important;
max-width: 0 !important;
min-width: 0 !important;
width: 0 !important;
}
}
</style>
@@ -0,0 +1,31 @@
<script setup>
defineProps({
title: { type: String, default: '' },
value: { type: [String, Number], default: '' },
});
</script>
<template>
<a-statistic :title="title" :value="value">
<template #prefix>
<slot name="prefix" />
</template>
<template #suffix>
<slot name="suffix" />
</template>
</a-statistic>
</template>
<style scoped>
:deep(.ant-statistic-content) {
font-size: 16px;
}
:global(body.dark .ant-statistic-content) {
color: var(--dark-color-text-primary);
}
:global(body.dark .ant-statistic-title) {
color: rgba(255, 255, 255, 0.55);
}
</style>
+366
View File
@@ -0,0 +1,366 @@
<script setup>
import { computed } from 'vue';
import dayjs from 'dayjs';
import PersianDatePicker from 'vue3-persian-datetime-picker';
import { useDatepicker } from '@/composables/useDatepicker.js';
// Drop-in replacement for <a-date-picker> that swaps to a real Jalali
// calendar (vue3-persian-datetime-picker, backed by moment-jalaali)
// when the panel's "Calendar Type" setting is `jalalian`.
//
// The v-model contract matches AD-Vue: the parent works with a dayjs
// object (or null). For the persian picker we serialize to/from the
// `YYYY-MM-DD HH:mm:ss` string it expects so callers don't need to
// know which renderer is active.
const props = defineProps({
value: { type: [Object, null], default: null },
showTime: { type: Boolean, default: true },
format: { type: String, default: 'YYYY-MM-DD HH:mm:ss' },
placeholder: { type: String, default: '' },
disabled: { type: Boolean, default: false },
});
const emit = defineEmits(['update:value']);
const { datepicker } = useDatepicker();
const isJalali = computed(() => datepicker.value === 'jalalian');
const ISO_FORMAT = 'YYYY-MM-DD HH:mm:ss';
// Persian picker's display format — `j…` tokens come from moment-jalaali
// and render Jalali year/month/day.
const persianDisplayFormat = computed(() =>
props.showTime ? 'jYYYY/jMM/jDD HH:mm:ss' : 'jYYYY/jMM/jDD',
);
// Persian picker stores the date as a Gregorian string in the format
// it was given via `format`. We normalize on `YYYY-MM-DD HH:mm:ss` so
// dayjs(...) round-trips cleanly.
const stringValue = computed({
get() {
const v = props.value;
if (!v) return '';
return dayjs.isDayjs(v) ? v.format(ISO_FORMAT) : dayjs(v).format(ISO_FORMAT);
},
set(next) {
if (!next) {
emit('update:value', null);
return;
}
const parsed = dayjs(next, ISO_FORMAT);
emit('update:value', parsed.isValid() ? parsed : null);
},
});
function onAntChange(next) {
emit('update:value', next || null);
}
</script>
<template>
<PersianDatePicker v-if="isJalali" v-model="stringValue" :format="ISO_FORMAT" :display-format="persianDisplayFormat"
:placeholder="placeholder" :disabled="disabled" color="#1677ff" auto-submit append-to="body"
input-class="ant-input persian-datepicker-input" class="jalali-datepicker" />
<a-date-picker v-else :value="value" :show-time="showTime ? { format: 'HH:mm:ss' } : false" :format="format"
:placeholder="placeholder" :disabled="disabled" :style="{ width: '100%' }" @update:value="onAntChange" />
</template>
<style scoped>
.jalali-datepicker {
width: 100%;
}
</style>
<!-- Theme overrides for the picker. AD-Vue 4 doesn't expose CSS variables
by default (its tokens live in JS), so we hardcode hexes per theme
class — `body.dark` for the navy theme, `[data-theme="ultra-dark"]`
for the neutral ultra-dark variant. The popup stays inside the
wrapper's subtree (no teleport) so global selectors reach it cleanly. -->
<style>
/* ===== Light (default) =================================================== */
.persian-datepicker-input {
width: 100%;
box-sizing: border-box;
padding: 4px 11px;
font-size: 14px;
border: 1px solid #d9d9d9;
border-radius: 6px;
background: #fff;
color: rgba(0, 0, 0, 0.88);
transition: border-color 0.2s, box-shadow 0.2s;
}
.persian-datepicker-input:hover {
border-color: #4096ff;
}
.persian-datepicker-input:focus {
border-color: #1677ff;
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1);
outline: none;
}
/* Light theme keeps the picker's brand-blue calendar button (set via
* inline style on .vpd-icon-btn) — only its border + corner radius are
* normalized so it sits flush with the input. Dark/ultra-dark themes
* below override the inline blue so the control matches the form. */
.vpd-main .vpd-icon-btn {
color: #fff;
border: 1px solid transparent;
border-radius: 6px 0 0 6px;
}
/* Match the input's left edge (no rounded left, no double border at the
* seam) so it sits flush against the icon-btn. */
.persian-datepicker-input {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.vpd-main .vpd-clear-btn {
color: rgba(0, 0, 0, 0.45);
background: transparent;
}
/* Width is exactly 316px so the 7-day grid (7 × 40px + 36px padding)
* fits flush. Don't add `border` here — box-sizing: border-box would
* eat 2px from the content width and the 7th day-cell of each row
* wraps. Use box-shadow + a wider radius for the visual edge instead. */
.vpd-wrapper .vpd-content {
background: #fff;
color: rgba(0, 0, 0, 0.88);
box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08),
0 3px 6px -4px rgba(0, 0, 0, 0.12),
0 9px 28px 8px rgba(0, 0, 0, 0.05);
border-radius: 8px;
overflow: hidden;
}
.vpd-wrapper .vpd-header {
background: #1677ff;
color: #fff;
border-radius: 8px 8px 0 0;
}
.vpd-wrapper .vpd-header .vpd-year-label,
.vpd-wrapper .vpd-header .vpd-date,
.vpd-wrapper .vpd-header .vpd-locales li {
color: #fff;
}
.vpd-wrapper .vpd-body {
background: #fff;
color: rgba(0, 0, 0, 0.88);
}
.vpd-wrapper .vpd-body .vpd-month-label,
.vpd-wrapper .vpd-body .vpd-month-label>span {
color: rgba(0, 0, 0, 0.88);
}
.vpd-wrapper .vpd-body .vpd-week,
.vpd-wrapper .vpd-body .vpd-weekday {
color: rgba(0, 0, 0, 0.55);
}
.vpd-wrapper .vpd-body .vpd-controls .vpd-next,
.vpd-wrapper .vpd-body .vpd-controls .vpd-prev {
color: rgba(0, 0, 0, 0.65);
}
/* The picker's <arrow> component renders an inline SVG with a hardcoded
* `fill="#000"` attribute. Override the path fill via CSS so the arrow
* is visible in every theme. */
.vpd-wrapper .vpd-next svg path,
.vpd-wrapper .vpd-prev svg path {
fill: rgba(0, 0, 0, 0.65);
}
.vpd-wrapper .vpd-body .vpd-controls .vpd-next:hover svg path,
.vpd-wrapper .vpd-body .vpd-controls .vpd-prev:hover svg path {
fill: #1677ff;
}
/* The picker paints disabled days as `darken(#fff, 20%)` (~#cccccc) which
* is invisible on white and dark themes alike. Reset the day text color
* across all states so days are always readable. */
.vpd-wrapper .vpd-day,
.vpd-wrapper .vpd-day .vpd-day-text {
color: rgba(0, 0, 0, 0.88) !important;
}
.vpd-wrapper .vpd-day[disabled='true'],
.vpd-wrapper .vpd-day[disabled='true'] .vpd-day-text {
color: rgba(0, 0, 0, 0.25) !important;
}
.vpd-wrapper .vpd-day:not([disabled='true']):hover .vpd-day-text,
.vpd-wrapper .vpd-day.vpd-selected .vpd-day-text {
color: #fff !important;
}
.vpd-wrapper .vpd-actions button {
color: rgba(0, 0, 0, 0.88);
background: transparent;
}
.vpd-wrapper .vpd-actions button:hover {
background: rgba(0, 0, 0, 0.04);
color: #1677ff;
}
.vpd-wrapper .vpd-addon-list,
.vpd-wrapper .vpd-addon-list-content {
background: #fff;
color: rgba(0, 0, 0, 0.88);
}
.vpd-wrapper .vpd-addon-list-item {
color: rgba(0, 0, 0, 0.88);
border-color: #fff;
}
.vpd-wrapper .vpd-addon-list-item.vpd-selected,
.vpd-wrapper .vpd-addon-list-item:hover {
background: rgba(0, 0, 0, 0.04);
}
.vpd-wrapper .vpd-close-addon {
color: rgba(0, 0, 0, 0.65);
background: rgba(0, 0, 0, 0.06);
}
/* ===== Dark (navy) ======================================================= */
body.dark .persian-datepicker-input {
background: #142340;
border-color: #1f3358;
color: rgba(255, 255, 255, 0.88);
}
body.dark .persian-datepicker-input:hover {
border-color: #4096ff;
}
body.dark .persian-datepicker-input:focus {
border-color: #1677ff;
box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.18);
}
body.dark .vpd-main .vpd-icon-btn {
background: rgba(255, 255, 255, 0.04) !important;
border: 1px solid #1f3358 !important;
border-right: none !important;
border-radius: 6px 0 0 6px !important;
color: rgba(255, 255, 255, 0.75) !important;
}
body.dark .vpd-wrapper .vpd-content {
background: #1a2c4d;
color: rgba(255, 255, 255, 0.88);
box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.32),
0 3px 6px -4px rgba(0, 0, 0, 0.48),
0 9px 28px 8px rgba(0, 0, 0, 0.2);
}
body.dark .vpd-wrapper .vpd-body {
background: #1a2c4d;
color: rgba(255, 255, 255, 0.88);
}
body.dark .vpd-wrapper .vpd-body .vpd-month-label,
body.dark .vpd-wrapper .vpd-body .vpd-month-label>span {
color: rgba(255, 255, 255, 0.88);
}
body.dark .vpd-wrapper .vpd-body .vpd-week,
body.dark .vpd-wrapper .vpd-body .vpd-weekday {
color: rgba(255, 255, 255, 0.55);
}
body.dark .vpd-wrapper .vpd-body .vpd-controls .vpd-next,
body.dark .vpd-wrapper .vpd-body .vpd-controls .vpd-prev {
color: rgba(255, 255, 255, 0.65);
}
body.dark .vpd-wrapper .vpd-next svg path,
body.dark .vpd-wrapper .vpd-prev svg path {
fill: rgba(255, 255, 255, 0.75);
}
body.dark .vpd-wrapper .vpd-body .vpd-controls .vpd-next:hover svg path,
body.dark .vpd-wrapper .vpd-body .vpd-controls .vpd-prev:hover svg path {
fill: #4096ff;
}
body.dark .vpd-wrapper .vpd-day,
body.dark .vpd-wrapper .vpd-day .vpd-day-text {
color: rgba(255, 255, 255, 0.88) !important;
}
body.dark .vpd-wrapper .vpd-day[disabled='true'],
body.dark .vpd-wrapper .vpd-day[disabled='true'] .vpd-day-text {
color: rgba(255, 255, 255, 0.25) !important;
}
body.dark .vpd-wrapper .vpd-actions button {
color: rgba(255, 255, 255, 0.88);
}
body.dark .vpd-wrapper .vpd-actions button:hover {
background: rgba(255, 255, 255, 0.06);
}
body.dark .vpd-wrapper .vpd-addon-list,
body.dark .vpd-wrapper .vpd-addon-list-content {
background: #1a2c4d;
color: rgba(255, 255, 255, 0.88);
}
body.dark .vpd-wrapper .vpd-addon-list-item {
color: rgba(255, 255, 255, 0.88);
border-color: transparent;
}
body.dark .vpd-wrapper .vpd-addon-list-item.vpd-selected,
body.dark .vpd-wrapper .vpd-addon-list-item:hover {
background: rgba(255, 255, 255, 0.06);
}
body.dark .vpd-wrapper .vpd-close-addon {
color: rgba(255, 255, 255, 0.65);
background: rgba(255, 255, 255, 0.08);
}
/* ===== Ultra-dark (neutral black) ======================================= */
html[data-theme='ultra-dark'] .persian-datepicker-input {
background: #0a0a0a;
border-color: #303030;
color: rgba(255, 255, 255, 0.88);
}
html[data-theme='ultra-dark'] .vpd-main .vpd-icon-btn {
background: rgba(255, 255, 255, 0.04) !important;
border: 1px solid #303030 !important;
border-right: none !important;
border-radius: 6px 0 0 6px !important;
color: rgba(255, 255, 255, 0.75) !important;
}
html[data-theme='ultra-dark'] .vpd-wrapper .vpd-content {
background: #141414;
color: rgba(255, 255, 255, 0.88);
}
html[data-theme='ultra-dark'] .vpd-wrapper .vpd-body {
background: #141414;
}
html[data-theme='ultra-dark'] .vpd-wrapper .vpd-addon-list,
html[data-theme='ultra-dark'] .vpd-wrapper .vpd-addon-list-content {
background: #141414;
}
</style>
+510
View File
@@ -0,0 +1,510 @@
<script setup>
import { computed } from 'vue';
import { DeleteOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { RandomUtil } from '@/utils';
import { Protocols } from '@/models/inbound.js';
// Mirrors web/html/form/stream/stream_finalmask.html. Used by both the
// inbound and outbound modals — they share the same StreamSettings
// shape (`stream.finalmask`, `stream.addTcpMask()`, etc.) so a single
// component handles both. The host modal passes its protocol through
// so we know whether to show only the Hysteria-specific UDP types.
const props = defineProps({
stream: { type: Object, required: true },
protocol: { type: String, default: '' },
});
const isHysteria = computed(() => props.protocol === Protocols.HYSTERIA);
const network = computed(() => props.stream?.network || '');
const showTcp = computed(() => ['raw', 'tcp', 'httpupgrade', 'ws', 'grpc', 'xhttp'].includes(network.value));
const showUdp = computed(() => isHysteria.value || network.value === 'kcp');
const showQuic = computed(() => isHysteria.value || network.value === 'xhttp');
// Reset the per-row settings shape when the user picks a different
// type — mirrors the legacy `mask._getDefaultSettings(type, {})` call.
function changeMaskType(mask, type) {
mask.type = type;
mask.settings = mask._getDefaultSettings(type, {});
}
// Special case from the legacy form: switching a UDP mask to xdns
// shrinks the kcp MTU; everything else needs the default 1350.
function changeUdpMaskType(mask, type) {
changeMaskType(mask, type);
if (network.value === 'kcp' && props.stream.kcp) {
props.stream.kcp.mtu = type === 'xdns' ? 900 : 1350;
}
}
// header-custom and noise rows share the same per-item shape — the
// type select rewires the packet field. Pulled out so the click
// handlers in the template stay readable.
function changeItemType(item, type) {
item.type = type;
if (type === 'base64') item.packet = RandomUtil.randomBase64();
else if (type === 'array') { item.rand = 0; item.packet = []; }
else item.packet = '';
}
function addUdpMaskWithDefault() {
const def = isHysteria.value ? 'salamander' : 'mkcp-aes128gcm';
props.stream.addUdpMask(def);
}
function newClientServerItem() {
return { delay: 0, rand: 0, randRange: '0-255', type: 'array', packet: [] };
}
function newUdpClientServerItem() {
return { rand: 0, randRange: '0-255', type: 'array', packet: [] };
}
function newNoiseItem() {
return { rand: '1-8192', randRange: '0-255', type: 'array', packet: [], delay: '10-20' };
}
</script>
<template>
<a-form v-if="showTcp || showUdp || showQuic" :colon="false" :label-col="{ md: { span: 8 } }"
:wrapper-col="{ md: { span: 14 } }">
<!-- ============================== TCP MASKS ============================== -->
<template v-if="showTcp">
<a-form-item label="TCP Masks">
<a-button type="primary" size="small" @click="stream.addTcpMask('fragment')">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(mask, mIdx) in (stream.finalmask.tcp || [])" :key="`tcp-${mIdx}`">
<a-divider :style="{ margin: '0' }">
TCP Mask {{ mIdx + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="stream.delTcpMask(mIdx)" />
</a-divider>
<a-form-item label="Type">
<a-select :value="mask.type" @change="(t) => changeMaskType(mask, t)">
<a-select-option value="fragment">Fragment</a-select-option>
<a-select-option value="header-custom">Header Custom</a-select-option>
<a-select-option value="sudoku">Sudoku</a-select-option>
</a-select>
</a-form-item>
<!-- Fragment -->
<template v-if="mask.type === 'fragment'">
<a-form-item label="Packets">
<a-select v-model:value="mask.settings.packets">
<a-select-option value="tlshello">tlshello</a-select-option>
<a-select-option value="1-3">1-3</a-select-option>
<a-select-option value="1-5">1-5</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Length">
<a-input v-model:value="mask.settings.length" placeholder="e.g. 100-200" />
</a-form-item>
<a-form-item label="Delay">
<a-input v-model:value="mask.settings.delay" placeholder="e.g. 10-20" />
</a-form-item>
<a-form-item label="Max Split">
<a-input v-model:value="mask.settings.maxSplit" placeholder="e.g. 3-6" />
</a-form-item>
</template>
<!-- Sudoku -->
<template v-if="mask.type === 'sudoku'">
<a-form-item label="Password">
<a-input v-model:value="mask.settings.password" placeholder="Obfuscation password" />
</a-form-item>
<a-form-item label="ASCII">
<a-input v-model:value="mask.settings.ascii" placeholder="ASCII" />
</a-form-item>
<a-form-item label="Custom Table">
<a-input v-model:value="mask.settings.customTable" placeholder="Custom Table" />
</a-form-item>
<a-form-item label="Custom Tables">
<a-input v-model:value="mask.settings.customTables" placeholder="Custom Tables" />
</a-form-item>
<a-form-item label="Padding Min">
<a-input-number v-model:value="mask.settings.paddingMin" :min="0" />
</a-form-item>
<a-form-item label="Padding Max">
<a-input-number v-model:value="mask.settings.paddingMax" :min="0" />
</a-form-item>
</template>
<!-- Header Custom clients/servers as 2D groups -->
<template v-if="mask.type === 'header-custom'">
<!-- Clients -->
<a-form-item label="Clients">
<a-button type="primary" size="small" @click="mask.settings.clients.push([newClientServerItem()])">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(group, gi) in mask.settings.clients" :key="`tcp-cg-${mIdx}-${gi}`">
<a-divider :style="{ margin: '0' }">
Clients Group {{ gi + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="mask.settings.clients.splice(gi, 1)" />
</a-divider>
<template v-for="(item, ii) in group" :key="`tcp-ci-${mIdx}-${gi}-${ii}`">
<a-form-item label="Type">
<a-select :value="item.type" @change="(t) => changeItemType(item, t)">
<a-select-option value="array">Array</a-select-option>
<a-select-option value="str">String</a-select-option>
<a-select-option value="hex">Hex</a-select-option>
<a-select-option value="base64">Base64</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Delay (ms)">
<a-input-number v-model:value="item.delay" :min="0" />
</a-form-item>
<template v-if="item.type === 'array'">
<a-form-item label="Rand">
<a-input-number v-model:value="item.rand" :min="0" />
</a-form-item>
<a-form-item label="Rand Range">
<a-input v-model:value="item.randRange" placeholder="0-255" />
</a-form-item>
</template>
<a-form-item v-else label="Packet">
<a-input-group v-if="item.type === 'base64'" compact>
<a-input v-model:value="item.packet" placeholder="binary data"
:style="{ width: 'calc(100% - 32px)' }" />
<a-button @click="item.packet = RandomUtil.randomBase64()">
<template #icon>
<ReloadOutlined />
</template>
</a-button>
</a-input-group>
<a-input v-else v-model:value="item.packet" placeholder="binary data" />
</a-form-item>
</template>
</template>
<!-- Servers -->
<a-form-item label="Servers">
<a-button type="primary" size="small" @click="mask.settings.servers.push([newClientServerItem()])">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(group, gi) in mask.settings.servers" :key="`tcp-sg-${mIdx}-${gi}`">
<a-divider :style="{ margin: '0' }">
Servers Group {{ gi + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="mask.settings.servers.splice(gi, 1)" />
</a-divider>
<template v-for="(item, ii) in group" :key="`tcp-si-${mIdx}-${gi}-${ii}`">
<a-form-item label="Type">
<a-select :value="item.type" @change="(t) => changeItemType(item, t)">
<a-select-option value="array">Array</a-select-option>
<a-select-option value="str">String</a-select-option>
<a-select-option value="hex">Hex</a-select-option>
<a-select-option value="base64">Base64</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Delay (ms)">
<a-input-number v-model:value="item.delay" :min="0" />
</a-form-item>
<template v-if="item.type === 'array'">
<a-form-item label="Rand">
<a-input-number v-model:value="item.rand" :min="0" />
</a-form-item>
<a-form-item label="Rand Range">
<a-input v-model:value="item.randRange" placeholder="0-255" />
</a-form-item>
</template>
<a-form-item v-else label="Packet">
<a-input-group v-if="item.type === 'base64'" compact>
<a-input v-model:value="item.packet" placeholder="binary data"
:style="{ width: 'calc(100% - 32px)' }" />
<a-button @click="item.packet = RandomUtil.randomBase64()">
<template #icon>
<ReloadOutlined />
</template>
</a-button>
</a-input-group>
<a-input v-else v-model:value="item.packet" placeholder="binary data" />
</a-form-item>
</template>
</template>
</template>
</template>
</template>
<!-- ============================== UDP MASKS ============================== -->
<template v-if="showUdp">
<a-form-item label="UDP Masks">
<a-button type="primary" size="small" @click="addUdpMaskWithDefault">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(mask, mIdx) in (stream.finalmask.udp || [])" :key="`udp-${mIdx}`">
<a-divider :style="{ margin: '0' }">
UDP Mask {{ mIdx + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="stream.delUdpMask(mIdx)" />
</a-divider>
<a-form-item label="Type">
<a-select :value="mask.type" @change="(t) => changeUdpMaskType(mask, t)">
<template v-if="isHysteria">
<a-select-option value="salamander">Salamander (Hysteria2)</a-select-option>
</template>
<template v-else>
<a-select-option value="mkcp-aes128gcm">mKCP AES-128-GCM</a-select-option>
<a-select-option value="header-dns">Header DNS</a-select-option>
<a-select-option value="header-dtls">Header DTLS 1.2</a-select-option>
<a-select-option value="header-srtp">Header SRTP</a-select-option>
<a-select-option value="header-utp">Header uTP</a-select-option>
<a-select-option value="header-wechat">Header WeChat Video</a-select-option>
<a-select-option value="header-wireguard">Header WireGuard</a-select-option>
<a-select-option value="mkcp-original">mKCP Original</a-select-option>
<a-select-option value="xdns">xDNS</a-select-option>
<a-select-option value="xicmp">xICMP</a-select-option>
<a-select-option value="header-custom">Header Custom</a-select-option>
<a-select-option value="noise">Noise</a-select-option>
</template>
</a-select>
</a-form-item>
<a-form-item v-if="['mkcp-aes128gcm', 'salamander'].includes(mask.type)" label="Password">
<a-input v-model:value="mask.settings.password" placeholder="Obfuscation password" />
</a-form-item>
<a-form-item v-if="mask.type === 'header-dns'" label="Domain">
<a-input v-model:value="mask.settings.domain" placeholder="e.g., www.example.com" />
</a-form-item>
<a-form-item v-if="mask.type === 'xdns'" label="Domains">
<a-select v-model:value="mask.settings.domains" mode="tags" :style="{ width: '100%' }"
:token-separators="[',']" placeholder="e.g., www.example.com" />
</a-form-item>
<!-- Noise -->
<template v-if="mask.type === 'noise'">
<a-form-item label="Reset">
<a-input-number v-model:value="mask.settings.reset" :min="0" />
</a-form-item>
<a-form-item label="Noise">
<a-button type="primary" size="small" @click="mask.settings.noise.push(newNoiseItem())">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(n, ni) in mask.settings.noise" :key="`udp-noise-${mIdx}-${ni}`">
<a-divider :style="{ margin: '0' }">
Noise {{ ni + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="mask.settings.noise.splice(ni, 1)" />
</a-divider>
<a-form-item label="Type">
<a-select :value="n.type" @change="(t) => changeItemType(n, t)">
<a-select-option value="array">Array</a-select-option>
<a-select-option value="str">String</a-select-option>
<a-select-option value="hex">Hex</a-select-option>
<a-select-option value="base64">Base64</a-select-option>
</a-select>
</a-form-item>
<template v-if="n.type === 'array'">
<a-form-item label="Rand">
<a-input v-model:value="n.rand" placeholder="0 or 1-8192" />
</a-form-item>
<a-form-item label="Rand Range">
<a-input v-model:value="n.randRange" placeholder="0-255" />
</a-form-item>
</template>
<a-form-item v-else label="Packet">
<a-input-group v-if="n.type === 'base64'" compact>
<a-input v-model:value="n.packet" placeholder="binary data" :style="{ width: 'calc(100% - 32px)' }" />
<a-button @click="n.packet = RandomUtil.randomBase64()">
<template #icon>
<ReloadOutlined />
</template>
</a-button>
</a-input-group>
<a-input v-else v-model:value="n.packet" placeholder="binary data" />
</a-form-item>
<a-form-item label="Delay">
<a-input v-model:value="n.delay" placeholder="10-20" />
</a-form-item>
</template>
</template>
<!-- Header Custom (UDP) flat client/server lists -->
<template v-if="mask.type === 'header-custom'">
<a-form-item label="Client">
<a-button type="primary" size="small" @click="mask.settings.client.push(newUdpClientServerItem())">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(c, ci) in mask.settings.client" :key="`udp-c-${mIdx}-${ci}`">
<a-divider :style="{ margin: '0' }">
Client {{ ci + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="mask.settings.client.splice(ci, 1)" />
</a-divider>
<a-form-item label="Type">
<a-select :value="c.type" @change="(t) => changeItemType(c, t)">
<a-select-option value="array">Array</a-select-option>
<a-select-option value="str">String</a-select-option>
<a-select-option value="hex">Hex</a-select-option>
<a-select-option value="base64">Base64</a-select-option>
</a-select>
</a-form-item>
<template v-if="c.type === 'array'">
<a-form-item label="Rand">
<a-input-number v-model:value="c.rand" />
</a-form-item>
<a-form-item label="Rand Range">
<a-input v-model:value="c.randRange" placeholder="0-255" />
</a-form-item>
</template>
<a-form-item v-else label="Packet">
<a-input-group v-if="c.type === 'base64'" compact>
<a-input v-model:value="c.packet" placeholder="binary data" :style="{ width: 'calc(100% - 32px)' }" />
<a-button @click="c.packet = RandomUtil.randomBase64()">
<template #icon>
<ReloadOutlined />
</template>
</a-button>
</a-input-group>
<a-input v-else v-model:value="c.packet" placeholder="binary data" />
</a-form-item>
</template>
<a-divider :style="{ margin: '0' }" />
<a-form-item label="Server">
<a-button type="primary" size="small" @click="mask.settings.server.push(newUdpClientServerItem())">
<template #icon>
<PlusOutlined />
</template>
</a-button>
</a-form-item>
<template v-for="(s, si) in mask.settings.server" :key="`udp-s-${mIdx}-${si}`">
<a-divider :style="{ margin: '0' }">
Server {{ si + 1 }}
<DeleteOutlined :style="{ color: 'rgb(255, 77, 79)', cursor: 'pointer', marginLeft: '8px' }"
@click="mask.settings.server.splice(si, 1)" />
</a-divider>
<a-form-item label="Type">
<a-select :value="s.type" @change="(t) => changeItemType(s, t)">
<a-select-option value="array">Array</a-select-option>
<a-select-option value="str">String</a-select-option>
<a-select-option value="hex">Hex</a-select-option>
<a-select-option value="base64">Base64</a-select-option>
</a-select>
</a-form-item>
<template v-if="s.type === 'array'">
<a-form-item label="Rand">
<a-input-number v-model:value="s.rand" />
</a-form-item>
<a-form-item label="Rand Range">
<a-input v-model:value="s.randRange" placeholder="0-255" />
</a-form-item>
</template>
<a-form-item v-else label="Packet">
<a-input-group v-if="s.type === 'base64'" compact>
<a-input v-model:value="s.packet" placeholder="binary data" :style="{ width: 'calc(100% - 32px)' }" />
<a-button @click="s.packet = RandomUtil.randomBase64()">
<template #icon>
<ReloadOutlined />
</template>
</a-button>
</a-input-group>
<a-input v-else v-model:value="s.packet" placeholder="binary data" />
</a-form-item>
</template>
</template>
<!-- xICMP -->
<template v-if="mask.type === 'xicmp'">
<a-form-item label="IP">
<a-input v-model:value="mask.settings.ip" placeholder="0.0.0.0" />
</a-form-item>
<a-form-item label="ID">
<a-input-number v-model:value="mask.settings.id" :min="0" />
</a-form-item>
</template>
</template>
</template>
<!-- ============================== QUIC PARAMS ============================== -->
<template v-if="showQuic">
<a-form-item label="QUIC Params">
<a-switch v-model:checked="stream.finalmask.enableQuicParams" />
</a-form-item>
<template v-if="stream.finalmask.enableQuicParams && stream.finalmask.quicParams">
<a-form-item label="Congestion">
<a-select v-model:value="stream.finalmask.quicParams.congestion">
<a-select-option value="reno">Reno</a-select-option>
<a-select-option value="bbr">BBR</a-select-option>
<a-select-option value="brutal">Brutal</a-select-option>
<a-select-option value="force-brutal">Force Brutal</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Debug">
<a-switch v-model:checked="stream.finalmask.quicParams.debug" />
</a-form-item>
<template v-if="['brutal', 'force-brutal'].includes(stream.finalmask.quicParams.congestion)">
<a-form-item label="Brutal Up">
<a-input v-model:value="stream.finalmask.quicParams.brutalUp" placeholder="65537" />
</a-form-item>
<a-form-item label="Brutal Down">
<a-input v-model:value="stream.finalmask.quicParams.brutalDown" placeholder="65537" />
</a-form-item>
</template>
<a-form-item label="UDP Hop">
<a-switch v-model:checked="stream.finalmask.quicParams.hasUdpHop" />
</a-form-item>
<template v-if="stream.finalmask.quicParams.hasUdpHop && stream.finalmask.quicParams.udpHop">
<a-form-item label="Hop Ports">
<a-input v-model:value="stream.finalmask.quicParams.udpHop.ports" placeholder="e.g. 20000-50000" />
</a-form-item>
<a-form-item label="Hop Interval (s)">
<a-input-number v-model:value="stream.finalmask.quicParams.udpHop.interval" :min="5" />
</a-form-item>
</template>
<a-form-item label="Max Idle Timeout (s)">
<a-input-number v-model:value="stream.finalmask.quicParams.maxIdleTimeout" :min="4" :max="120" />
</a-form-item>
<a-form-item label="Keep Alive Period (s)">
<a-input-number v-model:value="stream.finalmask.quicParams.keepAlivePeriod" :min="2" :max="60" />
</a-form-item>
<a-form-item label="Disable Path MTU Dis">
<a-switch v-model:checked="stream.finalmask.quicParams.disablePathMTUDiscovery" />
</a-form-item>
<a-form-item label="Max Incoming Streams">
<a-input-number v-model:value="stream.finalmask.quicParams.maxIncomingStreams" :min="8"
placeholder="1024 = default" />
</a-form-item>
<a-form-item label="Init Stream Window">
<a-input-number v-model:value="stream.finalmask.quicParams.initStreamReceiveWindow" :min="16384"
placeholder="8388608 = default" />
</a-form-item>
<a-form-item label="Max Stream Window">
<a-input-number v-model:value="stream.finalmask.quicParams.maxStreamReceiveWindow" :min="16384"
placeholder="8388608 = default" />
</a-form-item>
<a-form-item label="Init Conn Window">
<a-input-number v-model:value="stream.finalmask.quicParams.initConnectionReceiveWindow" :min="16384"
placeholder="20971520 = default" />
</a-form-item>
<a-form-item label="Max Conn Window">
<a-input-number v-model:value="stream.finalmask.quicParams.maxConnectionReceiveWindow" :min="16384"
placeholder="20971520 = default" />
</a-form-item>
</template>
</template>
</a-form>
</template>
+18
View File
@@ -0,0 +1,18 @@
<script setup>
// Inline ∞ SVG. The Unicode infinity character (U+221E) renders as an
// "m"-shaped glyph in some system fonts (Windows Segoe UI in particular),
// so the inbound list and client row table use this SVG instead. The
// path matches what the legacy panel embedded.
defineProps({
width: { type: [String, Number], default: 14 },
height: { type: [String, Number], default: 10 },
});
</script>
<template>
<svg :width="width" :height="height" viewBox="0 0 640 512" fill="currentColor" aria-hidden="true"
style="vertical-align: -1px; display: inline-block;">
<path
d="M484.4 96C407 96 349.2 164.1 320 208.5C290.8 164.1 233 96 155.6 96C69.75 96 0 167.8 0 256s69.75 160 155.6 160C233.1 416 290.8 347.9 320 303.5C349.2 347.9 407 416 484.4 416C570.3 416 640 344.2 640 256S570.3 96 484.4 96zM155.6 368C96.25 368 48 317.8 48 256s48.25-112 107.6-112c67.75 0 120.5 82.25 137.1 112C276 285.8 223.4 368 155.6 368zM484.4 368c-67.75 0-120.5-82.25-137.1-112C364 226.2 416.6 144 484.4 144C543.8 144 592 194.2 592 256S543.8 368 484.4 368z" />
</svg>
</template>
+52
View File
@@ -0,0 +1,52 @@
<script setup>
import { ref, watch } from 'vue';
// Generic prompt modal — used by features like "import inbound" that
// need a free-form text/textarea input and a confirm callback. The
// parent owns the action; this component only surfaces the value via
// the `confirm` event when the user clicks OK.
const props = defineProps({
open: { type: Boolean, default: false },
title: { type: String, default: '' },
okText: { type: String, default: 'OK' },
// 'text' = single-line input; 'textarea' = multi-line.
type: { type: String, default: 'text', validator: (v) => ['text', 'textarea'].includes(v) },
initialValue: { type: String, default: '' },
loading: { type: Boolean, default: false },
});
const emit = defineEmits(['update:open', 'confirm']);
const value = ref('');
watch(() => props.open, (next) => {
if (next) value.value = props.initialValue;
});
function close() { emit('update:open', false); }
function ok() { emit('confirm', value.value); }
// Enter submits when single-line; ctrl+S submits in textarea mode
// (matches legacy keybindings).
function onKeydown(e) {
if (props.type !== 'textarea' && e.key === 'Enter') {
e.preventDefault();
ok();
return;
}
if (props.type === 'textarea' && e.ctrlKey && e.key.toLowerCase() === 's') {
e.preventDefault();
ok();
}
}
</script>
<template>
<a-modal :open="open" :title="title" :ok-text="okText" cancel-text="Cancel" :mask-closable="false"
:confirm-loading="loading" @ok="ok" @cancel="close">
<a-textarea v-if="type === 'textarea'" v-model:value="value" :auto-size="{ minRows: 10, maxRows: 20 }" autofocus
@keydown="onKeydown" />
<a-input v-else v-model:value="value" autofocus @keydown="onKeydown" />
</a-modal>
</template>
@@ -0,0 +1,35 @@
<script setup>
import { computed } from 'vue';
const props = defineProps({
paddings: {
type: String,
default: 'default',
validator: (value) => ['small', 'default'].includes(value),
},
});
const padding = computed(() =>
props.paddings === 'small' ? '10px 20px !important' : '20px !important',
);
</script>
<template>
<a-list-item :style="{ padding }">
<a-row :gutter="[8, 16]">
<a-col :xs="24" :lg="12">
<a-list-item-meta>
<template #title>
<slot name="title" />
</template>
<template #description>
<slot name="description" />
</template>
</a-list-item-meta>
</a-col>
<a-col :xs="24" :lg="12">
<slot name="control" />
</a-col>
</a-row>
</a-list-item>
</template>
+297
View File
@@ -0,0 +1,297 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
const props = defineProps({
data: { type: Array, required: true },
labels: { type: Array, default: () => [] },
vbWidth: { type: Number, default: 320 },
height: { type: Number, default: 80 },
stroke: { type: String, default: '#008771' },
strokeWidth: { type: Number, default: 2 },
maxPoints: { type: Number, default: 120 },
showGrid: { type: Boolean, default: true },
gridColor: { type: String, default: 'rgba(0,0,0,0.1)' },
fillOpacity: { type: Number, default: 0.15 },
showMarker: { type: Boolean, default: true },
markerRadius: { type: Number, default: 2.8 },
showAxes: { type: Boolean, default: false },
yTickStep: { type: Number, default: 25 },
tickCountX: { type: Number, default: 4 },
paddingLeft: { type: Number, default: 32 },
paddingRight: { type: Number, default: 6 },
paddingTop: { type: Number, default: 6 },
paddingBottom: { type: Number, default: 20 },
showTooltip: { type: Boolean, default: false },
// Value-range customization. When valueMax is null the chart auto-scales
// to the running max of the data (useful for unbounded series like
// network throughput or online clients). Defaults preserve the legacy
// 0..100 percent behavior so existing callers don't need to change.
valueMin: { type: Number, default: 0 },
valueMax: { type: [Number, null], default: 100 },
// Y-axis tick formatter. Receives the raw value, returns the label.
// tooltipFormatter formats the hover-readout; falls back to yFormatter.
yFormatter: { type: Function, default: (v) => `${Math.round(v)}%` },
tooltipFormatter: { type: Function, default: null },
});
const hoverIdx = ref(-1);
// Measured CSS width of the SVG. Drives the viewBox so SVG units stay
// 1:1 with rendered pixels — otherwise `preserveAspectRatio="none"`
// stretches the X axis and squashes axis text horizontally on narrow
// containers (mobile). Falls back to the prop until the first measure.
const svgRef = ref(null);
const measuredWidth = ref(0);
const effectiveVbWidth = computed(() => measuredWidth.value > 0 ? measuredWidth.value : props.vbWidth);
let resizeObserver = null;
function measure() {
const el = svgRef.value;
if (!el) return;
const w = el.getBoundingClientRect?.().width || 0;
if (w > 0) measuredWidth.value = Math.round(w);
}
onMounted(() => {
measure();
if (typeof ResizeObserver !== 'undefined' && svgRef.value) {
resizeObserver = new ResizeObserver(measure);
resizeObserver.observe(svgRef.value);
} else {
window.addEventListener('resize', measure);
}
});
onBeforeUnmount(() => {
if (resizeObserver) resizeObserver.disconnect();
else window.removeEventListener('resize', measure);
});
const viewBoxAttr = computed(() => `0 0 ${effectiveVbWidth.value} ${props.height}`);
const drawWidth = computed(() => Math.max(1, effectiveVbWidth.value - props.paddingLeft - props.paddingRight));
const drawHeight = computed(() => Math.max(1, props.height - props.paddingTop - props.paddingBottom));
const nPoints = computed(() => Math.min(props.data.length, props.maxPoints));
const dataSlice = computed(() => {
const n = nPoints.value;
if (n === 0) return [];
return props.data.slice(props.data.length - n);
});
const labelsSlice = computed(() => {
const n = nPoints.value;
if (!props.labels?.length || n === 0) return [];
const start = Math.max(0, props.labels.length - n);
return props.labels.slice(start);
});
// Resolved domain. When valueMax is null we auto-scale; pad the upper
// bound by 10% so the line never touches the top edge — looks more
// natural and gives the axis a sane ceiling. Floor the dynamic range
// at 1 to avoid divide-by-zero on flat-line data (e.g. all zeros).
const yDomain = computed(() => {
const min = props.valueMin;
if (props.valueMax != null) return { min, max: props.valueMax };
let max = min;
for (const v of dataSlice.value) {
const n = Number(v);
if (Number.isFinite(n) && n > max) max = n;
}
if (max <= min) max = min + 1;
return { min, max: max * 1.1 };
});
function project(v) {
const { min, max } = yDomain.value;
const span = max - min;
if (span <= 0) return props.paddingTop + drawHeight.value;
const clipped = Math.max(min, Math.min(max, Number(v) || 0));
const ratio = (clipped - min) / span;
return Math.round(props.paddingTop + (drawHeight.value - ratio * drawHeight.value));
}
const pointsArr = computed(() => {
const n = nPoints.value;
if (n === 0) return [];
const slice = dataSlice.value;
const w = drawWidth.value;
const dx = n > 1 ? w / (n - 1) : 0;
return slice.map((v, i) => {
const x = Math.round(props.paddingLeft + i * dx);
return [x, project(v)];
});
});
const pointsStr = computed(() => pointsArr.value.map((p) => `${p[0]},${p[1]}`).join(' '));
const areaPath = computed(() => {
if (pointsArr.value.length === 0) return '';
const first = pointsArr.value[0];
const last = pointsArr.value[pointsArr.value.length - 1];
const baseY = props.paddingTop + drawHeight.value;
const line = pointsStr.value.replace(/ /g, ' L ');
return `M ${first[0]},${baseY} L ${line} L ${last[0]},${baseY} Z`;
});
const gridLines = computed(() => {
if (!props.showGrid) return [];
const h = drawHeight.value;
const w = drawWidth.value;
return [0, 0.25, 0.5, 0.75, 1].map((r) => {
const y = Math.round(props.paddingTop + h * r);
return { x1: props.paddingLeft, y1: y, x2: props.paddingLeft + w, y2: y };
});
});
const lastPoint = computed(() => {
if (pointsArr.value.length === 0) return null;
return pointsArr.value[pointsArr.value.length - 1];
});
// Y-axis tick rendering. We pick a small number of evenly spaced values
// inside the resolved domain and run them through yFormatter — that's
// what makes "MB/s" / "clients" / "%" all render correctly without the
// caller having to subclass the component.
const yTicks = computed(() => {
if (!props.showAxes) return [];
const { min, max } = yDomain.value;
const out = [];
// For percent-style domains keep the legacy fixed step; otherwise
// default to 4 evenly spaced ticks (5 lines including the bottom).
if (props.valueMax === 100 && props.valueMin === 0 && props.yTickStep > 0) {
for (let p = min; p <= max; p += props.yTickStep) {
const y = project(p);
out.push({ y, label: props.yFormatter(p) });
}
return out;
}
const ticks = 5;
for (let i = 0; i < ticks; i++) {
const v = min + ((max - min) * i) / (ticks - 1);
out.push({ y: project(v), label: props.yFormatter(v) });
}
return out;
});
const xTicks = computed(() => {
if (!props.showAxes) return [];
const labels = labelsSlice.value;
const n = nPoints.value;
if (n === 0) return [];
const m = Math.max(2, props.tickCountX);
const w = drawWidth.value;
const dx = n > 1 ? w / (n - 1) : 0;
const out = [];
for (let i = 0; i < m; i++) {
const idx = Math.round((i * (n - 1)) / (m - 1));
const label = labels[idx] != null ? String(labels[idx]) : String(idx);
const x = Math.round(props.paddingLeft + idx * dx);
out.push({ x, label });
}
return out;
});
function onMouseMove(evt) {
if (!props.showTooltip || pointsArr.value.length === 0) return;
const rect = evt.currentTarget.getBoundingClientRect();
const px = evt.clientX - rect.left;
const x = (px / rect.width) * effectiveVbWidth.value;
const n = nPoints.value;
const dx = n > 1 ? drawWidth.value / (n - 1) : 0;
const idx = Math.max(0, Math.min(n - 1, Math.round((x - props.paddingLeft) / (dx || 1))));
hoverIdx.value = idx;
}
function onMouseLeave() {
hoverIdx.value = -1;
}
function fmtHoverText() {
const idx = hoverIdx.value;
if (idx < 0 || idx >= dataSlice.value.length) return '';
const raw = Number(dataSlice.value[idx] || 0);
const fmt = props.tooltipFormatter || props.yFormatter;
const val = fmt(Number.isFinite(raw) ? raw : 0);
const lab = labelsSlice.value[idx] != null ? labelsSlice.value[idx] : '';
return `${val}${lab ? ' • ' + lab : ''}`;
}
// Stable per-instance gradient id so multiple sparklines on a page
// don't clobber each other's <defs id="spkGrad">.
const gradId = `spkGrad-${Math.random().toString(36).slice(2, 9)}`;
</script>
<template>
<svg ref="svgRef" width="100%" :height="height" :viewBox="viewBoxAttr" preserveAspectRatio="none"
class="sparkline-svg" @mousemove="onMouseMove" @mouseleave="onMouseLeave">
<defs>
<linearGradient :id="gradId" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" :stop-color="stroke" :stop-opacity="fillOpacity" />
<stop offset="100%" :stop-color="stroke" stop-opacity="0" />
</linearGradient>
</defs>
<g v-if="showGrid">
<line v-for="(g, i) in gridLines" :key="i" :x1="g.x1" :y1="g.y1" :x2="g.x2" :y2="g.y2" :stroke="gridColor"
stroke-width="1" class="cpu-grid-line" />
</g>
<g v-if="showAxes">
<text v-for="(t, i) in yTicks" :key="'y' + i" class="cpu-grid-y-text" :x="Math.max(0, paddingLeft - 4)"
:y="t.y + 4" text-anchor="end" font-size="10">{{ t.label }}</text>
<text v-for="(t, i) in xTicks" :key="'x' + i" class="cpu-grid-x-text" :x="t.x" :y="paddingTop + drawHeight + 14"
text-anchor="middle" font-size="10">{{ t.label }}</text>
</g>
<path v-if="areaPath" :d="areaPath" :fill="`url(#${gradId})`" stroke="none" />
<polyline :points="pointsStr" fill="none" :stroke="stroke" :stroke-width="strokeWidth" stroke-linecap="round"
stroke-linejoin="round" />
<circle v-if="showMarker && lastPoint" :cx="lastPoint[0]" :cy="lastPoint[1]" :r="markerRadius" :fill="stroke" />
<g v-if="showTooltip && hoverIdx >= 0 && pointsArr[hoverIdx]">
<line class="cpu-grid-h-line" :x1="pointsArr[hoverIdx][0]" :x2="pointsArr[hoverIdx][0]" :y1="paddingTop"
:y2="paddingTop + drawHeight" stroke="rgba(0,0,0,0.2)" stroke-width="1" />
<circle :cx="pointsArr[hoverIdx][0]" :cy="pointsArr[hoverIdx][1]" r="3.5" :fill="stroke" />
<text class="cpu-grid-text" :x="pointsArr[hoverIdx][0]" :y="paddingTop + 12" text-anchor="middle"
font-size="11">{{ fmtHoverText() }}</text>
</g>
</svg>
</template>
<style scoped>
.sparkline-svg {
display: block;
width: 100%;
}
</style>
<!-- Axis labels live on SVG <text> elements; Vue's scoped CSS doesn't
reliably hash-attribute SVG descendants, so the dark-mode overrides
have to live in a non-scoped block to actually take effect. The
numbers are also small, so the dark-theme fills run at ~85% opacity
for legibility (the previous 55% was washed out on navy backgrounds). -->
<style>
.sparkline-svg .cpu-grid-y-text,
.sparkline-svg .cpu-grid-x-text {
fill: rgba(0, 0, 0, 0.65);
}
.sparkline-svg .cpu-grid-text {
fill: rgba(0, 0, 0, 0.88);
}
body.dark .sparkline-svg .cpu-grid-y-text,
body.dark .sparkline-svg .cpu-grid-x-text {
fill: rgba(255, 255, 255, 0.85);
}
body.dark .sparkline-svg .cpu-grid-text {
fill: rgba(255, 255, 255, 0.95);
}
body.dark .sparkline-svg .cpu-grid-line {
stroke: rgba(255, 255, 255, 0.12);
}
body.dark .sparkline-svg .cpu-grid-h-line {
stroke: rgba(255, 255, 255, 0.35);
}
</style>
+311
View File
@@ -0,0 +1,311 @@
<script>
// Use defineComponent so we can keep the parent + child components in
// the same file with the provide() <-> inject relationship intact.
import { defineComponent, h, computed, ref, resolveComponent, inject } from 'vue';
import { DragOutlined } from '@ant-design/icons-vue';
const ROW_CLASS = 'sortable-row';
// Sortable a-table — drag-to-reorder rows using Pointer Events.
//
// Why a custom component:
// - Old impl set draggable: true on every row, which broke text selection
// in cells and let HTML5 start drags from anywhere on the row. This
// version only initiates drag from an explicit handle, via Pointer
// Events (one API for mouse + touch + pen).
// - During drag, data-source is reordered live; the source row visually
// slides into the target slot. The live reorder IS the visual feedback.
// - On commit, emits onsort(sourceIndex, targetIndex) — same signature as
// before so existing call sites stay unchanged.
// - Keyboard support: ArrowUp/ArrowDown move the focused handle's row by
// one; Escape cancels an in-flight drag.
export const TableSortableTrigger = defineComponent({
name: 'TableSortableTrigger',
props: {
itemIndex: { type: Number, required: true },
},
setup(props) {
const sortable = inject('sortable', null);
const ariaLabel = computed(() => `Drag to reorder row ${(props.itemIndex ?? 0) + 1}`);
function onPointerDown(e) {
sortable?.startDrag?.(e, props.itemIndex);
}
function onKeyDown(e) {
const move = sortable?.moveByKeyboard;
if (!move) return;
if (e.key === 'ArrowUp') {
e.preventDefault();
move(-1, props.itemIndex);
} else if (e.key === 'ArrowDown') {
e.preventDefault();
move(+1, props.itemIndex);
}
}
return () => h(DragOutlined, {
class: 'sortable-icon',
role: 'button',
tabindex: 0,
'aria-label': ariaLabel.value,
onPointerdown: onPointerDown,
onKeydown: onKeyDown,
});
},
});
export default defineComponent({
name: 'TableSortable',
inheritAttrs: false,
props: {
dataSource: { type: Array, default: () => [] },
customRow: { type: Function, default: null },
rowKey: { type: [String, Function], default: null },
locale: {
type: Object,
default: () => ({ filterConfirm: 'OK', filterReset: 'Reset', emptyText: 'No data' }),
},
},
emits: ['onsort'],
setup(props, { emit, slots, attrs, expose }) {
// null when idle; while dragging:
// { sourceIndex, targetIndex, pointerId, sourceKey }
const drag = ref(null);
const rootRef = ref(null);
const isDragging = computed(() => drag.value !== null);
// Resolve the row key for a record. Used to identify the source row
// even after data-source is reordered live during drag.
function keyOf(record, fallback) {
const rk = props.rowKey;
if (typeof rk === 'function') return rk(record);
if (typeof rk === 'string') return record?.[rk];
return fallback;
}
function attachListeners() {
document.addEventListener('pointermove', onPointerMove, true);
document.addEventListener('pointerup', onPointerUp, true);
document.addEventListener('pointercancel', cancelDrag, true);
document.addEventListener('keydown', cancelDrag, true);
}
function detachListeners() {
document.removeEventListener('pointermove', onPointerMove, true);
document.removeEventListener('pointerup', onPointerUp, true);
document.removeEventListener('pointercancel', cancelDrag, true);
document.removeEventListener('keydown', cancelDrag, true);
}
function startDrag(e, sourceIndex) {
// Primary button only (mouse left / first touch).
if (e.button != null && e.button !== 0) return;
e.preventDefault();
const record = props.dataSource?.[sourceIndex];
drag.value = {
sourceIndex,
targetIndex: sourceIndex,
pointerId: e.pointerId,
sourceKey: keyOf(record, sourceIndex),
};
// Capture the pointer so move/up keep firing even if the cursor
// leaves the icon. Try/catch — some older browsers throw on capture.
if (e.target?.setPointerCapture && e.pointerId != null) {
try { e.target.setPointerCapture(e.pointerId); } catch (_) { /* ignore */ }
}
attachListeners();
}
function onPointerMove(e) {
const d = drag.value;
if (!d) return;
if (d.pointerId != null && e.pointerId !== d.pointerId) return;
const root = rootRef.value;
if (!root) return;
const rows = root.querySelectorAll(`tr.${ROW_CLASS}`);
if (!rows.length) return;
const y = e.clientY;
const firstRect = rows[0].getBoundingClientRect();
const lastRect = rows[rows.length - 1].getBoundingClientRect();
let target = d.targetIndex;
if (y < firstRect.top) {
target = 0;
} else if (y > lastRect.bottom) {
target = rows.length - 1;
} else {
for (let i = 0; i < rows.length; i++) {
const rect = rows[i].getBoundingClientRect();
if (y >= rect.top && y <= rect.bottom) {
target = i;
break;
}
}
}
if (target !== d.targetIndex) {
drag.value = { ...d, targetIndex: target };
}
}
function onPointerUp(e) {
const d = drag.value;
if (!d) return;
if (d.pointerId != null && e.pointerId !== d.pointerId) return;
detachListeners();
const captured = d;
drag.value = null;
if (captured.sourceIndex !== captured.targetIndex) {
emit('onsort', captured.sourceIndex, captured.targetIndex);
}
}
function cancelDrag(e) {
// Triggered by pointercancel and keydown. For keydown only act on
// Escape; otherwise let the event propagate.
if (e?.type === 'keydown' && e.key !== 'Escape') return;
detachListeners();
drag.value = null;
}
function moveByKeyboard(direction, sourceIndex) {
const target = sourceIndex + direction;
if (target < 0 || target >= (props.dataSource?.length ?? 0)) return;
emit('onsort', sourceIndex, target);
}
function customRowRender(record, index) {
const parent = typeof props.customRow === 'function' ? props.customRow(record, index) || {} : {};
const d = drag.value;
const isSource = d && keyOf(record, index) === d.sourceKey;
// Vue 3 customRow shape: a flat object of attrs/listeners/class —
// no nested props/on like Vue 2.
return {
...parent,
class: { [ROW_CLASS]: true, 'sortable-source-row': !!isSource, ...(parent.class || {}) },
};
}
// Render-data: dataSource with the source row spliced into targetIndex.
// When idle the original list is returned unchanged so a-table can
// diff against a stable reference.
const records = computed(() => {
const d = drag.value;
const src = props.dataSource ?? [];
if (!d || d.sourceIndex === d.targetIndex) return src;
const list = src.slice();
const [item] = list.splice(d.sourceIndex, 1);
list.splice(d.targetIndex, 0, item);
return list;
});
expose({ startDrag, moveByKeyboard });
return {
rootRef, drag, isDragging, records, slots, attrs,
startDrag, moveByKeyboard, customRowRender,
};
},
// provide() needs to live at the options level so child components in
// the rendered subtree resolve the same instance methods.
provide() {
return {
sortable: {
startDrag: (...a) => this.startDrag(...a),
moveByKeyboard: (...a) => this.moveByKeyboard(...a),
},
};
},
beforeUnmount() {
document.removeEventListener('pointermove', this.onPointerMove, true);
document.removeEventListener('pointerup', this.onPointerUp, true);
document.removeEventListener('pointercancel', this.cancelDrag, true);
document.removeEventListener('keydown', this.cancelDrag, true);
},
render() {
// Forward every passed slot to a-table by reusing the slot fn
// directly. Vue 3 slots are scoped by default so no $scopedSlots dance.
const tableSlots = {};
for (const name of Object.keys(this.slots)) {
tableSlots[name] = this.slots[name];
}
// Resolved at runtime so the user's app.use(Antd) registration wins;
// avoids importing Table directly here.
const ATable = resolveComponent('a-table');
return h(
'div',
{ ref: 'rootRef' },
[h(
ATable,
{
...this.attrs,
'data-source': this.records,
'row-key': this.rowKey,
customRow: this.customRowRender,
locale: this.locale,
class: ['sortable-table', { 'sortable-table-dragging': this.isDragging }],
},
tableSlots,
)],
);
},
});
</script>
<style>
.sortable-icon {
display: inline-flex;
align-items: center;
justify-content: center;
cursor: grab;
padding: 6px;
border-radius: 6px;
color: rgba(255, 255, 255, 0.5);
transition: background-color 0.15s ease, color 0.15s ease;
user-select: none;
touch-action: none;
}
.sortable-icon:hover {
color: rgba(255, 255, 255, 0.85);
background: rgba(255, 255, 255, 0.06);
}
.sortable-icon:active {
cursor: grabbing;
}
.sortable-icon:focus-visible {
outline: 2px solid #008771;
outline-offset: 2px;
}
.light .sortable-icon {
color: rgba(0, 0, 0, 0.45);
}
.light .sortable-icon:hover {
color: rgba(0, 0, 0, 0.85);
background: rgba(0, 0, 0, 0.05);
}
.sortable-table-dragging .sortable-source-row>td {
background: rgba(0, 135, 113, 0.10) !important;
transition: background-color 0.18s ease;
}
.sortable-table-dragging .sortable-source-row .routing-index,
.sortable-table-dragging .sortable-source-row .outbound-index {
opacity: 0.45;
}
.sortable-table-dragging .sortable-row>td {
transition: background-color 0.18s ease;
}
.sortable-table-dragging,
.sortable-table-dragging * {
user-select: none;
}
</style>
+66
View File
@@ -0,0 +1,66 @@
<script setup>
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { ClipboardManager, FileManager } from '@/utils';
// Read-only text modal — used to surface multi-line export blobs
// (subscription URLs, raw inbound JSON, generated share links) the
// way the legacy txtModal did.
defineProps({
open: { type: Boolean, default: false },
title: { type: String, default: '' },
content: { type: String, default: '' },
// When set, surfaces a download button that writes `content` to a
// text file with this name.
fileName: { type: String, default: '' },
});
const emit = defineEmits(['update:open']);
function close() {
emit('update:open', false);
}
async function copy(value) {
const ok = await ClipboardManager.copyText(value || '');
if (ok) {
message.success('Copied');
close();
}
}
function download(content, name) {
if (!name) return;
FileManager.downloadTextFile(content, name);
}
</script>
<template>
<a-modal :open="open" :title="title" :closable="true" @cancel="close">
<a-textarea :value="content" readonly :auto-size="{ minRows: 10, maxRows: 20 }" class="text-modal-content" />
<template #footer>
<a-button v-if="fileName" @click="download(content, fileName)">
<template #icon>
<DownloadOutlined />
</template>
{{ fileName }}
</a-button>
<a-button type="primary" @click="copy(content)">
<template #icon>
<CopyOutlined />
</template>
Copy
</a-button>
</template>
</a-modal>
</template>
<style scoped>
.text-modal-content {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
overflow-y: auto;
}
</style>
+49
View File
@@ -0,0 +1,49 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { BulbFilled, BulbOutlined } from '@ant-design/icons-vue';
import { theme, currentTheme, toggleTheme, toggleUltra, pauseAnimationsUntilLeave } from '@/composables/useTheme.js';
const { t } = useI18n();
const BulbIcon = computed(() => (theme.isDark ? BulbFilled : BulbOutlined));
function onDarkChange() {
pauseAnimationsUntilLeave('change-theme');
toggleTheme();
}
function onUltraClick() {
pauseAnimationsUntilLeave('change-theme-ultra');
toggleUltra();
}
</script>
<template>
<a-menu :theme="currentTheme" mode="inline" :selected-keys="[]">
<a-sub-menu>
<template #title>
<span>
<component :is="BulbIcon" />
<span class="theme-label">{{ t('menu.theme') }}</span>
</span>
</template>
<a-menu-item id="change-theme" class="ant-menu-theme-switch">
<span>{{ t('menu.dark') }}</span>
<a-switch :style="{ marginLeft: '2px' }" size="small" :checked="theme.isDark" @change="onDarkChange" />
</a-menu-item>
<a-menu-item v-if="theme.isDark" id="change-theme-ultra" class="ant-menu-theme-switch">
<span>{{ t('menu.ultraDark') }}</span>
<a-checkbox :style="{ marginLeft: '2px' }" :checked="theme.isUltra" @click="onUltraClick" />
</a-menu-item>
</a-sub-menu>
</a-menu>
</template>
<style scoped>
.theme-label {
margin-left: 8px;
}
</style>
@@ -0,0 +1,25 @@
<script setup>
import { theme, toggleTheme, toggleUltra, pauseAnimationsUntilLeave } from '@/composables/useTheme.js';
function onDarkChange() {
pauseAnimationsUntilLeave('change-theme');
toggleTheme();
}
function onUltraClick() {
toggleUltra();
}
</script>
<template>
<a-space id="change-theme" direction="vertical" :size="10" :style="{ width: '100%' }">
<a-space direction="horizontal" size="small">
<a-switch size="small" :checked="theme.isDark" @change="onDarkChange" />
<span>Dark</span>
</a-space>
<a-space v-if="theme.isDark" direction="horizontal" size="small">
<a-checkbox :checked="theme.isUltra" @click="onUltraClick" />
<span>Ultra dark</span>
</a-space>
</a-space>
</template>
+45
View File
@@ -0,0 +1,45 @@
// Module-scoped reactive ref for the panel's "Calendar Type" setting.
// Loaded from /panel/setting/defaultSettings on first use, so any
// component (modals, inbound forms, future pages) can read the same
// value without prop-drilling and without re-fetching.
//
// useInbounds (which already reads defaultSettings for its own state)
// calls setDatepicker() after its fetch so we don't issue a second
// HTTP round-trip on the inbounds page.
import { readonly, ref } from 'vue';
import { HttpUtil } from '@/utils';
const datepicker = ref('gregorian');
let fetched = false;
let pending = null;
async function loadOnce() {
if (fetched) return;
if (pending) {
await pending;
return;
}
pending = (async () => {
try {
const msg = await HttpUtil.post('/panel/setting/defaultSettings');
if (msg?.success) {
datepicker.value = msg.obj?.datepicker || 'gregorian';
}
} finally {
fetched = true;
pending = null;
}
})();
await pending;
}
export function setDatepicker(value) {
fetched = true;
datepicker.value = value || 'gregorian';
}
export function useDatepicker() {
loadOnce();
return { datepicker: readonly(datepicker) };
}
+26
View File
@@ -0,0 +1,26 @@
import { ref, onBeforeUnmount, onMounted } from 'vue';
const MOBILE_BREAKPOINT_PX = 768;
// Vue 3 replacement for the legacy MediaQueryMixin. Returns a reactive
// `isMobile` ref that updates on window resize. Use inside <script setup>:
//
// const { isMobile } = useMediaQuery();
export function useMediaQuery(breakpoint = MOBILE_BREAKPOINT_PX) {
const compute = () => window.innerWidth <= breakpoint;
const isMobile = ref(compute());
const onResize = () => {
isMobile.value = compute();
};
onMounted(() => {
window.addEventListener('resize', onResize);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', onResize);
});
return { isMobile };
}
+42
View File
@@ -0,0 +1,42 @@
// Lightweight composable that fetches the node list once on mount and
// exposes id→name + id→online lookups. Used by the Inbounds page so it
// can render a Node selector and a Node column without pulling the
// full pages/nodes/useNodes.js (which polls and owns CRUD state).
import { onMounted, ref, computed } from 'vue';
import { HttpUtil } from '@/utils';
export function useNodeList() {
const nodes = ref([]);
const fetched = ref(false);
async function refresh() {
const msg = await HttpUtil.get('/panel/api/nodes/list');
if (msg?.success) {
nodes.value = Array.isArray(msg.obj) ? msg.obj : [];
}
fetched.value = true;
}
// Indexed by id for O(1) UI lookups (Node column on N-row tables).
const byId = computed(() => {
const m = new Map();
for (const n of nodes.value) m.set(n.id, n);
return m;
});
function nameFor(id) {
if (id == null) return null;
return byId.value.get(id)?.name || null;
}
function isOnline(id) {
if (id == null) return true;
const n = byId.value.get(id);
return n != null && n.enable && n.status === 'online';
}
onMounted(refresh);
return { nodes, fetched, refresh, byId, nameFor, isOnline };
}
+43
View File
@@ -0,0 +1,43 @@
import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue';
import { HttpUtil } from '@/utils';
import { Status } from '@/models/status.js';
const POLL_INTERVAL_MS = 2000;
// Polls /panel/api/server/status and exposes a reactive Status object
// + a `fetched` flag so consumers can show a spinner before the first
// successful fetch.
//
// WebSocket integration is intentionally deferred to a later sub-phase.
// Polling at 2s is the same fallback the legacy panel falls back to
// when its websocket link drops, so we're shipping the proven path
// first and adding the websocket on top later.
export function useStatus() {
const status = shallowRef(new Status());
const fetched = ref(false);
let timer = null;
async function refresh() {
try {
const msg = await HttpUtil.get('/panel/api/server/status');
if (msg?.success) {
status.value = new Status(msg.obj);
if (!fetched.value) fetched.value = true;
}
} catch (e) {
console.error('Failed to get status:', e);
}
}
onMounted(() => {
refresh();
timer = window.setInterval(refresh, POLL_INTERVAL_MS);
});
onBeforeUnmount(() => {
if (timer != null) window.clearInterval(timer);
});
return { status, fetched, refresh };
}
+128
View File
@@ -0,0 +1,128 @@
import { reactive, computed, watchEffect } from 'vue';
import { theme as antdTheme } from 'ant-design-vue';
// Single shared theme state. `import { theme } from '@/composables/useTheme.js'`
// from any component to read/toggle. Boot side-effects (apply current
// theme to <body>/<html>) run once at module load so the page is in the
// right theme before Vue mounts.
const STORAGE_DARK = 'dark-mode';
const STORAGE_ULTRA = 'isUltraDarkThemeEnabled';
function readBool(key, fallback) {
const raw = localStorage.getItem(key);
if (raw === null) return fallback;
return raw === 'true';
}
const isDark = readBool(STORAGE_DARK, true);
const isUltra = readBool(STORAGE_ULTRA, false);
export const theme = reactive({
isDark,
isUltra,
});
export const currentTheme = computed(() => (theme.isDark ? 'dark' : 'light'));
// AD-Vue 4 theme config consumed by every page's <a-config-provider>.
// Three modes — light / dark / ultra-dark — all share AD-Vue's vanilla
// blue primary. Dark uses a navy palette across page/cards/modals so
// the sidebar blends with the rest of the surface; ultra-dark stays
// neutral black on top of darkAlgorithm.
const DARK_TOKENS = {
colorBgBase: '#0a1426',
colorBgLayout: '#0a1426',
colorBgContainer: '#142340',
colorBgElevated: '#1a2c4d',
};
const ULTRA_DARK_TOKENS = {
colorBgBase: '#000',
colorBgLayout: '#000',
colorBgContainer: '#0a0a0a',
colorBgElevated: '#141414',
};
// AD-Vue 4 hardcodes navy `#001529` / `#002140` as the Layout sider
// + trigger backgrounds and `#001529` / `#000c17` as the dark Menu item
// backgrounds (see node_modules/ant-design-vue/es/{layout,menu}/style/
// index.js). Override at the component-token level so the sider blends
// with darkAlgorithm's neutral surfaces.
// Dark theme uses a refined navy for the sidebar — distinct from the
// neutral ultra-dark and warmer than AD-Vue's stock #001529.
const DARK_LAYOUT_TOKENS = {
colorBgHeader: '#0d1d33',
colorBgTrigger: '#15294a',
colorBgBody: '#000',
};
const ULTRA_DARK_LAYOUT_TOKENS = {
colorBgHeader: '#0a0a0a',
colorBgTrigger: '#141414',
colorBgBody: '#000',
};
const DARK_MENU_TOKENS = {
colorItemBg: '#0d1d33',
colorSubItemBg: '#08142a',
menuSubMenuBg: '#0d1d33',
};
const ULTRA_DARK_MENU_TOKENS = {
colorItemBg: '#0a0a0a',
colorSubItemBg: '#000',
menuSubMenuBg: '#0a0a0a',
};
export const antdThemeConfig = computed(() => {
if (!theme.isDark) {
return { algorithm: antdTheme.defaultAlgorithm };
}
return {
algorithm: antdTheme.darkAlgorithm,
token: theme.isUltra ? ULTRA_DARK_TOKENS : DARK_TOKENS,
components: {
Layout: theme.isUltra ? ULTRA_DARK_LAYOUT_TOKENS : DARK_LAYOUT_TOKENS,
Menu: theme.isUltra ? ULTRA_DARK_MENU_TOKENS : DARK_MENU_TOKENS,
},
};
});
export function toggleTheme() {
theme.isDark = !theme.isDark;
}
export function toggleUltra() {
theme.isUltra = !theme.isUltra;
}
// Briefly disable theme transition animations while a toggle is in
// flight, then re-enable on mouseleave. Mirrors the legacy panel's
// behavior of preventing flicker when hovering the theme menu.
export function pauseAnimationsUntilLeave(elementId) {
document.documentElement.setAttribute('data-theme-animations', 'off');
const el = document.getElementById(elementId);
if (!el) return;
const restore = () => {
document.documentElement.removeAttribute('data-theme-animations');
el.removeEventListener('mouseleave', restore);
el.removeEventListener('touchend', restore);
};
el.addEventListener('mouseleave', restore);
el.addEventListener('touchend', restore);
}
// Apply theme to DOM and persist whenever it changes.
watchEffect(() => {
document.body.setAttribute('class', theme.isDark ? 'dark' : 'light');
localStorage.setItem(STORAGE_DARK, String(theme.isDark));
if (theme.isUltra) {
document.documentElement.setAttribute('data-theme', 'ultra-dark');
} else {
document.documentElement.removeAttribute('data-theme');
}
localStorage.setItem(STORAGE_ULTRA, String(theme.isUltra));
// Keep the global #message container's class in sync so AD-Vue toasts
// pick up the right styling.
const msg = document.getElementById('message');
if (msg) msg.className = theme.isDark ? 'dark' : 'light';
});
+48
View File
@@ -0,0 +1,48 @@
import { onBeforeUnmount, onMounted } from 'vue';
import { WebSocketClient } from '@/api/websocket.js';
// One client per browser tab (= per multi-page entry). WebSocketClient is
// idempotent: repeated connect() calls while the socket is already open
// are no-ops, so multiple components on the same page can share a single
// underlying connection without each spawning their own.
let sharedClient = null;
function getSharedClient() {
if (sharedClient) return sharedClient;
const basePath = (typeof window !== 'undefined' && window.__X_UI_BASE_PATH__) || '';
sharedClient = new WebSocketClient(basePath);
return sharedClient;
}
// useWebSocket lets a Vue component subscribe to live server-pushed
// events. Pass a map of { eventName: handler } and the composable wires
// connect()/disconnect() into the component lifecycle and unsubscribes
// every handler on unmount so a stale closure can't fire after the
// page has moved on.
//
// Example:
// useWebSocket({
// traffic: (payload) => applyTrafficEvent(payload),
// client_stats: (payload) => applyClientStatsEvent(payload),
// invalidate: ({ type }) => { if (type === 'inbounds') refresh(); },
// });
//
// Built-in lifecycle events ('connected' / 'disconnected' / 'error')
// can be subscribed to alongside server-emitted types.
export function useWebSocket(handlers) {
const client = getSharedClient();
const entries = Object.entries(handlers || {});
onMounted(() => {
for (const [event, fn] of entries) client.on(event, fn);
client.connect();
});
onBeforeUnmount(() => {
for (const [event, fn] of entries) client.off(event, fn);
// Don't disconnect — another mounted component on the same page may
// still be subscribed. The client closes naturally on page unload.
});
return { client };
}
+17
View File
@@ -0,0 +1,17 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import InboundsPage from '@/pages/inbounds/InboundsPage.vue';
setupAxios();
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(InboundsPage).use(Antd).use(i18n).mount('#app');
+19
View File
@@ -0,0 +1,19 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
// Importing useTheme triggers the boot side-effect that applies the
// stored theme to <body>/<html> before Vue mounts.
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import IndexPage from '@/pages/index/IndexPage.vue';
setupAxios();
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(IndexPage).use(Antd).use(i18n).mount('#app');
+21
View File
@@ -0,0 +1,21 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
// Importing this module triggers the boot side-effect that applies the
// stored theme to <body>/<html> before Vue renders anything.
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import LoginPage from '@/pages/login/LoginPage.vue';
setupAxios();
// Toasts attach to a #message div the page provides — keeps theme
// styling in sync with the rest of the panel.
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(LoginPage).use(Antd).use(i18n).mount('#app');
+17
View File
@@ -0,0 +1,17 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import NodesPage from '@/pages/nodes/NodesPage.vue';
setupAxios();
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(NodesPage).use(Antd).use(i18n).mount('#app');
+19
View File
@@ -0,0 +1,19 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
// Importing useTheme triggers the boot side-effect that applies the
// stored theme to <body>/<html> before Vue mounts.
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import SettingsPage from '@/pages/settings/SettingsPage.vue';
setupAxios();
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(SettingsPage).use(Antd).use(i18n).mount('#app');
+18
View File
@@ -0,0 +1,18 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
// The sub page is served by the subscription HTTP server (sub/sub.go)
// at /<linksPath>/<subId>?html=1. Go injects window.__SUB_PAGE_DATA__
// with the parsed traffic/quota/expiry view-model and the rendered
// share links — the SPA reads those at mount.
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import SubPage from '@/pages/sub/SubPage.vue';
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(SubPage).use(Antd).use(i18n).mount('#app');
+17
View File
@@ -0,0 +1,17 @@
import { createApp } from 'vue';
import Antd, { message } from 'ant-design-vue';
import 'ant-design-vue/dist/reset.css';
import { setupAxios } from '@/api/axios-init.js';
import '@/composables/useTheme.js';
import { i18n } from '@/i18n/index.js';
import XrayPage from '@/pages/xray/XrayPage.vue';
setupAxios();
const messageContainer = document.getElementById('message');
if (messageContainer) {
message.config({ getContainer: () => messageContainer });
}
createApp(XrayPage).use(Antd).use(i18n).mount('#app');
+93
View File
@@ -0,0 +1,93 @@
// vue-i18n setup. Locale files live in web/translation/*.json — the same
// directory the Go binary embeds, so SPA + Telegram bot + subscription
// page all read from a single source.
//
// Usage in a component:
// import { useI18n } from 'vue-i18n';
// const { t } = useI18n();
// ...
// <span>{{ t('pages.inbounds.email') }}</span>
//
// Or via the global helper exposed on the app:
// <span>{{ $t('pages.inbounds.email') }}</span>
//
// The locale follows the `lang` cookie that LanguageManager already
// reads/writes — switching language anywhere in the app continues to
// trigger a full page reload (matches legacy ergonomics), so we don't
// need a runtime locale switcher here.
import { createI18n } from 'vue-i18n';
import { LanguageManager } from '@/utils';
// Lazy-loaded locales — Vite splits each one into its own chunk. We
// eager-load only the active language plus the en-US fallback so the
// initial page payload stays small (the inbounds bundle was sitting
// at ~700kB gzipped with all 13 locales eager; now ~480kB).
//
// LanguageManager.setLanguage() does a full reload on change, so
// "lazy" here effectively means "load only what this page needs for
// its lifetime."
const FALLBACK = 'en-US';
const lazyModules = import.meta.glob('../../../web/translation/*.json');
const eagerModules = import.meta.glob('../../../web/translation/*.json', { eager: true });
function moduleKeyFor(code) {
return `../../../web/translation/${code}.json`;
}
// Resolve the active locale via LanguageManager so the cookie set on
// the legacy panel keeps working after a user upgrades. Falls back
// to en-US when the cookie names a language we don't have.
let active = LanguageManager.getLanguage();
if (!Object.prototype.hasOwnProperty.call(lazyModules, moduleKeyFor(active))) {
active = FALLBACK;
}
const messages = {};
// Eagerly include the active locale + the fallback (when distinct)
// so the very first render has strings ready. Vite still emits these
// as their own chunks so the user pays for at most two locales.
for (const code of new Set([active, FALLBACK])) {
const mod = eagerModules[moduleKeyFor(code)];
if (mod) messages[code] = mod.default || mod;
}
export const i18n = createI18n({
legacy: false,
// `composition` mode (legacy: false) so `useI18n()` works in
// <script setup> blocks.
globalInjection: true,
locale: active,
fallbackLocale: FALLBACK,
// Locale JSON is nested by namespace ({pages: {inbounds: {email: ...}}})
// so vue-i18n's default `.`-delimited lookups walk straight into it.
messages,
// The Go side sometimes interpolates `#variable#` into translated
// strings (e.g. xraySwitchVersionDialogDesc). vue-i18n's default
// expects `{var}` — disable warnings about strings that look like
// they don't use the new syntax.
warnHtmlMessage: false,
missingWarn: false,
fallbackWarn: false,
});
// Convenience export for non-component contexts (HTTP error toasts,
// stores, etc.) that need to look up a translation outside a setup
// scope.
export function t(key, params) {
return i18n.global.t(key, params || {});
}
// loadLocale fetches a locale module on demand and registers it with
// vue-i18n. Pages that switch language at runtime (rather than via
// LanguageManager's reload) can call this to swap strings live.
export async function loadLocale(code) {
const key = moduleKeyFor(code);
const loader = lazyModules[key];
if (!loader) return false;
const mod = await loader();
i18n.global.setLocaleMessage(code, mod.default || mod);
i18n.global.locale.value = code;
return true;
}
@@ -1,4 +1,8 @@
class DBInbound {
import dayjs from 'dayjs';
import { ObjectUtil, NumberFormatter, SizeFormatter } from '@/utils';
import { Inbound, Protocols } from './inbound.js';
export class DBInbound {
constructor(data) {
this.id = 0;
@@ -21,6 +25,9 @@ class DBInbound {
this.tag = "";
this.sniffing = "";
this.clientStats = ""
// Optional FK to web/runtime registered Node. null/undefined =
// local panel; otherwise the inbound lives on the named node.
this.nodeId = null;
if (data == null) {
return;
}
@@ -75,7 +82,7 @@ class DBInbound {
if (this.expiryTime === 0) {
return null;
}
return moment(this.expiryTime);
return dayjs(this.expiryTime);
}
set _expiryTime(t) {
@@ -169,8 +176,8 @@ class DBInbound {
}
}
genInboundLinks(remarkModel) {
genInboundLinks(remarkModel, hostOverride = '') {
const inbound = this.toInbound();
return inbound.genInboundLinks(this.remark, remarkModel);
return inbound.genInboundLinks(this.remark, remarkModel, hostOverride);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,27 +1,24 @@
// List of popular services for VLESS Reality Target/SNI randomization
const REALITY_TARGETS = [
{ target: 'www.apple.com:443', sni: 'www.apple.com' },
{ target: 'www.icloud.com:443', sni: 'www.icloud.com' },
{ target: 'www.amazon.com:443', sni: 'www.amazon.com' },
{ target: 'aws.amazon.com:443', sni: 'aws.amazon.com' },
{ target: 'www.oracle.com:443', sni: 'www.oracle.com' },
{ target: 'www.nvidia.com:443', sni: 'www.nvidia.com' },
{ target: 'www.amd.com:443', sni: 'www.amd.com' },
{ target: 'www.intel.com:443', sni: 'www.intel.com' },
{ target: 'www.tesla.com:443', sni: 'www.tesla.com' },
{ target: 'www.sony.com:443', sni: 'www.sony.com' }
];
/**
* Returns a random Reality target configuration from the predefined list
* @returns {Object} Object with target and sni properties
*/
function getRandomRealityTarget() {
const randomIndex = Math.floor(Math.random() * REALITY_TARGETS.length);
const selected = REALITY_TARGETS[randomIndex];
// Return a copy to avoid reference issues
return {
target: selected.target,
sni: selected.sni
};
}
// List of popular services for VLESS Reality Target/SNI randomization
export const REALITY_TARGETS = [
{ target: 'www.amazon.com:443', sni: 'www.amazon.com' },
{ target: 'aws.amazon.com:443', sni: 'aws.amazon.com' },
{ target: 'www.oracle.com:443', sni: 'www.oracle.com' },
{ target: 'www.nvidia.com:443', sni: 'www.nvidia.com' },
{ target: 'www.amd.com:443', sni: 'www.amd.com' },
{ target: 'www.intel.com:443', sni: 'www.intel.com' },
{ target: 'www.sony.com:443', sni: 'www.sony.com' }
];
/**
* Returns a random Reality target configuration from the predefined list
* @returns {Object} Object with target and sni properties
*/
export function getRandomRealityTarget() {
const randomIndex = Math.floor(Math.random() * REALITY_TARGETS.length);
const selected = REALITY_TARGETS[randomIndex];
// Return a copy to avoid reference issues
return {
target: selected.target,
sni: selected.sni
};
}
@@ -1,4 +1,11 @@
class AllSetting {
// Mirrors web/assets/js/model/setting.js — every field on this class is
// round-tripped through `/panel/setting/all` and `/panel/setting/update`,
// so adding a field here without a matching Go-side change will silently
// drop it on save. Defaults match the legacy panel.
import { ObjectUtil } from '@/utils';
export class AllSetting {
constructor(data) {
this.webListen = "";
@@ -43,6 +50,7 @@ class AllSetting {
this.subDomain = "";
this.externalTrafficInformEnable = false;
this.externalTrafficInformURI = "";
this.restartXrayOnClientDisable = true;
this.subCertFile = "";
this.subKeyFile = "";
this.subUpdates = 12;
+71
View File
@@ -0,0 +1,71 @@
import { NumberFormatter } from '@/utils';
export class CurTotal {
constructor(current, total) {
this.current = current;
this.total = total;
}
get percent() {
if (this.total === 0) return 0;
return NumberFormatter.toFixed((this.current / this.total) * 100, 2);
}
get color() {
// Match AD-Vue 4's semantic palette so the gauges fit the
// global blue/gold/red theme instead of the legacy teal/orange.
const p = this.percent;
if (p < 80) return '#1677ff'; // primary
if (p < 90) return '#faad14'; // warning
return '#ff4d4f'; // danger
}
}
const XRAY_STATE_COLORS = {
running: 'green',
stop: 'orange',
error: 'red',
};
export class Status {
constructor(data) {
this.cpu = new CurTotal(0, 0);
this.cpuCores = 0;
this.logicalPro = 0;
this.cpuSpeedMhz = 0;
this.disk = new CurTotal(0, 0);
this.loads = [0, 0, 0];
this.mem = new CurTotal(0, 0);
this.netIO = { up: 0, down: 0 };
this.netTraffic = { sent: 0, recv: 0 };
this.publicIP = { ipv4: 0, ipv6: 0 };
this.swap = new CurTotal(0, 0);
this.tcpCount = 0;
this.udpCount = 0;
this.uptime = 0;
this.appUptime = 0;
this.appStats = { threads: 0, mem: 0, uptime: 0 };
this.xray = { state: 'stop', errorMsg: '', version: '', color: '' };
if (data == null) return;
this.cpu = new CurTotal(data.cpu, 100);
this.cpuCores = data.cpuCores;
this.logicalPro = data.logicalPro;
this.cpuSpeedMhz = data.cpuSpeedMhz;
this.disk = new CurTotal(data.disk?.current ?? 0, data.disk?.total ?? 0);
this.loads = (data.loads || [0, 0, 0]).map((v) => NumberFormatter.toFixed(v, 2));
this.mem = new CurTotal(data.mem?.current ?? 0, data.mem?.total ?? 0);
this.netIO = data.netIO ?? this.netIO;
this.netTraffic = data.netTraffic ?? this.netTraffic;
this.publicIP = data.publicIP ?? this.publicIP;
this.swap = new CurTotal(data.swap?.current ?? 0, data.swap?.total ?? 0);
this.tcpCount = data.tcpCount ?? 0;
this.udpCount = data.udpCount ?? 0;
this.uptime = data.uptime ?? 0;
this.appUptime = data.appUptime ?? 0;
this.appStats = data.appStats ?? this.appStats;
this.xray = { ...this.xray, ...(data.xray || {}) };
this.xray.color = XRAY_STATE_COLORS[this.xray.state] ?? 'gray';
}
}
@@ -0,0 +1,273 @@
<script setup>
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { SyncOutlined } from '@ant-design/icons-vue';
import { HttpUtil, RandomUtil, SizeFormatter } from '@/utils';
const { t } = useI18n();
import {
Inbound,
Protocols,
USERS_SECURITY,
TLS_FLOW_CONTROL,
} from '@/models/inbound.js';
import DateTimePicker from '@/components/DateTimePicker.vue';
// Bulk-add up to 500 clients in one go. The legacy panel offers five
// generation modes — this component preserves them all:
// 0: Random — N fully-random emails (no prefix)
// 1: Random+Prefix — N random emails preceded by `prefix`
// 2: Random+Prefix+Num — emails like `<rand><prefix><num>` for num in [first..last]
// 3: Random+Prefix+Num+Postfix — same + appended postfix
// 4: Prefix+Num+Postfix — no random part, just `<prefix><num><postfix>`
const props = defineProps({
open: { type: Boolean, default: false },
dbInbound: { type: Object, default: null },
subEnable: { type: Boolean, default: false },
tgBotEnable: { type: Boolean, default: false },
ipLimitEnable: { type: Boolean, default: false },
});
const emit = defineEmits(['update:open', 'saved']);
const SECURITY_OPTIONS = Object.values(USERS_SECURITY);
const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
// === Reactive form state ===========================================
// Cloned inbound (so canEnableTlsFlow() works).
const inbound = ref(null);
const saving = ref(false);
const delayedStart = ref(false);
const form = reactive({
emailMethod: 0,
firstNum: 1,
lastNum: 1,
emailPrefix: '',
emailPostfix: '',
quantity: 1,
security: USERS_SECURITY.AUTO,
flow: '',
subId: '',
tgId: 0,
limitIp: 0,
totalGB: 0,
expiryTime: 0, // ms epoch; negative => delayed start days
reset: 0,
});
const expiryDate = computed({
get: () => (form.expiryTime > 0 ? dayjs(form.expiryTime) : null),
set: (next) => { form.expiryTime = next ? next.valueOf() : 0; },
});
const delayedExpireDays = computed({
get: () => (form.expiryTime < 0 ? form.expiryTime / -86400000 : 0),
set: (days) => { form.expiryTime = -86400000 * (days || 0); },
});
watch(() => props.open, (next) => {
if (!next) return;
if (!props.dbInbound) return;
inbound.value = Inbound.fromJson(props.dbInbound.toInbound().toJson());
// Reset all form fields on every open — bulk add is intentionally
// stateless between sessions (legacy resets on .show()).
form.emailMethod = 0;
form.firstNum = 1;
form.lastNum = 1;
form.emailPrefix = '';
form.emailPostfix = '';
form.quantity = 1;
form.security = USERS_SECURITY.AUTO;
form.flow = '';
form.subId = '';
form.tgId = 0;
form.limitIp = 0;
form.totalGB = 0;
form.expiryTime = 0;
form.reset = 0;
delayedStart.value = false;
});
function close() {
emit('update:open', false);
}
function makeNewClient(parsed) {
switch (parsed.protocol) {
case Protocols.VMESS: return new Inbound.VmessSettings.VMESS();
case Protocols.VLESS: return new Inbound.VLESSSettings.VLESS();
case Protocols.TROJAN: return new Inbound.TrojanSettings.Trojan();
case Protocols.SHADOWSOCKS: {
const method = parsed.settings.shadowsockses[0]?.method || parsed.settings.method;
return new Inbound.ShadowsocksSettings.Shadowsocks(method);
}
case Protocols.HYSTERIA: return new Inbound.HysteriaSettings.Hysteria();
default: return null;
}
}
function buildClients() {
if (!inbound.value) return [];
const out = [];
const method = form.emailMethod;
let start;
let end;
if (method > 1) {
start = form.firstNum;
end = form.lastNum + 1;
} else {
start = 0;
end = form.quantity;
}
const prefix = method > 0 && form.emailPrefix.length > 0 ? form.emailPrefix : '';
const useNum = method > 1;
const postfix = method > 2 && form.emailPostfix.length > 0 ? form.emailPostfix : '';
for (let i = start; i < end; i++) {
const c = makeNewClient(inbound.value);
if (!c) continue;
if (method === 4) c.email = '';
c.email += useNum ? prefix + String(i) + postfix : prefix + postfix;
if (form.subId.length > 0) c.subId = form.subId;
c.tgId = form.tgId;
c.security = form.security;
c.limitIp = form.limitIp;
// Use the clien's totalGB setter (ms epoch and bytes already handled
// identically for bulk and single client paths).
c.totalGB = Math.round((form.totalGB || 0) * SizeFormatter.ONE_GB);
c.expiryTime = form.expiryTime;
if (inbound.value.canEnableTlsFlow()) c.flow = form.flow;
c.reset = form.reset;
out.push(c);
}
return out;
}
async function submit() {
const clients = buildClients();
if (clients.length === 0) return;
saving.value = true;
try {
const payload = {
id: props.dbInbound.id,
// Clients all serialize via toString() — same shape the single-
// client modal posts. Joining with `,` lets the Go side parse the
// outer array directly.
settings: `{"clients": [${clients.map((c) => c.toString()).join(',')}]}`,
};
const msg = await HttpUtil.post('/panel/api/inbounds/addClient', payload);
if (msg?.success) {
emit('saved');
close();
}
} finally {
saving.value = false;
}
}
</script>
<template>
<a-modal :open="open" :title="t('pages.client.bulk')" :ok-text="t('create')" :cancel-text="t('close')"
:confirm-loading="saving" :mask-closable="false" @ok="submit" @cancel="close">
<a-form v-if="inbound" :colon="false" :label-col="{ sm: { span: 8 } }" :wrapper-col="{ sm: { span: 14 } }">
<a-form-item :label="t('pages.client.method')">
<a-select v-model:value="form.emailMethod">
<a-select-option :value="0">Random</a-select-option>
<a-select-option :value="1">Random + Prefix</a-select-option>
<a-select-option :value="2">Random + Prefix + Num</a-select-option>
<a-select-option :value="3">Random + Prefix + Num + Postfix</a-select-option>
<a-select-option :value="4">Prefix + Num + Postfix</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="form.emailMethod > 1" :label="t('pages.client.first')">
<a-input-number v-model:value="form.firstNum" :min="1" />
</a-form-item>
<a-form-item v-if="form.emailMethod > 1" :label="t('pages.client.last')">
<a-input-number v-model:value="form.lastNum" :min="form.firstNum" />
</a-form-item>
<a-form-item v-if="form.emailMethod > 0" :label="t('pages.client.prefix')">
<a-input v-model:value="form.emailPrefix" />
</a-form-item>
<a-form-item v-if="form.emailMethod > 2" :label="t('pages.client.postfix')">
<a-input v-model:value="form.emailPostfix" />
</a-form-item>
<a-form-item v-if="form.emailMethod < 2" :label="t('pages.client.clientCount')">
<a-input-number v-model:value="form.quantity" :min="1" :max="500" />
</a-form-item>
<a-form-item v-if="inbound.protocol === Protocols.VMESS" :label="t('security')">
<a-select v-model:value="form.security">
<a-select-option v-for="key in SECURITY_OPTIONS" :key="key" :value="key">{{ key }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="inbound.canEnableTlsFlow()" label="Flow">
<a-select v-model:value="form.flow">
<a-select-option value="">{{ t('none') }}</a-select-option>
<a-select-option v-for="key in FLOW_OPTIONS" :key="key" :value="key">{{ key }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="subEnable">
<template #label>
{{ t('subscription.title') }}
<SyncOutlined class="random-icon" @click="form.subId = RandomUtil.randomLowerAndNum(16)" />
</template>
<a-input v-model:value="form.subId" />
</a-form-item>
<a-form-item v-if="tgBotEnable" label="Telegram ID">
<a-input-number v-model:value="form.tgId" :min="0" :style="{ width: '50%' }" />
</a-form-item>
<a-form-item v-if="ipLimitEnable" :label="t('pages.inbounds.IPLimit')">
<a-input-number v-model:value="form.limitIp" :min="0" />
</a-form-item>
<a-form-item>
<template #label>
<a-tooltip :title="t('pages.inbounds.meansNoLimit')">{{ t('pages.inbounds.totalFlow') }}</a-tooltip>
</template>
<a-input-number v-model:value="form.totalGB" :min="0" :step="0.1" />
</a-form-item>
<a-form-item :label="t('pages.client.delayedStart')">
<a-switch v-model:checked="delayedStart" @click="form.expiryTime = 0" />
</a-form-item>
<a-form-item v-if="delayedStart" :label="t('pages.client.expireDays')">
<a-input-number v-model:value="delayedExpireDays" :min="0" />
</a-form-item>
<a-form-item v-else>
<template #label>
<a-tooltip :title="t('pages.inbounds.leaveBlankToNeverExpire')">{{ t('pages.inbounds.expireDate')
}}</a-tooltip>
</template>
<DateTimePicker v-model:value="expiryDate" />
</a-form-item>
<a-form-item v-if="form.expiryTime !== 0">
<template #label>
<a-tooltip :title="t('pages.client.renewDesc')">{{ t('pages.client.renew') }}</a-tooltip>
</template>
<a-input-number v-model:value="form.reset" :min="0" />
</a-form-item>
</a-form>
</a-modal>
</template>
<style scoped>
.random-icon {
margin-left: 4px;
cursor: pointer;
color: var(--ant-primary-color, #1890ff);
}
</style>
@@ -0,0 +1,394 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import { SyncOutlined, RetweetOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import {
HttpUtil,
RandomUtil,
SizeFormatter,
ColorUtils,
} from '@/utils';
import { Inbound, Protocols, USERS_SECURITY, TLS_FLOW_CONTROL } from '@/models/inbound.js';
import DateTimePicker from '@/components/DateTimePicker.vue';
const { t } = useI18n();
// Add OR edit a single client on a multi-user inbound (VMess / VLess /
// Trojan / Shadowsocks-multi / Hysteria). The legacy panel routes both
// flows through the same modal — same here.
//
// On submit we serialize the client via its toString() (which is just
// JSON.stringify of toJson()) and post it inside a one-element clients
// array so the Go side reuses the same parsing path as the inbound
// settings update.
const props = defineProps({
open: { type: Boolean, default: false },
mode: { type: String, default: 'add', validator: (v) => ['add', 'edit'].includes(v) },
dbInbound: { type: Object, default: null },
clientIndex: { type: Number, default: null },
// Sidecar config from the inbounds page — controls visibility of
// the Subscription, Telegram, and IP-limit fields.
subEnable: { type: Boolean, default: false },
tgBotEnable: { type: Boolean, default: false },
ipLimitEnable: { type: Boolean, default: false },
trafficDiff: { type: Number, default: 0 },
});
const emit = defineEmits(['update:open', 'saved']);
// === Reactive draft =================================================
const inbound = ref(null);
const client = ref(null);
const oldClientId = ref('');
const clientStats = ref(null);
const saving = ref(false);
const delayedStart = ref(false);
const SECURITY_OPTIONS = Object.values(USERS_SECURITY);
const FLOW_OPTIONS = Object.values(TLS_FLOW_CONTROL);
const protocol = computed(() => inbound.value?.protocol);
const isVmessOrVless = computed(() =>
protocol.value === Protocols.VMESS || protocol.value === Protocols.VLESS,
);
const isTrojanOrSS = computed(() =>
protocol.value === Protocols.TROJAN || protocol.value === Protocols.SHADOWSOCKS,
);
const expiryDate = computed({
get: () => (client.value?.expiryTime > 0 ? dayjs(client.value.expiryTime) : null),
set: (next) => { if (client.value) client.value.expiryTime = next ? next.valueOf() : 0; },
});
const delayedExpireDays = computed({
get: () => {
if (!client.value || client.value.expiryTime >= 0) return 0;
return client.value.expiryTime / -86400000;
},
set: (days) => {
if (!client.value) return;
client.value.expiryTime = -86400000 * (days || 0);
},
});
const totalGB = computed({
get: () => {
if (!client.value || !client.value.totalGB) return 0;
return Math.round((client.value.totalGB / SizeFormatter.ONE_GB) * 100) / 100;
},
set: (gb) => {
if (!client.value) return;
client.value.totalGB = Math.round((gb || 0) * SizeFormatter.ONE_GB);
},
});
const isExpired = computed(() => {
if (props.mode !== 'edit' || !client.value) return false;
return client.value.expiryTime > 0 && client.value.expiryTime < Date.now();
});
const isTrafficExhausted = computed(() => {
if (!clientStats.value || clientStats.value.total <= 0) return false;
return clientStats.value.up + clientStats.value.down >= clientStats.value.total;
});
function getClientId(proto, c) {
switch (proto) {
case Protocols.TROJAN: return c.password;
case Protocols.SHADOWSOCKS: return c.email;
case Protocols.HYSTERIA: return c.auth;
default: return c.id;
}
}
function makeNewClient(proto, parsed) {
switch (proto) {
case Protocols.VMESS: return new Inbound.VmessSettings.VMESS();
case Protocols.VLESS: return new Inbound.VLESSSettings.VLESS();
case Protocols.TROJAN: return new Inbound.TrojanSettings.Trojan();
case Protocols.SHADOWSOCKS: {
const method = parsed.settings.method;
return new Inbound.ShadowsocksSettings.Shadowsocks(
method,
RandomUtil.randomShadowsocksPassword(method),
);
}
case Protocols.HYSTERIA: return new Inbound.HysteriaSettings.Hysteria();
default: return null;
}
}
watch(() => props.open, (next) => {
if (!next) return;
if (!props.dbInbound) return;
const parsed = Inbound.fromJson(props.dbInbound.toInbound().toJson());
inbound.value = parsed;
delayedStart.value = false;
if (props.mode === 'edit') {
const idx = props.clientIndex ?? 0;
client.value = parsed.clients[idx];
if (client.value && client.value.expiryTime < 0) delayedStart.value = true;
oldClientId.value = getClientId(parsed.protocol, client.value);
} else {
const c = makeNewClient(parsed.protocol, parsed);
if (c) parsed.clients.push(c);
client.value = parsed.clients[parsed.clients.length - 1];
oldClientId.value = '';
}
clientStats.value = (props.dbInbound.clientStats || []).find(
(s) => s.email === client.value?.email,
) || null;
});
function close() {
emit('update:open', false);
}
function randomEmail() {
if (client.value) client.value.email = RandomUtil.randomLowerAndNum(9);
}
function randomId() {
if (client.value) client.value.id = RandomUtil.randomUUID();
}
function randomPassword() {
if (!client.value || !inbound.value) return;
if (inbound.value.protocol === Protocols.SHADOWSOCKS) {
client.value.password = RandomUtil.randomShadowsocksPassword(
inbound.value.settings.method,
);
} else {
client.value.password = RandomUtil.randomSeq(10);
}
}
function randomAuth() {
if (client.value) client.value.auth = RandomUtil.randomSeq(10);
}
function randomSubId() {
if (client.value) client.value.subId = RandomUtil.randomLowerAndNum(16);
}
const clientIpsText = ref('');
async function loadClientIps() {
if (!client.value?.email) return;
const msg = await HttpUtil.post(`/panel/api/inbounds/clientIps/${client.value.email}`);
if (!msg?.success) {
clientIpsText.value = msg?.obj || '';
return;
}
let ips = msg.obj;
if (typeof ips === 'string' && ips.startsWith('[') && ips.endsWith(']')) {
try {
const parsed = JSON.parse(ips);
ips = Array.isArray(parsed) ? parsed.join('\n') : ips;
} catch (_e) {
// leave as raw
}
}
clientIpsText.value = ips || '';
}
async function clearClientIps() {
if (!client.value?.email) return;
const msg = await HttpUtil.post(`/panel/api/inbounds/clearClientIps/${client.value.email}`);
if (msg?.success) clientIpsText.value = '';
}
async function resetClientTraffic() {
if (!clientStats.value || !client.value?.email) return;
const msg = await HttpUtil.post(
`/panel/api/inbounds/${props.dbInbound.id}/resetClientTraffic/${client.value.email}`,
);
if (msg?.success) {
clientStats.value.up = 0;
clientStats.value.down = 0;
}
}
async function submit() {
if (!client.value || !inbound.value) return;
saving.value = true;
try {
const payload = {
id: props.dbInbound.id,
settings: `{"clients": [${client.value.toString()}]}`,
};
const url = props.mode === 'edit'
? `/panel/api/inbounds/updateClient/${oldClientId.value}`
: '/panel/api/inbounds/addClient';
const msg = await HttpUtil.post(url, payload);
if (msg?.success) {
emit('saved');
close();
}
} finally {
saving.value = false;
}
}
const title = computed(() =>
props.mode === 'edit' ? t('pages.client.edit') : t('pages.client.add'),
);
</script>
<template>
<a-modal :open="open" :title="title"
:ok-text="mode === 'edit' ? t('pages.client.submitEdit') : t('pages.client.submitAdd')" :cancel-text="t('close')"
:confirm-loading="saving" :mask-closable="false" @ok="submit" @cancel="close">
<a-tag v-if="mode === 'edit' && (isExpired || isTrafficExhausted)" color="red" class="status-banner">
{{ t('depleted') }}
</a-tag>
<a-form v-if="client && inbound" layout="horizontal" :colon="false" :label-col="{ sm: { span: 8 } }"
:wrapper-col="{ sm: { span: 14 } }">
<a-form-item :label="t('enable')">
<a-switch v-model:checked="client.enable" />
</a-form-item>
<a-form-item>
<template #label>
{{ t('pages.inbounds.email') }}
<SyncOutlined class="random-icon" @click="randomEmail" />
</template>
<a-input v-model:value="client.email" />
</a-form-item>
<a-form-item v-if="isTrojanOrSS">
<template #label>
{{ t('password') }}
<SyncOutlined class="random-icon" @click="randomPassword" />
</template>
<a-input v-model:value="client.password" />
</a-form-item>
<a-form-item v-if="protocol === Protocols.HYSTERIA">
<template #label>
{{ t('password') }}
<SyncOutlined class="random-icon" @click="randomAuth" />
</template>
<a-input v-model:value="client.auth" />
</a-form-item>
<a-form-item v-if="isVmessOrVless">
<template #label>
ID
<SyncOutlined class="random-icon" @click="randomId" />
</template>
<a-input v-model:value="client.id" />
</a-form-item>
<a-form-item v-if="protocol === Protocols.VMESS" :label="t('security')">
<a-select v-model:value="client.security">
<a-select-option v-for="key in SECURITY_OPTIONS" :key="key" :value="key">
{{ key }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="client.email && subEnable">
<template #label>
{{ t('subscription.title') }}
<SyncOutlined class="random-icon" @click="randomSubId" />
</template>
<a-input v-model:value="client.subId" />
</a-form-item>
<a-form-item v-if="client.email && tgBotEnable" label="Telegram ID">
<a-input-number v-model:value="client.tgId" :min="0" :style="{ width: '50%' }" />
</a-form-item>
<a-form-item v-if="client.email" :label="t('comment')">
<a-input v-model:value="client.comment" />
</a-form-item>
<a-form-item v-if="ipLimitEnable" :label="t('pages.inbounds.IPLimit')">
<a-input-number v-model:value="client.limitIp" :min="0" />
</a-form-item>
<a-form-item v-if="ipLimitEnable && client.limitIp > 0 && client.email && mode === 'edit'"
:label="t('pages.inbounds.IPLimitlog')">
<a-textarea v-model:value="clientIpsText" readonly :placeholder="t('pages.inbounds.IPLimitlogDesc')"
:auto-size="{ minRows: 3, maxRows: 8 }" @click="loadClientIps" />
<a-button type="link" size="small" danger @click="clearClientIps">
<template #icon>
<DeleteOutlined />
</template>
{{ t('pages.inbounds.IPLimitlogclear') }}
</a-button>
</a-form-item>
<a-form-item v-if="inbound.canEnableTlsFlow()" label="Flow">
<a-select v-model:value="client.flow">
<a-select-option value="">{{ t('none') }}</a-select-option>
<a-select-option v-for="key in FLOW_OPTIONS" :key="key" :value="key">
{{ key }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item v-if="protocol === Protocols.VLESS" label="Reverse tag">
<a-input v-model:value="client.reverseTag" placeholder="Optional reverse tag" />
</a-form-item>
<a-form-item>
<template #label>
<a-tooltip :title="t('pages.inbounds.meansNoLimit')">{{ t('pages.inbounds.totalFlow') }}</a-tooltip>
</template>
<a-input-number v-model:value="totalGB" :min="0" :step="0.1" />
</a-form-item>
<a-form-item v-if="mode === 'edit' && clientStats" :label="t('usage')">
<a-tag :color="ColorUtils.clientUsageColor(clientStats, trafficDiff)">
{{ SizeFormatter.sizeFormat(clientStats.up) }} /
{{ SizeFormatter.sizeFormat(clientStats.down) }}
({{ SizeFormatter.sizeFormat(clientStats.up + clientStats.down) }})
</a-tag>
<a-tooltip v-if="client.email" :title="t('pages.inbounds.resetTraffic')">
<RetweetOutlined class="action-icon" @click="resetClientTraffic" />
</a-tooltip>
</a-form-item>
<a-form-item :label="t('pages.client.delayedStart')">
<a-switch v-model:checked="delayedStart" @click="client.expiryTime = 0" />
</a-form-item>
<a-form-item v-if="delayedStart" :label="t('pages.client.expireDays')">
<a-input-number v-model:value="delayedExpireDays" :min="0" />
</a-form-item>
<a-form-item v-else>
<template #label>
<a-tooltip :title="t('pages.inbounds.leaveBlankToNeverExpire')">{{ t('pages.inbounds.expireDate')
}}</a-tooltip>
</template>
<DateTimePicker v-model:value="expiryDate" />
<a-tag v-if="mode === 'edit' && isExpired" color="red">{{ t('depleted') }}</a-tag>
</a-form-item>
<a-form-item v-if="client.expiryTime !== 0">
<template #label>
<a-tooltip :title="t('pages.client.renewDesc')">{{ t('pages.client.renew') }}</a-tooltip>
</template>
<a-input-number v-model:value="client.reset" :min="0" />
</a-form-item>
</a-form>
</a-modal>
</template>
<style scoped>
.status-banner {
display: block;
margin-bottom: 10px;
text-align: center;
}
.random-icon,
.action-icon {
margin-left: 4px;
cursor: pointer;
color: var(--ant-primary-color, #1890ff);
}
</style>
@@ -0,0 +1,640 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
EditOutlined,
InfoCircleOutlined,
QrcodeOutlined,
RetweetOutlined,
DeleteOutlined,
EllipsisOutlined,
} from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
import { SizeFormatter, IntlUtil, ColorUtils } from '@/utils';
import InfinityIcon from '@/components/InfinityIcon.vue';
import { useDatepicker } from '@/composables/useDatepicker.js';
const { datepicker } = useDatepicker();
const { t } = useI18n();
// Per-inbound expand-row content. CSS-grid layout (not a nested
// <a-table>) so it sits flush inside the parent's expanded cell.
// No API calls here — events bubble to the parent's modals.
const props = defineProps({
dbInbound: { type: Object, required: true },
isMobile: { type: Boolean, default: false },
trafficDiff: { type: Number, default: 0 },
expireDiff: { type: Number, default: 0 },
onlineClients: { type: Array, default: () => [] },
lastOnlineMap: { type: Object, default: () => ({}) },
isDarkTheme: { type: Boolean, default: false },
});
const emit = defineEmits([
'edit-client',
'qrcode-client',
'info-client',
'reset-traffic-client',
'delete-client',
'toggle-enable-client',
]);
const inbound = computed(() => props.dbInbound.toInbound());
const clients = computed(() => inbound.value?.clients || []);
// === Per-client stats lookup =======================================
const statsMap = computed(() => {
const m = new Map();
for (const cs of (props.dbInbound.clientStats || [])) m.set(cs.email, cs);
return m;
});
function statsFor(email) {
return email ? statsMap.value.get(email) : null;
}
function getUp(email) { return statsFor(email)?.up || 0; }
function getDown(email) { return statsFor(email)?.down || 0; }
function getSum(email) { const s = statsFor(email); return s ? s.up + s.down : 0; }
function getRem(email) {
const s = statsFor(email);
if (!s) return 0;
const r = s.total - s.up - s.down;
return r > 0 ? r : 0;
}
function getAllTime(email) {
const s = statsFor(email);
if (!s) return 0;
// allTime is the cumulative-historical counter; never let it dip
// below up+down (manual edits / partial migrations can push it under).
const current = (s.up || 0) + (s.down || 0);
return s.allTime > current ? s.allTime : current;
}
function isClientDepleted(email) {
const s = statsFor(email);
if (!s) return false;
const total = s.total ?? 0;
const used = (s.up ?? 0) + (s.down ?? 0);
if (total > 0 && used >= total) return true;
const exp = s.expiryTime ?? 0;
if (exp > 0 && Date.now() >= exp) return true;
return false;
}
function isClientOnline(email) {
return !!email && props.onlineClients.includes(email);
}
function lastOnlineLabel(email) {
const ts = props.lastOnlineMap[email];
if (!ts) return '-';
return IntlUtil.formatDate(ts, datepicker.value);
}
function statsProgress(email) {
const s = statsFor(email);
if (!s) return 0;
if (s.total === 0) return 100;
return (100 * (s.down + s.up)) / s.total;
}
function expireProgress(expTime, reset) {
const now = Date.now();
const remainedSec = expTime < 0 ? -expTime / 1000 : (expTime - now) / 1000;
const resetSec = reset * 86400;
if (remainedSec >= resetSec) return 0;
return 100 * (1 - remainedSec / resetSec);
}
function clientStatsColor(email) {
return ColorUtils.clientUsageColor(statsFor(email), props.trafficDiff);
}
function statsExpColor(email) {
// AD-Vue 4 semantic palette mirrors ColorUtils.* so the badge dot
// matches the row's traffic/expiry tags.
const PURPLE = '#722ed1', SUCCESS = '#52c41a', WARN = '#faad14', DANGER = '#ff4d4f';
if (!email) return PURPLE;
const s = statsFor(email);
if (!s) return PURPLE;
const a = ColorUtils.usageColor(s.down + s.up, props.trafficDiff, s.total);
const b = ColorUtils.usageColor(Date.now(), props.expireDiff, s.expiryTime);
if (a === 'red' || b === 'red') return DANGER;
if (a === 'orange' || b === 'orange') return WARN;
if (a === 'green' || b === 'green') return SUCCESS;
return PURPLE;
}
const isRemovable = computed(() => clients.value.length > 1);
function totalGbDisplay(client) {
if (!client.totalGB || client.totalGB <= 0) return '';
return `${Math.round((client.totalGB / 1073741824) * 100) / 100} GB`;
}
const isUnlimitedTotal = (client) => !client.totalGB || client.totalGB <= 0;
function statusBadgeColor(client) {
if (!client.enable) return props.isDarkTheme ? '#2c3950' : '#bcbcbc';
return statsExpColor(client.email);
}
// === Action confirms ==============================================
function confirmReset(client) {
Modal.confirm({
title: `${t('pages.inbounds.resetTraffic')}${client.email}`,
content: t('pages.inbounds.resetTrafficContent'),
okText: t('reset'),
cancelText: t('cancel'),
onOk: () => emit('reset-traffic-client', { dbInbound: props.dbInbound, client }),
});
}
function confirmDelete(client) {
Modal.confirm({
title: `${t('pages.inbounds.deleteClient')}${client.email}`,
content: t('pages.inbounds.deleteClientContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: () => emit('delete-client', { dbInbound: props.dbInbound, client }),
});
}
// Stable row key for v-for — falls back through email/id/password
// because not every protocol fills the same field.
function rowKey(client) {
return client.email || client.id || client.password || JSON.stringify(client);
}
</script>
<template>
<div class="client-list" :class="{ 'is-mobile': isMobile, 'is-dark': isDarkTheme }">
<!-- ====================== Desktop: grid table ===================== -->
<template v-if="!isMobile">
<div class="client-row client-list-header">
<div class="cell cell-actions">{{ t('pages.settings.actions') }}</div>
<div class="cell cell-enable">{{ t('enable') }}</div>
<div class="cell cell-online">{{ t('online') }}</div>
<div class="cell cell-client">{{ t('pages.inbounds.client') }}</div>
<div class="cell cell-traffic">{{ t('pages.inbounds.traffic') }}</div>
<div class="cell cell-alltime">{{ t('pages.inbounds.allTimeTraffic') }}</div>
<div class="cell cell-expiry">{{ t('pages.inbounds.expireDate') }}</div>
</div>
<div v-for="client in clients" :key="rowKey(client)" class="client-row">
<div class="cell cell-actions">
<a-tooltip v-if="dbInbound.hasLink()" :title="t('qrCode')">
<QrcodeOutlined class="row-icon" @click="emit('qrcode-client', { dbInbound, client })" />
</a-tooltip>
<a-tooltip :title="t('edit')">
<EditOutlined class="row-icon" @click="emit('edit-client', { dbInbound, client })" />
</a-tooltip>
<a-tooltip :title="t('info')">
<InfoCircleOutlined class="row-icon" @click="emit('info-client', { dbInbound, client })" />
</a-tooltip>
<a-tooltip v-if="client.email" :title="t('pages.inbounds.resetTraffic')">
<RetweetOutlined class="row-icon" @click="confirmReset(client)" />
</a-tooltip>
<a-tooltip v-if="isRemovable" :title="t('delete')">
<DeleteOutlined class="row-icon danger" @click="confirmDelete(client)" />
</a-tooltip>
</div>
<div class="cell cell-enable">
<a-switch :checked="client.enable" size="small"
@change="(next) => emit('toggle-enable-client', { dbInbound, client, next })" />
</div>
<div class="cell cell-online">
<a-popover>
<template #content>{{ t('lastOnline') }}: {{ lastOnlineLabel(client.email) }}</template>
<a-tag v-if="client.enable && isClientOnline(client.email)" color="green">{{ t('online') }}</a-tag>
<a-tag v-else>{{ t('offline') }}</a-tag>
</a-popover>
</div>
<div class="cell cell-client">
<a-tooltip>
<template #title>
<template v-if="isClientDepleted(client.email)">{{ t('depleted') }}</template>
<template v-else-if="!client.enable">{{ t('disabled') }}</template>
<template v-else-if="isClientOnline(client.email)">{{ t('online') }}</template>
<template v-else>{{ t('offline') }}</template>
</template>
<a-badge :color="statusBadgeColor(client)" />
</a-tooltip>
<div class="client-id-stack">
<a-tooltip :title="client.email">
<span class="client-email">{{ client.email }}</span>
</a-tooltip>
<span v-if="client.comment && client.comment.trim()" class="client-comment">
{{ client.comment.length > 50 ? client.comment.substring(0, 47) + '…' : client.comment }}
</span>
</div>
</div>
<div class="cell cell-traffic">
<a-popover>
<template v-if="client.email" #content>
<table cellpadding="2">
<tbody>
<tr>
<td> {{ SizeFormatter.sizeFormat(getUp(client.email)) }}</td>
<td> {{ SizeFormatter.sizeFormat(getDown(client.email)) }}</td>
</tr>
<tr v-if="client.totalGB > 0">
<td>{{ t('remained') }}</td>
<td>{{ SizeFormatter.sizeFormat(getRem(client.email)) }}</td>
</tr>
</tbody>
</table>
</template>
<div class="usage-bar">
<span class="usage-text">{{ SizeFormatter.sizeFormat(getSum(client.email)) }}</span>
<a-progress v-if="!client.enable" :stroke-color="isDarkTheme ? 'rgb(72,84,105)' : '#bcbcbc'"
:show-info="false" :percent="statsProgress(client.email)" size="small" />
<a-progress v-else-if="client.totalGB > 0" :stroke-color="clientStatsColor(client.email)"
:show-info="false" :status="isClientDepleted(client.email) ? 'exception' : ''"
:percent="statsProgress(client.email)" size="small" />
<a-progress v-else :show-info="false" :percent="100" stroke-color="#722ed1" size="small" />
<span class="usage-text">
<InfinityIcon v-if="isUnlimitedTotal(client)" />
<template v-else>{{ totalGbDisplay(client) }}</template>
</span>
</div>
</a-popover>
</div>
<div class="cell cell-alltime">
<a-tag>{{ SizeFormatter.sizeFormat(getAllTime(client.email)) }}</a-tag>
</div>
<div class="cell cell-expiry">
<template v-if="client.expiryTime !== 0 && client.reset > 0">
<a-popover>
<template #content>
<span v-if="client.expiryTime < 0">{{ t('pages.client.delayedStart') }}</span>
<span v-else>{{ IntlUtil.formatDate(client.expiryTime, datepicker) }}</span>
</template>
<div class="usage-bar">
<span class="usage-text">{{ IntlUtil.formatRelativeTime(client.expiryTime) }}</span>
<a-progress :show-info="false" :status="isClientDepleted(client.email) ? 'exception' : ''"
:percent="expireProgress(client.expiryTime, client.reset)" size="small" />
<span class="usage-text">{{ client.reset }}d</span>
</div>
</a-popover>
</template>
<a-popover v-else-if="client.expiryTime !== 0">
<template #content>
<span v-if="client.expiryTime < 0">{{ t('pages.client.delayedStart') }}</span>
<span v-else>{{ IntlUtil.formatDate(client.expiryTime) }}</span>
</template>
<a-tag :style="{ minWidth: '50px', border: 'none' }"
:color="ColorUtils.userExpiryColor(expireDiff, client, isDarkTheme)">
{{ IntlUtil.formatRelativeTime(client.expiryTime) }}
</a-tag>
</a-popover>
<a-tag v-else :color="ColorUtils.userExpiryColor(expireDiff, client, isDarkTheme)" :style="{ border: 'none' }"
class="infinite-tag">
<InfinityIcon />
</a-tag>
</div>
</div>
</template>
<!-- ====================== Mobile: card list ======================= -->
<template v-else>
<div v-for="client in clients" :key="rowKey(client)" class="client-card">
<div class="client-card-head">
<a-tooltip>
<template #title>
<template v-if="isClientDepleted(client.email)">{{ t('depleted') }}</template>
<template v-else-if="!client.enable">{{ t('disabled') }}</template>
<template v-else-if="isClientOnline(client.email)">{{ t('online') }}</template>
<template v-else>{{ t('offline') }}</template>
</template>
<a-badge :color="statusBadgeColor(client)" />
</a-tooltip>
<a-tooltip :title="client.email">
<span class="client-email">{{ client.email }}</span>
</a-tooltip>
<div class="client-card-actions">
<a-switch :checked="client.enable" size="small"
@change="(next) => emit('toggle-enable-client', { dbInbound, client, next })" />
<a-dropdown :trigger="['click']" placement="bottomRight">
<EllipsisOutlined class="row-icon" @click.prevent />
<template #overlay>
<a-menu>
<a-menu-item v-if="dbInbound.hasLink()" @click="emit('qrcode-client', { dbInbound, client })">
<QrcodeOutlined /> {{ t('qrCode') }}
</a-menu-item>
<a-menu-item @click="emit('edit-client', { dbInbound, client })">
<EditOutlined /> {{ t('edit') }}
</a-menu-item>
<a-menu-item @click="emit('info-client', { dbInbound, client })">
<InfoCircleOutlined /> {{ t('info') }}
</a-menu-item>
<a-menu-item v-if="client.email" @click="confirmReset(client)">
<RetweetOutlined /> {{ t('pages.inbounds.resetTraffic') }}
</a-menu-item>
<a-menu-item v-if="isRemovable" @click="confirmDelete(client)">
<DeleteOutlined /> <span class="danger">{{ t('delete') }}</span>
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</div>
</div>
<div v-if="client.comment && client.comment.trim()" class="client-comment-line">
{{ client.comment.length > 80 ? client.comment.substring(0, 77) + '…' : client.comment }}
</div>
<div class="client-card-foot">
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.traffic') }}</span>
<a-tag :color="clientStatsColor(client.email)">
{{ SizeFormatter.sizeFormat(getSum(client.email)) }} /
<InfinityIcon v-if="isUnlimitedTotal(client)" />
<template v-else>{{ totalGbDisplay(client) }}</template>
</a-tag>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.allTimeTraffic') }}</span>
<a-tag>{{ SizeFormatter.sizeFormat(getAllTime(client.email)) }}</a-tag>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('online') }}</span>
<a-tag v-if="client.enable && isClientOnline(client.email)" color="green">{{ t('online') }}</a-tag>
<a-tag v-else>{{ t('offline') }}</a-tag>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.expireDate') }}</span>
<a-tag v-if="client.expiryTime > 0" :color="ColorUtils.userExpiryColor(expireDiff, client, isDarkTheme)">
{{ IntlUtil.formatRelativeTime(client.expiryTime) }}
</a-tag>
<a-tag v-else-if="client.expiryTime < 0" color="green">
{{ -client.expiryTime / 86400000 }}d ({{ t('pages.client.delayedStart') }})
</a-tag>
<a-tag v-else color="purple">
<InfinityIcon />
</a-tag>
</div>
</div>
</div>
</template>
</div>
</template>
<style scoped>
.client-list {
margin: -8px 0;
font-size: 13px;
}
.client-row {
display: grid;
grid-template-columns:
140px
/* actions */
60px
/* enable */
80px
/* online */
minmax(160px, 2fr)
/* client identity */
minmax(160px, 2fr)
/* traffic */
130px
/* all-time */
140px;
/* expiry */
gap: 12px;
align-items: center;
padding: 8px 16px;
border-top: 1px solid rgba(128, 128, 128, 0.12);
}
.client-row:last-child {
border-bottom: 1px solid rgba(128, 128, 128, 0.12);
}
.client-list-header {
font-weight: 500;
font-size: 12px;
opacity: 0.65;
padding-top: 6px;
padding-bottom: 6px;
border-top: none;
text-transform: uppercase;
letter-spacing: 0.02em;
}
.cell {
min-width: 0;
/* allow grid children to shrink instead of overflowing */
}
.cell-actions,
.cell-enable,
.cell-online,
.cell-alltime {
text-align: center;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
flex-wrap: wrap;
}
.cell-actions {
justify-content: flex-start;
}
.cell-client {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.cell-traffic,
.cell-expiry {
text-align: center;
}
.client-list-header .cell {
text-align: center;
}
.client-list-header .cell-actions,
.client-list-header .cell-client {
text-align: left;
}
/* Action icons */
.row-icon {
font-size: 16px;
cursor: pointer;
padding: 0 2px;
color: inherit;
transition: color 120ms ease;
}
.row-icon:hover {
color: var(--ant-color-primary, #1677ff);
}
.row-icon.danger {
color: #ff4d4f;
}
.danger {
color: #ff4d4f;
}
/* Client identity stack (badge + email + comment) */
.client-id-stack {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
overflow: hidden;
}
.client-email {
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
.client-comment {
font-size: 11px;
opacity: 0.7;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
}
/* Traffic / expiry inline bar: text | progress | text */
.usage-bar {
display: grid;
grid-template-columns: minmax(50px, auto) minmax(40px, 1fr) minmax(40px, auto);
align-items: center;
gap: 6px;
}
.usage-text {
font-size: 12px;
white-space: nowrap;
}
.usage-bar :deep(.ant-progress) {
margin: 0;
line-height: 1;
}
.infinite-tag {
min-width: 50px;
display: inline-flex;
align-items: center;
justify-content: center;
}
/* Strip AD-Vue's default expanded-cell padding so the desktop grid
* sits flush against the inbound row's left/right edges. */
:deep(.ant-table-expanded-row > .ant-table-cell) {
padding: 0 !important;
}
/* ===== Mobile card list =========================================== */
.client-list.is-mobile {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
}
.client-card {
border: 1px solid rgba(128, 128, 128, 0.18);
border-radius: 8px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
:global(body.dark) .client-card {
border-color: rgba(255, 255, 255, 0.1);
}
.client-card-head {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.client-card-head .client-email {
flex: 1;
min-width: 0;
font-size: 14px;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.client-card-actions {
margin-left: auto;
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.client-card-actions .row-icon {
font-size: 20px;
padding: 4px;
}
.client-comment-line {
font-size: 11px;
opacity: 0.7;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.client-card-foot {
display: flex;
flex-direction: column;
gap: 4px;
}
.client-card-foot .stat-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.client-card-foot .stat-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
opacity: 0.6;
min-width: 96px;
flex-shrink: 0;
}
.client-card-foot :deep(.ant-tag) {
margin: 0;
}
/* Bigger status badge for thumb-readable state at a glance. */
.client-card-head :deep(.ant-badge-status-dot) {
width: 9px;
height: 9px;
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+812
View File
@@ -0,0 +1,812 @@
<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
PlusOutlined,
MenuOutlined,
SearchOutlined,
FilterOutlined,
MoreOutlined,
EditOutlined,
QrcodeOutlined,
UserAddOutlined,
UsergroupAddOutlined,
CopyOutlined,
FileDoneOutlined,
ExportOutlined,
ImportOutlined,
ReloadOutlined,
RestOutlined,
RetweetOutlined,
BlockOutlined,
DeleteOutlined,
InfoCircleOutlined,
RightOutlined,
} from '@ant-design/icons-vue';
import { HttpUtil, ObjectUtil, SizeFormatter, IntlUtil, ColorUtils } from '@/utils';
import { DBInbound } from '@/models/dbinbound.js';
import { Inbound } from '@/models/inbound.js';
import InfinityIcon from '@/components/InfinityIcon.vue';
import ClientRowTable from './ClientRowTable.vue';
import { useDatepicker } from '@/composables/useDatepicker.js';
const { datepicker } = useDatepicker();
const { t } = useI18n();
const props = defineProps({
dbInbounds: { type: Array, required: true },
clientCount: { type: Object, required: true },
onlineClients: { type: Array, required: true },
lastOnlineMap: { type: Object, default: () => ({}) },
expireDiff: { type: Number, default: 0 },
trafficDiff: { type: Number, default: 0 },
pageSize: { type: Number, default: 0 },
isMobile: { type: Boolean, default: false },
isDarkTheme: { type: Boolean, default: false },
subEnable: { type: Boolean, default: false },
// Map node id -> node row, supplied by the parent page so each
// inbound row can render its node name without an extra fetch.
nodesById: { type: Map, default: () => new Map() },
});
const emit = defineEmits([
'refresh',
'add-inbound',
'general-action',
'row-action',
// Per-client events surfaced from the expand-row table.
'edit-client',
'qrcode-client',
'info-client',
'reset-traffic-client',
'delete-client',
'toggle-enable-client',
]);
// ============ Toolbar / search & filter =============================
const enableFilter = ref(false);
const searchKey = ref('');
const filterBy = ref('');
// Toggle the filter mode — flip cleans the other input.
function onToggleFilter() {
if (enableFilter.value) searchKey.value = '';
else filterBy.value = '';
}
// ============ Search / filter projection =============================
// Mirrors the legacy logic: when searching, keep inbounds that match
// anywhere (deep search); when filtering, keep inbounds that have at
// least one client in the requested bucket and reduce their settings
// to that bucket.
function projectInbound(dbInbound, predicate) {
const next = new DBInbound(dbInbound);
let settings;
try {
settings = JSON.parse(dbInbound.settings || '{}');
} catch (_e) {
settings = {};
}
if (!Array.isArray(settings.clients)) return next;
const filtered = settings.clients.filter(predicate);
next.settings = Inbound.Settings.fromJson(dbInbound.protocol, { clients: filtered });
next.invalidateCache();
return next;
}
const visibleInbounds = computed(() => {
if (enableFilter.value) {
if (ObjectUtil.isEmpty(filterBy.value)) return [...props.dbInbounds];
const out = [];
for (const dbInbound of props.dbInbounds) {
const c = props.clientCount[dbInbound.id];
if (!c || !c[filterBy.value] || c[filterBy.value].length === 0) continue;
const list = c[filterBy.value];
out.push(projectInbound(dbInbound, (client) => list.includes(client.email)));
}
return out;
}
if (ObjectUtil.isEmpty(searchKey.value)) return [...props.dbInbounds];
const out = [];
for (const dbInbound of props.dbInbounds) {
if (!ObjectUtil.deepSearch(dbInbound, searchKey.value)) continue;
out.push(projectInbound(dbInbound, (client) => ObjectUtil.deepSearch(client, searchKey.value)));
}
return out;
});
// ============ Columns =================================================
// `key`-driven so we can render via the body-cell slot below. AD-Vue 4's
// `responsive` array still works on column defs. Computed so column
// labels react to live locale switches.
const desktopColumns = computed(() => {
const cols = [
{ title: 'ID', dataIndex: 'id', key: 'id', align: 'right', width: 30, responsive: ['xs'] },
{ title: t('pages.inbounds.operate'), key: 'action', align: 'center', width: 30 },
{ title: t('pages.inbounds.enable'), key: 'enable', align: 'center', width: 35 },
{ title: t('pages.inbounds.remark'), dataIndex: 'remark', key: 'remark', align: 'center', width: 60 },
];
if (props.nodesById.size > 0) {
cols.push({ title: t('pages.inbounds.node'), key: 'node', align: 'center', width: 60 });
}
cols.push(
{ title: t('pages.inbounds.port'), dataIndex: 'port', key: 'port', align: 'center', width: 40 },
{ title: t('pages.inbounds.protocol'), key: 'protocol', align: 'left', width: 130 },
{ title: t('clients'), key: 'clients', align: 'left', width: 50 },
{ title: t('pages.inbounds.traffic'), key: 'traffic', align: 'center', width: 90 },
{ title: t('pages.inbounds.allTimeTraffic'), key: 'allTimeInbound', align: 'center', width: 95 },
{ title: t('pages.inbounds.expireDate'), key: 'expiryTime', align: 'center', width: 40 },
);
return cols;
});
const columns = computed(() => desktopColumns.value);
// Mobile expansion state — replaces a-table's expandable() since the
// mobile branch renders a hand-rolled card list rather than a table.
const expandedIds = ref(new Set());
function toggleExpanded(id) {
const next = new Set(expandedIds.value);
if (next.has(id)) next.delete(id);
else next.add(id);
expandedIds.value = next;
}
function isExpanded(id) {
return expandedIds.value.has(id);
}
// ============ Pagination ============================================
function paginationFor(rows) {
const size = props.pageSize > 0 ? props.pageSize : rows.length || 1;
return {
pageSize: size,
showSizeChanger: false,
hideOnSinglePage: true,
};
}
// ============ Per-row enable switch =================================
async function onSwitchEnable(dbInbound, next) {
const previous = dbInbound.enable;
dbInbound.enable = next; // optimistic
try {
const formData = new FormData();
formData.append('enable', String(next));
const msg = await HttpUtil.post(`/panel/api/inbounds/setEnable/${dbInbound.id}`, formData);
if (!msg?.success) dbInbound.enable = previous;
} catch (_e) {
dbInbound.enable = previous;
}
}
// ============ Helpers shared with the templates =====================
// Whether to show the "Switch xray" / qrcode menu entry — same predicate
// as legacy: SS single-user inbounds and WireGuard inbounds expose
// inbound-wide QR codes.
function showQrCodeMenu(dbInbound) {
if (dbInbound.isWireguard) return true;
if (dbInbound.isSS) {
try {
return !dbInbound.toInbound().isSSMultiUser;
} catch (_e) {
return false;
}
}
return false;
}
</script>
<template>
<a-card hoverable>
<template #title>
<a-space direction="horizontal">
<a-button type="primary" @click="emit('add-inbound')">
<template #icon>
<PlusOutlined />
</template>
<template v-if="!isMobile">{{ t('pages.inbounds.addInbound') }}</template>
</a-button>
<a-dropdown :trigger="['click']">
<a-button type="primary">
<template #icon>
<MenuOutlined />
</template>
<template v-if="!isMobile">{{ t('pages.inbounds.generalActions') }}</template>
</a-button>
<template #overlay>
<a-menu @click="(a) => emit('general-action', a.key)">
<a-menu-item key="import">
<ImportOutlined /> {{ t('pages.inbounds.importInbound') }}
</a-menu-item>
<a-menu-item key="export">
<ExportOutlined /> {{ t('pages.inbounds.export') }}
</a-menu-item>
<a-menu-item v-if="subEnable" key="subs">
<ExportOutlined /> {{ t('pages.inbounds.export') }} {{ t('pages.settings.subSettings') }}
</a-menu-item>
<a-menu-item key="resetInbounds">
<ReloadOutlined /> {{ t('pages.inbounds.resetAllTraffic') }}
</a-menu-item>
<a-menu-item key="resetClients">
<FileDoneOutlined /> {{ t('pages.inbounds.resetAllClientTraffics') }}
</a-menu-item>
<a-menu-item key="delDepletedClients" class="danger-item">
<RestOutlined /> {{ t('pages.inbounds.delDepletedClients') }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</a-space>
</template>
<a-space direction="vertical" :style="{ width: '100%' }">
<!-- Search / filter toolbar -->
<div :class="isMobile ? 'filter-bar mobile' : 'filter-bar'">
<a-switch v-model:checked="enableFilter" @change="onToggleFilter">
<template #checkedChildren>
<SearchOutlined />
</template>
<template #unCheckedChildren>
<FilterOutlined />
</template>
</a-switch>
<a-input v-if="!enableFilter" v-model:value="searchKey" :placeholder="t('search')" autofocus
:size="isMobile ? 'small' : 'middle'" :style="{ maxWidth: '300px' }" />
<a-radio-group v-if="enableFilter" v-model:value="filterBy" button-style="solid"
:size="isMobile ? 'small' : 'middle'">
<a-radio-button value="">{{ t('none') }}</a-radio-button>
<a-radio-button value="active">{{ t('subscription.active') }}</a-radio-button>
<a-radio-button value="deactive">{{ t('disabled') }}</a-radio-button>
<a-radio-button value="depleted">{{ t('depleted') }}</a-radio-button>
<a-radio-button value="expiring">{{ t('depletingSoon') }}</a-radio-button>
<a-radio-button value="online">{{ t('online') }}</a-radio-button>
</a-radio-group>
</div>
<!-- ====================== Mobile: card list ======================= -->
<div v-if="isMobile" class="inbound-cards">
<div v-if="visibleInbounds.length === 0" class="card-empty"></div>
<div v-for="record in visibleInbounds" :key="record.id" class="inbound-card">
<!-- Header: chevron (multi-user only) + remark + enable + actions -->
<div class="card-head" @click="record.isMultiUser() && toggleExpanded(record.id)">
<RightOutlined v-if="record.isMultiUser()" class="card-expand"
:class="{ 'is-expanded': isExpanded(record.id) }" />
<span class="card-id">#{{ record.id }}</span>
<span class="tag-name">{{ record.remark }}</span>
<div class="card-actions" @click.stop>
<a-switch :checked="record.enable" size="small" @change="(next) => onSwitchEnable(record, next)" />
<a-dropdown :trigger="['click']" placement="bottomRight">
<MoreOutlined class="row-action-trigger" @click.prevent />
<template #overlay>
<a-menu @click="(a) => emit('row-action', { key: a.key, dbInbound: record })">
<a-menu-item key="edit">
<EditOutlined /> {{ t('edit') }}
</a-menu-item>
<a-menu-item v-if="showQrCodeMenu(record)" key="qrcode">
<QrcodeOutlined /> {{ t('qrCode') }}
</a-menu-item>
<template v-if="record.isMultiUser()">
<a-menu-item key="addClient">
<UserAddOutlined /> {{ t('pages.client.add') }}
</a-menu-item>
<a-menu-item key="addBulkClient">
<UsergroupAddOutlined /> {{ t('pages.client.bulk') }}
</a-menu-item>
<a-menu-item key="copyClients">
<CopyOutlined /> {{ t('pages.client.copyFromInbound') }}
</a-menu-item>
<a-menu-item key="resetClients">
<FileDoneOutlined /> {{ t('pages.inbounds.resetInboundClientTraffics') }}
</a-menu-item>
<a-menu-item key="export">
<ExportOutlined /> {{ t('pages.inbounds.export') }}
</a-menu-item>
<a-menu-item v-if="subEnable" key="subs">
<ExportOutlined /> {{ t('pages.inbounds.export') }} {{ t('pages.settings.subSettings') }}
</a-menu-item>
<a-menu-item key="delDepletedClients" class="danger-item">
<RestOutlined /> {{ t('pages.inbounds.delDepletedClients') }}
</a-menu-item>
</template>
<template v-else>
<a-menu-item key="showInfo">
<InfoCircleOutlined /> {{ t('info') }}
</a-menu-item>
</template>
<a-menu-item key="clipboard">
<CopyOutlined /> {{ t('pages.inbounds.exportInbound') }}
</a-menu-item>
<a-menu-item key="resetTraffic">
<RetweetOutlined /> {{ t('pages.inbounds.resetTraffic') }}
</a-menu-item>
<a-menu-item key="clone">
<BlockOutlined /> {{ t('pages.inbounds.clone') }}
</a-menu-item>
<a-menu-item key="delete" class="danger-item">
<DeleteOutlined /> {{ t('delete') }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</div>
</div>
<!-- 2-column labelled stat grid: protocol/port/node + traffic/clients/expiry -->
<div class="card-stats">
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.protocol') }}</span>
<a-tag color="purple">{{ record.protocol }}</a-tag>
<template v-if="record.isVMess || record.isVLess || record.isTrojan || record.isSS">
<a-tag color="green">{{ record.toInbound().stream.network }}</a-tag>
<a-tag v-if="record.toInbound().stream.isTls" color="blue">TLS</a-tag>
<a-tag v-if="record.toInbound().stream.isReality" color="blue">Reality</a-tag>
</template>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.port') }}</span>
<a-tag>{{ record.port }}</a-tag>
</div>
<div v-if="nodesById.size > 0" class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.node') }}</span>
<a-tag v-if="record.nodeId == null" color="default">
{{ t('pages.inbounds.localPanel') }}
</a-tag>
<a-tag v-else-if="nodesById.get(record.nodeId)"
:color="nodesById.get(record.nodeId).status === 'online' ? 'blue' : 'red'">
{{ nodesById.get(record.nodeId).name }}
</a-tag>
<a-tag v-else color="orange">#{{ record.nodeId }}</a-tag>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.traffic') }}</span>
<a-tag :color="ColorUtils.usageColor(record.up + record.down, trafficDiff, record.total)">
{{ SizeFormatter.sizeFormat(record.up + record.down) }} /
<template v-if="record.total > 0">{{ SizeFormatter.sizeFormat(record.total) }}</template>
<InfinityIcon v-else />
</a-tag>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.allTimeTraffic') }}</span>
<a-tag>{{ SizeFormatter.sizeFormat(record.allTime || 0) }}</a-tag>
</div>
<div v-if="clientCount[record.id]" class="stat-row">
<span class="stat-label">{{ t('clients') }}</span>
<a-tag color="green">{{ clientCount[record.id].clients }}</a-tag>
<a-tag v-if="clientCount[record.id].online.length" color="blue">
{{ clientCount[record.id].online.length }} {{ t('online') }}
</a-tag>
<a-tag v-if="clientCount[record.id].depleted.length" color="red">
{{ clientCount[record.id].depleted.length }} {{ t('depleted') }}
</a-tag>
<a-tag v-if="clientCount[record.id].expiring.length" color="orange">
{{ clientCount[record.id].expiring.length }} {{ t('depletingSoon') }}
</a-tag>
</div>
<div class="stat-row">
<span class="stat-label">{{ t('pages.inbounds.expireDate') }}</span>
<a-tag v-if="record.expiryTime > 0"
:color="ColorUtils.usageColor(Date.now(), expireDiff, record._expiryTime)">
{{ IntlUtil.formatRelativeTime(record.expiryTime) }}
</a-tag>
<a-tag v-else color="purple">
<InfinityIcon />
</a-tag>
</div>
</div>
<!-- Expanded client list (multi-user only) -->
<div v-if="record.isMultiUser() && isExpanded(record.id)" class="card-clients">
<ClientRowTable :db-inbound="record" :is-mobile="true" :traffic-diff="trafficDiff" :expire-diff="expireDiff"
:online-clients="onlineClients" :last-online-map="lastOnlineMap" :is-dark-theme="isDarkTheme"
@edit-client="(p) => emit('edit-client', p)" @qrcode-client="(p) => emit('qrcode-client', p)"
@info-client="(p) => emit('info-client', p)"
@reset-traffic-client="(p) => emit('reset-traffic-client', p)"
@delete-client="(p) => emit('delete-client', p)"
@toggle-enable-client="(p) => emit('toggle-enable-client', p)" />
</div>
</div>
</div>
<!-- ====================== Desktop: a-table ======================== -->
<a-table v-else :columns="columns" :data-source="visibleInbounds" :row-key="(r) => r.id"
:pagination="paginationFor(visibleInbounds)" :scroll="{ x: 1000 }" :style="{ marginTop: '10px' }" size="small"
:row-class-name="(r) => (r.isMultiUser() ? '' : 'hide-expand-icon')">
<!-- Per-inbound client list, expanded by clicking the row's
default expand chevron. Hidden via row-class-name for
non-multi-user inbounds (matches legacy behavior). -->
<template #expandedRowRender="{ record }">
<ClientRowTable v-if="record.isMultiUser()" :db-inbound="record" :is-mobile="isMobile"
:traffic-diff="trafficDiff" :expire-diff="expireDiff" :online-clients="onlineClients"
:last-online-map="lastOnlineMap" :is-dark-theme="isDarkTheme" @edit-client="(p) => emit('edit-client', p)"
@qrcode-client="(p) => emit('qrcode-client', p)" @info-client="(p) => emit('info-client', p)"
@reset-traffic-client="(p) => emit('reset-traffic-client', p)"
@delete-client="(p) => emit('delete-client', p)"
@toggle-enable-client="(p) => emit('toggle-enable-client', p)" />
</template>
<template #bodyCell="{ column, record }">
<!-- ============== Action dropdown ============== -->
<template v-if="column.key === 'action'">
<a-dropdown :trigger="['click']">
<MoreOutlined class="row-action-trigger" @click.prevent />
<template #overlay>
<a-menu @click="(a) => emit('row-action', { key: a.key, dbInbound: record })">
<a-menu-item key="edit">
<EditOutlined /> {{ t('edit') }}
</a-menu-item>
<a-menu-item v-if="showQrCodeMenu(record)" key="qrcode">
<QrcodeOutlined /> {{ t('qrCode') }}
</a-menu-item>
<template v-if="record.isMultiUser()">
<a-menu-item key="addClient">
<UserAddOutlined /> {{ t('pages.client.add') }}
</a-menu-item>
<a-menu-item key="addBulkClient">
<UsergroupAddOutlined /> {{ t('pages.client.bulk') }}
</a-menu-item>
<a-menu-item key="copyClients">
<CopyOutlined /> {{ t('pages.client.copyFromInbound') }}
</a-menu-item>
<a-menu-item key="resetClients">
<FileDoneOutlined /> {{ t('pages.inbounds.resetInboundClientTraffics') }}
</a-menu-item>
<a-menu-item key="export">
<ExportOutlined /> {{ t('pages.inbounds.export') }}
</a-menu-item>
<a-menu-item v-if="subEnable" key="subs">
<ExportOutlined /> {{ t('pages.inbounds.export') }} — {{ t('pages.settings.subSettings') }}
</a-menu-item>
<a-menu-item key="delDepletedClients" class="danger-item">
<RestOutlined /> {{ t('pages.inbounds.delDepletedClients') }}
</a-menu-item>
</template>
<template v-else>
<a-menu-item key="showInfo">
<InfoCircleOutlined /> {{ t('info') }}
</a-menu-item>
</template>
<a-menu-item key="clipboard">
<CopyOutlined /> {{ t('pages.inbounds.exportInbound') }}
</a-menu-item>
<a-menu-item key="resetTraffic">
<RetweetOutlined /> {{ t('pages.inbounds.resetTraffic') }}
</a-menu-item>
<a-menu-item key="clone">
<BlockOutlined /> {{ t('pages.inbounds.clone') }}
</a-menu-item>
<a-menu-item key="delete" class="danger-item">
<DeleteOutlined /> {{ t('delete') }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
<!-- ============== Enable switch (desktop) ============== -->
<template v-else-if="column.key === 'enable'">
<a-switch :checked="record.enable" @change="(next) => onSwitchEnable(record, next)" />
</template>
<!-- ============== Node deployment tag ============== -->
<template v-else-if="column.key === 'node'">
<template v-if="record.nodeId == null">
<a-tag color="default">{{ t('pages.inbounds.localPanel') }}</a-tag>
</template>
<template v-else-if="nodesById.get(record.nodeId)">
<a-tag :color="nodesById.get(record.nodeId).status === 'online' ? 'blue' : 'red'">
{{ nodesById.get(record.nodeId).name }}
</a-tag>
</template>
<template v-else>
<!-- Node row was deleted but inbound still references it. -->
<a-tag color="orange">node #{{ record.nodeId }}</a-tag>
</template>
</template>
<!-- ============== Protocol tags ============== -->
<template v-else-if="column.key === 'protocol'">
<div class="protocol-tags">
<a-tag color="purple">{{ record.protocol }}</a-tag>
<template v-if="record.isVMess || record.isVLess || record.isTrojan || record.isSS">
<a-tag color="green">{{ record.toInbound().stream.network }}</a-tag>
<a-tag v-if="record.toInbound().stream.isTls" color="blue">TLS</a-tag>
<a-tag v-if="record.toInbound().stream.isReality" color="blue">Reality</a-tag>
</template>
</div>
</template>
<!-- ============== Clients tag + popovers ============== -->
<template v-else-if="column.key === 'clients'">
<template v-if="clientCount[record.id]">
<a-tag color="green" style="margin: 0">{{ clientCount[record.id].clients }}</a-tag>
<a-popover v-if="clientCount[record.id].deactive.length" :title="t('disabled')">
<template #content>
<div v-for="email in clientCount[record.id].deactive" :key="email">{{ email }}</div>
</template>
<a-tag style="margin: 0; padding: 0 2px">{{ clientCount[record.id].deactive.length }}</a-tag>
</a-popover>
<a-popover v-if="clientCount[record.id].depleted.length" :title="t('depleted')">
<template #content>
<div v-for="email in clientCount[record.id].depleted" :key="email">{{ email }}</div>
</template>
<a-tag color="red" style="margin: 0; padding: 0 2px">{{ clientCount[record.id].depleted.length
}}</a-tag>
</a-popover>
<a-popover v-if="clientCount[record.id].expiring.length" :title="t('depletingSoon')">
<template #content>
<div v-for="email in clientCount[record.id].expiring" :key="email">{{ email }}</div>
</template>
<a-tag color="orange" style="margin: 0; padding: 0 2px">{{ clientCount[record.id].expiring.length
}}</a-tag>
</a-popover>
<a-popover v-if="clientCount[record.id].online.length" :title="t('online')">
<template #content>
<div v-for="email in clientCount[record.id].online" :key="email">{{ email }}</div>
</template>
<a-tag color="blue" style="margin: 0; padding: 0 2px">{{ clientCount[record.id].online.length }}</a-tag>
</a-popover>
</template>
</template>
<!-- ============== Traffic ============== -->
<template v-else-if="column.key === 'traffic'">
<a-popover>
<template #content>
<table cellpadding="2">
<tbody>
<tr>
<td>↑ {{ SizeFormatter.sizeFormat(record.up) }}</td>
<td>↓ {{ SizeFormatter.sizeFormat(record.down) }}</td>
</tr>
<tr v-if="record.total > 0 && record.up + record.down < record.total">
<td>{{ t('remained') }}</td>
<td>{{ SizeFormatter.sizeFormat(record.total - record.up - record.down) }}</td>
</tr>
</tbody>
</table>
</template>
<a-tag :color="ColorUtils.usageColor(record.up + record.down, trafficDiff, record.total)">
{{ SizeFormatter.sizeFormat(record.up + record.down) }} /
<template v-if="record.total > 0">{{ SizeFormatter.sizeFormat(record.total) }}</template>
<InfinityIcon v-else />
</a-tag>
</a-popover>
</template>
<!-- ============== All-time inbound traffic ============== -->
<template v-else-if="column.key === 'allTimeInbound'">
<a-tag>{{ SizeFormatter.sizeFormat(record.allTime || 0) }}</a-tag>
</template>
<!-- ============== Expiry ============== -->
<template v-else-if="column.key === 'expiryTime'">
<a-popover v-if="record.expiryTime > 0">
<template #content>{{ IntlUtil.formatDate(record.expiryTime, datepicker) }}</template>
<a-tag :color="ColorUtils.usageColor(Date.now(), expireDiff, record._expiryTime)" style="min-width: 50px">
{{ IntlUtil.formatRelativeTime(record.expiryTime) }}
</a-tag>
</a-popover>
<a-tag v-else color="purple">
<InfinityIcon />
</a-tag>
</template>
</template>
</a-table>
</a-space>
</a-card>
</template>
<style scoped>
.filter-bar {
display: flex;
align-items: center;
gap: 8px;
}
.filter-bar.mobile {
display: block;
}
.filter-bar.mobile>* {
margin-bottom: 4px;
}
.protocol-tags {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
}
.row-action-trigger {
font-size: 20px;
cursor: pointer;
}
.danger-item {
color: #ff4d4f;
}
/* Hide the expand chevron on rows whose inbound has no client list
* (HTTP/Mixed/Tunnel/WireGuard single-config). */
:deep(.hide-expand-icon .ant-table-row-expand-icon) {
visibility: hidden;
}
/* Push the expand chevron away from the table's left edge so it has
* a little breathing room instead of being flush against the corner. */
:deep(.ant-table-tbody .ant-table-cell-with-append) {
padding-left: 12px;
}
:deep(.ant-table-row-expand-icon) {
margin-inline-end: 10px;
margin-inline-start: 4px;
}
/* Round the table's outer corners — AD-Vue gives .ant-table the radius
* token, but the inner header strip and footer touch the edges, so clip
* them here. */
:deep(.ant-table) {
border-radius: 8px;
overflow: hidden;
}
:deep(.ant-table-container) {
border-radius: 8px;
overflow: hidden;
}
:deep(.ant-table-thead > tr:first-child > *:first-child) {
border-start-start-radius: 8px;
}
:deep(.ant-table-thead > tr:first-child > *:last-child) {
border-start-end-radius: 8px;
}
:deep(.ant-table-tbody > tr:last-child > *:first-child) {
border-end-start-radius: 8px;
}
:deep(.ant-table-tbody > tr:last-child > *:last-child) {
border-end-end-radius: 8px;
}
/* ===== Mobile card list ===========================================
* <768px renders inbounds as a vertical stack of cards via the
* v-if="isMobile" branch above; the desktop <a-table> isn't mounted
* so the legacy table-cell tightening rules went away. */
.inbound-cards {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 4px;
}
.inbound-card {
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 10px;
padding: 12px;
background: rgba(255, 255, 255, 0.02);
display: flex;
flex-direction: column;
gap: 8px;
}
:global(body.dark) .inbound-card {
background: rgba(255, 255, 255, 0.03);
border-color: rgba(255, 255, 255, 0.1);
}
.card-head {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
user-select: none;
}
.card-id {
font-size: 11px;
opacity: 0.6;
}
.tag-name {
font-weight: 600;
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-actions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.card-expand {
font-size: 12px;
opacity: 0.6;
transition: transform 150ms ease;
flex-shrink: 0;
}
.card-expand.is-expanded {
transform: rotate(90deg);
}
.card-stats {
display: flex;
flex-direction: column;
gap: 6px;
}
.stat-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.stat-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
opacity: 0.6;
min-width: 96px;
flex-shrink: 0;
}
.card-stats :deep(.ant-tag) {
margin: 0;
}
.card-clients {
margin-top: 4px;
padding-top: 8px;
border-top: 1px solid rgba(128, 128, 128, 0.15);
}
.card-empty {
text-align: center;
opacity: 0.4;
padding: 20px 0;
}
@media (max-width: 768px) {
:deep(.ant-card-head) {
padding: 0 12px;
min-height: 44px;
}
:deep(.ant-card-head-title),
:deep(.ant-card-extra) {
padding: 8px 0;
}
:deep(.ant-card-body) {
padding: 8px;
}
.filter-bar.mobile {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.filter-bar.mobile>* {
margin-bottom: 0;
}
.row-action-trigger {
font-size: 22px;
padding: 4px;
}
}
</style>
@@ -0,0 +1,694 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, message } from 'ant-design-vue';
import {
SwapOutlined,
PieChartOutlined,
HistoryOutlined,
BarsOutlined,
TeamOutlined,
} from '@ant-design/icons-vue';
import { HttpUtil, SizeFormatter, RandomUtil } from '@/utils';
import { Inbound } from '@/models/inbound.js';
import { theme as themeState, antdThemeConfig } from '@/composables/useTheme.js';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
import AppSidebar from '@/components/AppSidebar.vue';
import CustomStatistic from '@/components/CustomStatistic.vue';
import { useNodeList } from '@/composables/useNodeList.js';
import InboundList from './InboundList.vue';
import InboundFormModal from './InboundFormModal.vue';
import ClientFormModal from './ClientFormModal.vue';
import ClientBulkModal from './ClientBulkModal.vue';
import InboundInfoModal from './InboundInfoModal.vue';
import QrCodeModal from './QrCodeModal.vue';
import TextModal from '@/components/TextModal.vue';
import PromptModal from '@/components/PromptModal.vue';
import { useInbounds } from './useInbounds.js';
import { useWebSocket } from '@/composables/useWebSocket.js';
const { t } = useI18n();
const {
fetched,
dbInbounds,
clientCount,
onlineClients,
totals,
expireDiff,
trafficDiff,
pageSize,
subSettings,
tgBotEnable,
ipLimitEnable,
remarkModel,
lastOnlineMap,
refresh,
fetchDefaultSettings,
applyTrafficEvent,
applyClientStatsEvent,
applyInvalidate,
applyInboundsEvent,
} = useInbounds();
// Live updates over WebSocket — replaces the old 5s polling loop.
// The backend pushes traffic + per-client deltas every ~10s; we merge
// them into the local refs in-place so counters and online badges
// update without re-fetching the whole list.
useWebSocket({
traffic: applyTrafficEvent,
client_stats: applyClientStatsEvent,
invalidate: applyInvalidate,
inbounds: applyInboundsEvent,
});
const { isMobile } = useMediaQuery();
// Node list lives on the central panel; the Inbounds page consumes
// the id→node map for the new "Node" column. Fetched once on mount.
const { byId: nodesById } = useNodeList();
const basePath = window.__X_UI_BASE_PATH__ || '';
const requestUri = window.location.pathname;
onMounted(async () => {
await fetchDefaultSettings();
await refresh();
});
// === Add/Edit modal ===================================================
const formOpen = ref(false);
const formMode = ref('add');
const formDbInbound = ref(null);
// === Client modal (single + bulk) =====================================
const clientOpen = ref(false);
const clientMode = ref('add');
const clientDbInbound = ref(null);
const clientIndex = ref(null);
const bulkOpen = ref(false);
const bulkDbInbound = ref(null);
// === Info / QR-code modals ===========================================
const infoOpen = ref(false);
const infoDbInbound = ref(null);
const infoClientIndex = ref(0);
const qrOpen = ref(false);
const qrDbInbound = ref(null);
const qrClient = ref(null);
// hostOverrideFor returns the node's address for a node-managed inbound,
// or '' when the inbound runs locally. Wired into the QR / Info modals
// and into export-all-links functions so generated share links point at
// the node, not the central panel.
function hostOverrideFor(dbInbound) {
if (!dbInbound || dbInbound.nodeId == null) return '';
return nodesById.value.get(dbInbound.nodeId)?.address || '';
}
const infoNodeAddress = computed(() => hostOverrideFor(infoDbInbound.value));
const qrNodeAddress = computed(() => hostOverrideFor(qrDbInbound.value));
// === Shared text + prompt modal state =================================
const textOpen = ref(false);
const textTitle = ref('');
const textContent = ref('');
const textFileName = ref('');
const promptOpen = ref(false);
const promptTitle = ref('');
const promptOkText = ref('OK');
const promptType = ref('textarea');
const promptInitial = ref('');
const promptLoading = ref(false);
let promptHandler = null;
function openText({ title, content, fileName = '' }) {
textTitle.value = title;
textContent.value = content;
textFileName.value = fileName;
textOpen.value = true;
}
function openPrompt({ title, okText, type = 'textarea', value = '', confirm }) {
promptTitle.value = title;
promptOkText.value = okText || 'OK';
promptType.value = type;
promptInitial.value = value;
promptHandler = confirm;
promptOpen.value = true;
}
async function onPromptConfirm(value) {
if (!promptHandler) { promptOpen.value = false; return; }
promptLoading.value = true;
try {
const ok = await promptHandler(value);
if (ok !== false) promptOpen.value = false;
} finally {
promptLoading.value = false;
}
}
// === Export helpers — mirror legacy txtModal call sites ==============
function exportInboundLinks(dbInbound) {
const projected = checkFallback(dbInbound);
openText({
title: 'Export inbound links',
content: projected.genInboundLinks(remarkModel.value, hostOverrideFor(dbInbound)),
fileName: projected.remark || 'inbound',
});
}
function exportInboundClipboard(dbInbound) {
openText({
title: 'Inbound JSON',
content: JSON.stringify(dbInbound, null, 2),
});
}
function exportInboundSubs(dbInbound) {
const inbound = dbInbound.toInbound();
const clients = inbound?.clients || [];
const subLinks = [];
for (const c of clients) {
if (c.subId && subSettings.value.subURI) {
subLinks.push(subSettings.value.subURI + c.subId);
}
}
openText({
title: 'Export subscription links',
content: [...new Set(subLinks)].join('\n'),
fileName: `${dbInbound.remark || 'inbound'}-Subs`,
});
}
function exportAllLinks() {
const out = [];
for (const ib of dbInbounds.value) {
out.push(ib.genInboundLinks(remarkModel.value, hostOverrideFor(ib)));
}
openText({
title: 'Export all inbound links',
content: out.join('\r\n'),
fileName: 'All-Inbounds',
});
}
function exportAllSubs() {
const out = [];
for (const ib of dbInbounds.value) {
const inbound = ib.toInbound();
const clients = inbound?.clients || [];
for (const c of clients) {
if (c.subId && subSettings.value.subURI) {
out.push(subSettings.value.subURI + c.subId);
}
}
}
openText({
title: 'Export all subscription links',
content: [...new Set(out)].join('\r\n'),
fileName: 'All-Inbounds-Subs',
});
}
function importInbound() {
openPrompt({
title: 'Import inbound',
okText: 'Import',
type: 'textarea',
value: '',
confirm: async (value) => {
const msg = await HttpUtil.post('/panel/api/inbounds/import', { data: value });
if (msg?.success) {
await refresh();
return true;
}
return false;
},
});
}
// `checkFallback` mirrors the legacy helper: when an inbound listens
// on a unix-socket fallback (`@<name>`), point the link generator at
// the root inbound that owns the listen address so QRs/links carry
// the externally-reachable host:port and the right TLS state.
function checkFallback(dbInbound) {
// We don't keep parsed Inbounds in state right now (the page works
// off DBInbounds); compute on the fly.
if (!dbInbound.listen?.startsWith?.('@')) return dbInbound;
for (const candidate of dbInbounds.value) {
if (candidate.id === dbInbound.id) continue;
const parsed = candidate.toInbound();
if (!parsed.isTcp) continue;
if (!['trojan', 'vless'].includes(parsed.protocol)) continue;
const fallbacks = parsed.settings.fallbacks || [];
if (!fallbacks.find((f) => f.dest === dbInbound.listen)) continue;
// Build a one-off DBInbound copy with the parent's listen/port +
// copied stream so the link gen sees the public endpoint.
const projected = JSON.parse(JSON.stringify(dbInbound));
projected.listen = candidate.listen;
projected.port = candidate.port;
const inheritedStream = parsed.stream;
const ownInbound = dbInbound.toInbound();
ownInbound.stream.security = inheritedStream.security;
ownInbound.stream.tls = inheritedStream.tls;
ownInbound.stream.externalProxy = inheritedStream.externalProxy;
projected.streamSettings = ownInbound.stream.toString();
// Re-wrap so callers get the same DBInbound shape they had.
return new dbInbound.constructor(projected);
}
return dbInbound;
}
function findClientIndex(dbInbound, client) {
if (!client) return 0;
const inbound = dbInbound.toInbound();
const clients = inbound?.clients || [];
const idx = clients.findIndex((c) => {
if (!c) return false;
switch (dbInbound.protocol) {
case 'trojan':
case 'shadowsocks':
return c.password === client.password && c.email === client.email;
default:
return c.id === client.id && c.email === client.email;
}
});
return idx >= 0 ? idx : 0;
}
function getClientId(protocol, client) {
switch (protocol) {
case 'trojan': return client.password;
case 'shadowsocks': return client.email;
case 'hysteria': return client.auth;
default: return client.id;
}
}
// === Per-client handlers (called from the expand-row table) =========
function onEditClient({ dbInbound, client }) {
clientMode.value = 'edit';
clientDbInbound.value = dbInbound;
clientIndex.value = findClientIndex(dbInbound, client);
clientOpen.value = true;
}
function onQrcodeClient({ dbInbound, client }) {
qrDbInbound.value = checkFallback(dbInbound);
qrClient.value = client || null;
qrOpen.value = true;
}
function onInfoClient({ dbInbound, client }) {
infoDbInbound.value = checkFallback(dbInbound);
infoClientIndex.value = findClientIndex(dbInbound, client);
infoOpen.value = true;
}
async function onResetTrafficClient({ dbInbound, client }) {
const msg = await HttpUtil.post(
`/panel/api/inbounds/${dbInbound.id}/resetClientTraffic/${client.email}`,
);
if (msg?.success) await refresh();
}
async function onDeleteClient({ dbInbound, client }) {
const clientId = getClientId(dbInbound.protocol, client);
const msg = await HttpUtil.post(`/panel/api/inbounds/${dbInbound.id}/delClient/${clientId}`);
if (msg?.success) await refresh();
}
async function onToggleEnableClient({ dbInbound, client, next }) {
// Mirror legacy: clone the parsed inbound, flip enable on the matching
// client, and post the whole client back through updateClient. This
// keeps the wire shape identical to the modal save path.
const inbound = dbInbound.toInbound();
const clients = inbound?.clients || [];
const idx = findClientIndex(dbInbound, client);
if (idx < 0 || !clients[idx]) return;
clients[idx].enable = next;
const clientId = getClientId(dbInbound.protocol, clients[idx]);
const msg = await HttpUtil.post(`/panel/api/inbounds/updateClient/${clientId}`, {
id: dbInbound.id,
settings: `{"clients": [${clients[idx].toString()}]}`,
});
if (msg?.success) await refresh();
}
function onAddInbound() {
formMode.value = 'add';
formDbInbound.value = null;
formOpen.value = true;
}
function openEdit(dbInbound) {
formMode.value = 'edit';
formDbInbound.value = dbInbound;
formOpen.value = true;
}
function openAddClient(dbInbound) {
clientMode.value = 'add';
clientDbInbound.value = dbInbound;
clientIndex.value = null;
clientOpen.value = true;
}
function openAddBulkClient(dbInbound) {
bulkDbInbound.value = dbInbound;
bulkOpen.value = true;
}
// Per-row destructive actions go through Modal.confirm (matches legacy).
function confirmDelete(dbInbound) {
Modal.confirm({
title: `Delete inbound "${dbInbound.remark}"?`,
content: 'This removes the inbound and all its clients. This cannot be undone.',
okText: 'Delete',
okType: 'danger',
cancelText: 'Cancel',
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/del/${dbInbound.id}`);
if (msg?.success) await refresh();
},
});
}
function confirmResetTraffic(dbInbound) {
Modal.confirm({
title: `Reset traffic for "${dbInbound.remark}"?`,
content: 'Resets up/down counters to 0 for this inbound.',
okText: 'Reset',
cancelText: 'Cancel',
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/resetAllTraffics`);
if (msg?.success) await refresh();
},
});
}
function confirmDelDepleted(dbInboundId) {
Modal.confirm({
title: 'Delete depleted clients?',
content: 'Removes every client whose traffic is exhausted or whose expiry has passed.',
okText: 'Delete',
okType: 'danger',
cancelText: 'Cancel',
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/delDepletedClients/${dbInboundId}`);
if (msg?.success) await refresh();
},
});
}
// Clone — adds a new inbound with the same protocol+stream+sniffing
// but a fresh remark/port and an empty client list.
function confirmClone(dbInbound) {
Modal.confirm({
title: `Clone inbound "${dbInbound.remark}"?`,
content: 'Creates a copy with a new port and an empty client list.',
okText: 'Clone',
cancelText: 'Cancel',
onOk: async () => {
const baseInbound = dbInbound.toInbound();
const data = {
up: 0,
down: 0,
total: 0,
remark: `${dbInbound.remark} (clone)`,
enable: false,
expiryTime: 0,
listen: '',
port: RandomUtil.randomInteger(10000, 60000),
protocol: baseInbound.protocol,
settings: Inbound.Settings.getSettings(baseInbound.protocol).toString(),
streamSettings: baseInbound.stream.toString(),
sniffing: baseInbound.sniffing.toString(),
};
const msg = await HttpUtil.post('/panel/api/inbounds/add', data);
if (msg?.success) await refresh();
},
});
}
function onGeneralAction(key) {
switch (key) {
case 'import':
importInbound();
break;
case 'export':
exportAllLinks();
break;
case 'subs':
exportAllSubs();
break;
case 'resetInbounds':
Modal.confirm({
title: 'Reset all inbound traffic?',
okText: 'Reset',
cancelText: 'Cancel',
onOk: async () => {
const msg = await HttpUtil.post('/panel/api/inbounds/resetAllTraffics');
if (msg?.success) await refresh();
},
});
break;
case 'resetClients':
Modal.confirm({
title: 'Reset all client traffic across all inbounds?',
okText: 'Reset',
cancelText: 'Cancel',
onOk: async () => {
const msg = await HttpUtil.post('/panel/api/inbounds/resetAllClientTraffics/-1');
if (msg?.success) await refresh();
},
});
break;
case 'delDepletedClients':
confirmDelDepleted(-1);
break;
default:
message.info(`General action "${key}" — coming in a later 5f subphase`);
}
}
function onRowAction({ key, dbInbound }) {
switch (key) {
case 'edit':
openEdit(dbInbound);
break;
case 'addClient':
openAddClient(dbInbound);
break;
case 'addBulkClient':
openAddBulkClient(dbInbound);
break;
case 'showInfo':
infoDbInbound.value = checkFallback(dbInbound);
infoClientIndex.value = findClientIndex(dbInbound, null);
infoOpen.value = true;
break;
case 'qrcode':
qrDbInbound.value = checkFallback(dbInbound);
qrClient.value = null;
qrOpen.value = true;
break;
case 'export':
exportInboundLinks(dbInbound);
break;
case 'subs':
exportInboundSubs(dbInbound);
break;
case 'clipboard':
exportInboundClipboard(dbInbound);
break;
case 'copyClients':
// Copy-clients-from-inbound is a tiny dedicated modal in legacy
// (lets you tick clients to copy across inbounds). Defer to a
// future commit — surface a friendly message for now.
message.info('Copy clients across inbounds — coming soon');
break;
case 'delete':
confirmDelete(dbInbound);
break;
case 'resetTraffic':
confirmResetTraffic(dbInbound);
break;
case 'clone':
confirmClone(dbInbound);
break;
case 'resetClients':
Modal.confirm({
title: `Reset client traffic on "${dbInbound.remark}"?`,
okText: 'Reset',
cancelText: 'Cancel',
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/inbounds/resetAllClientTraffics/${dbInbound.id}`);
if (msg?.success) await refresh();
},
});
break;
case 'delDepletedClients':
confirmDelDepleted(dbInbound.id);
break;
default:
message.info(`Action "${key}" — coming in a later 5f subphase`);
}
}
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout class="inbounds-page" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
<AppSidebar :base-path="basePath" :request-uri="requestUri" />
<a-layout class="content-shell">
<a-layout-content id="content-layout" class="content-area">
<a-spin :spinning="!fetched" :delay="200" tip="Loading…" size="large">
<div v-if="!fetched" class="loading-spacer" />
<a-row v-else :gutter="[isMobile ? 8 : 16, 12]">
<!-- Summary statistics card -->
<a-col :span="24">
<a-card size="small" hoverable class="summary-card">
<a-row :gutter="[16, 12]">
<a-col :xs="12" :sm="12" :md="5">
<CustomStatistic :title="t('pages.inbounds.totalDownUp')"
:value="`${SizeFormatter.sizeFormat(totals.up)} / ${SizeFormatter.sizeFormat(totals.down)}`">
<template #prefix>
<SwapOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :xs="12" :sm="12" :md="5">
<CustomStatistic :title="t('pages.inbounds.totalUsage')"
:value="SizeFormatter.sizeFormat(totals.up + totals.down)">
<template #prefix>
<PieChartOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :xs="12" :sm="12" :md="5">
<CustomStatistic :title="t('pages.inbounds.allTimeTrafficUsage')"
:value="SizeFormatter.sizeFormat(totals.allTime)">
<template #prefix>
<HistoryOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :xs="12" :sm="12" :md="5">
<CustomStatistic :title="t('pages.inbounds.inboundCount')" :value="String(dbInbounds.length)">
<template #prefix>
<BarsOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :xs="24" :sm="24" :md="4">
<CustomStatistic :title="t('clients')" value=" ">
<template #prefix>
<a-space direction="horizontal">
<TeamOutlined />
<a-tag color="green">{{ totals.clients }}</a-tag>
<a-tag v-if="totals.deactive.length">{{ totals.deactive.length }}</a-tag>
<a-tag v-if="totals.depleted.length" color="red">{{ totals.depleted.length }}</a-tag>
<a-tag v-if="totals.expiring.length" color="orange">{{ totals.expiring.length }}</a-tag>
</a-space>
</template>
</CustomStatistic>
</a-col>
</a-row>
</a-card>
</a-col>
<!-- Inbound list toolbar, search/filter, columns, row actions -->
<a-col :span="24">
<InboundList :db-inbounds="dbInbounds" :client-count="clientCount" :online-clients="onlineClients"
:last-online-map="lastOnlineMap" :is-dark-theme="themeState.isDark" :expire-diff="expireDiff"
:traffic-diff="trafficDiff" :page-size="pageSize" :is-mobile="isMobile"
:sub-enable="subSettings.enable" :nodes-by-id="nodesById" @refresh="refresh"
@add-inbound="onAddInbound" @general-action="onGeneralAction" @row-action="onRowAction"
@edit-client="onEditClient" @qrcode-client="onQrcodeClient" @info-client="onInfoClient"
@reset-traffic-client="onResetTrafficClient" @delete-client="onDeleteClient"
@toggle-enable-client="onToggleEnableClient" />
</a-col>
</a-row>
</a-spin>
</a-layout-content>
</a-layout>
<InboundFormModal v-model:open="formOpen" :mode="formMode" :db-inbound="formDbInbound" @saved="refresh" />
<ClientFormModal v-model:open="clientOpen" :mode="clientMode" :db-inbound="clientDbInbound"
:client-index="clientIndex" :sub-enable="subSettings.enable" :tg-bot-enable="tgBotEnable"
:ip-limit-enable="ipLimitEnable" :traffic-diff="trafficDiff" @saved="refresh" />
<ClientBulkModal v-model:open="bulkOpen" :db-inbound="bulkDbInbound" :sub-enable="subSettings.enable"
:tg-bot-enable="tgBotEnable" :ip-limit-enable="ipLimitEnable" @saved="refresh" />
<InboundInfoModal v-model:open="infoOpen" :db-inbound="infoDbInbound" :client-index="infoClientIndex"
:remark-model="remarkModel" :expire-diff="expireDiff" :traffic-diff="trafficDiff"
:ip-limit-enable="ipLimitEnable" :tg-bot-enable="tgBotEnable" :sub-settings="subSettings"
:last-online-map="lastOnlineMap" :node-address="infoNodeAddress" />
<QrCodeModal v-model:open="qrOpen" :db-inbound="qrDbInbound" :client="qrClient" :remark-model="remarkModel"
:node-address="qrNodeAddress" />
<TextModal v-model:open="textOpen" :title="textTitle" :content="textContent" :file-name="textFileName" />
<PromptModal v-model:open="promptOpen" :title="promptTitle" :ok-text="promptOkText" :type="promptType"
:initial-value="promptInitial" :loading="promptLoading" @confirm="onPromptConfirm" />
</a-layout>
</a-config-provider>
</template>
<style scoped>
.inbounds-page {
--bg-page: #e6e8ec;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.inbounds-page.is-dark {
--bg-page: #0a1222;
--bg-card: #151f31;
}
.inbounds-page.is-dark.is-ultra {
--bg-page: #050505;
--bg-card: #0c0e12;
}
.inbounds-page :deep(.ant-layout),
.inbounds-page :deep(.ant-layout-content) {
background: transparent;
}
.content-shell {
background: transparent;
}
.content-area {
padding: 24px;
}
@media (max-width: 768px) {
.content-area {
padding: 8px;
}
}
.loading-spacer {
min-height: calc(100vh - 120px);
}
.summary-card {
padding: 16px;
}
@media (max-width: 768px) {
.summary-card {
padding: 8px;
}
}
</style>
@@ -0,0 +1,67 @@
<script setup>
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Protocols } from '@/models/inbound.js';
import QrPanel from './QrPanel.vue';
const { t } = useI18n();
// Light QR-only modal — used for the "qrcode" row action on
// single-user Shadowsocks and WireGuard inbounds. The big info modal
// (InboundInfoModal) is too detailed when the user just wants the
// share link as a QR.
const props = defineProps({
open: { type: Boolean, default: false },
dbInbound: { type: Object, default: null },
client: { type: Object, default: null },
remarkModel: { type: String, default: '-ieo' },
// Address of the node hosting this inbound (empty string for local).
// When set, share/QR links use it as the host instead of the panel's
// origin — node-managed inbounds proxy from the node, not the panel.
nodeAddress: { type: String, default: '' },
});
const emit = defineEmits(['update:open']);
const links = ref([]);
const wireguardConfigs = ref([]);
const wireguardLinks = ref([]);
watch(() => props.open, (next) => {
if (!next || !props.dbInbound) return;
const inbound = props.dbInbound.toInbound();
if (inbound.protocol === Protocols.WIREGUARD) {
const peerRemark = props.client?.email
? `${props.dbInbound.remark}-${props.client.email}`
: props.dbInbound.remark;
wireguardConfigs.value = inbound.genWireguardConfigs(peerRemark, '-ieo', props.nodeAddress).split('\r\n');
wireguardLinks.value = inbound.genWireguardLinks(peerRemark, '-ieo', props.nodeAddress).split('\r\n');
links.value = [];
} else {
// When a client is provided we generate per-client share links;
// otherwise (single-user SS) fall back to the inbound's settings.
links.value = inbound.genAllLinks(props.dbInbound.remark, props.remarkModel, props.client, props.nodeAddress);
wireguardConfigs.value = [];
wireguardLinks.value = [];
}
});
function close() {
emit('update:open', false);
}
</script>
<template>
<a-modal :open="open" :title="t('qrCode')" :footer="null" width="420px" @cancel="close">
<template v-if="dbInbound">
<QrPanel v-for="(link, idx) in links" :key="`l${idx}`" :value="link.link"
:remark="link.remark || `Link ${idx + 1}`" />
<template v-for="(cfg, idx) in wireguardConfigs" :key="`w${idx}`">
<QrPanel :value="cfg" :remark="`Peer ${idx + 1} config`" :download-name="`peer-${idx + 1}.conf`" />
<QrPanel v-if="wireguardLinks[idx]" :value="wireguardLinks[idx]" :remark="`Peer ${idx + 1} link`" />
</template>
</template>
</a-modal>
</template>
+153
View File
@@ -0,0 +1,153 @@
<script setup>
import { onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import QRious from 'qrious';
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { ClipboardManager, FileManager } from '@/utils';
const { t } = useI18n();
// Renders a single share-link as a clickable QR code + a copy button
// + (optional) a download button. Used per-link inside the inbound
// info modal — the canvas is repainted whenever `value` changes.
const props = defineProps({
// The link or config text to encode + display.
value: { type: String, required: true },
// Header label shown next to the copy button.
remark: { type: String, default: '' },
// Optional download filename — when set, surfaces a download button.
downloadName: { type: String, default: '' },
// Final on-screen QR size in CSS pixels. The canvas drawing buffer
// is rounded down to a multiple of the QR matrix width (so the QR
// fills it edge-to-edge) and CSS then scales the canvas to exactly
// this size — so a denser QR (e.g. WireGuard config) and a sparser
// one (its link) display at identical dimensions.
size: { type: Number, default: 240 },
// Toggle the QR rendering off when callers only want the "row of buttons"
// styling (used when the legacy panel rendered links without QRs).
showQr: { type: Boolean, default: true },
});
const canvas = ref(null);
// Byte-mode capacities (level M) for QR versions 1..40 — used to pick
// the matrix width up front so we can size the canvas as a multiple
// of pixelSize. Without this, QRious renders at floor(size/matrix)
// and centers, leaving a white margin whenever size isn't divisible.
const QR_M_BYTE_CAPACITY = [
14, 26, 42, 62, 84, 106, 122, 152, 180, 213,
251, 287, 331, 362, 412, 450, 504, 560, 624, 666,
711, 779, 857, 911, 997, 1059, 1125, 1190, 1264, 1370,
1452, 1538, 1628, 1722, 1809, 1911, 1989, 2099, 2213, 2331,
];
function pickQrMatrixWidth(value) {
const byteLen = new TextEncoder().encode(value).length;
for (let i = 0; i < QR_M_BYTE_CAPACITY.length; i++) {
if (byteLen <= QR_M_BYTE_CAPACITY[i]) return 17 + 4 * (i + 1);
}
return 17 + 4 * 40; // version 40 (177 modules)
}
function paint() {
if (!props.showQr || !canvas.value || !props.value) return;
// Canvas size = matrixWidth × pixelSize, so the QR fills it edge-to-
// edge. pixelSize is floored against the requested size so the QR
// never grows past the host's expected box.
const matrixWidth = pickQrMatrixWidth(props.value);
const pixelSize = Math.max(1, Math.floor(props.size / matrixWidth));
const exactSize = matrixWidth * pixelSize;
new QRious({
element: canvas.value,
size: exactSize,
value: props.value,
background: 'white',
backgroundAlpha: 1,
foreground: 'black',
padding: 0,
level: 'M',
});
}
onMounted(paint);
watch(() => props.value, paint);
watch(() => props.size, paint);
async function copy() {
const ok = await ClipboardManager.copyText(props.value);
if (ok) message.success(t('copied'));
}
function download() {
if (!props.downloadName) return;
FileManager.downloadTextFile(props.value, props.downloadName);
}
</script>
<template>
<div class="qr-panel">
<div class="qr-panel-header">
<a-tag color="green" class="qr-remark">{{ remark }}</a-tag>
<a-tooltip :title="t('copy')">
<a-button size="small" @click="copy">
<template #icon>
<CopyOutlined />
</template>
</a-button>
</a-tooltip>
<a-tooltip v-if="downloadName" :title="t('download')">
<a-button size="small" @click="download">
<template #icon>
<DownloadOutlined />
</template>
</a-button>
</a-tooltip>
</div>
<div v-if="showQr" class="qr-panel-canvas">
<canvas ref="canvas" :style="{ width: `${size}px`, height: `${size}px` }" @click="copy" />
</div>
</div>
</template>
<style scoped>
.qr-panel {
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 8px;
padding: 10px;
margin-bottom: 10px;
display: flex;
flex-direction: column;
gap: 6px;
}
.qr-panel-header {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.qr-remark {
margin: 0;
}
.qr-panel-canvas {
display: flex;
justify-content: center;
padding: 6px 0;
}
.qr-panel-canvas canvas {
cursor: pointer;
display: block;
border-radius: 4px;
/* Drawing buffer is matrix-snapped (smaller than display size for
* dense QRs); scale up crisply so dense and sparse QRs share the
* same on-screen footprint without blurring. */
image-rendering: pixelated;
image-rendering: crisp-edges;
}
</style>
+332
View File
@@ -0,0 +1,332 @@
// Loads the inbound list + sidecar data the page needs (online users,
// last-online-map, default settings) and computes the per-inbound client
// roll-ups the legacy panel surfaces in the popovers.
//
// Live-update model: initial GET on mount, then the WebSocket delta path
// keeps the table fresh — the page subscribes to the server's `traffic`,
// `client_stats`, and `invalidate` events and merges them into local
// refs in-place. The manual refresh button is kept as a fallback.
import { computed, ref, shallowRef } from 'vue';
import { HttpUtil, ObjectUtil } from '@/utils';
import { DBInbound } from '@/models/dbinbound.js';
import { Protocols } from '@/models/inbound.js';
import { setDatepicker } from '@/composables/useDatepicker.js';
export function useInbounds() {
const fetched = ref(false);
const refreshing = ref(false);
// shallowRef because each refresh swaps the array; per-row reactivity is
// unnecessary at the page level (modals work on copies).
const dbInbounds = shallowRef([]);
const clientCount = ref({});
const onlineClients = ref([]);
const lastOnlineMap = ref({});
// Default-settings sidecar fields the table needs for color/expiry math.
const expireDiff = ref(0);
const trafficDiff = ref(0);
const subSettings = ref({
enable: false,
subTitle: '',
subURI: '',
subJsonURI: '',
subJsonEnable: false,
});
const remarkModel = ref('-ieo');
const datepicker = ref('gregorian');
const tgBotEnable = ref(false);
const ipLimitEnable = ref(false);
const pageSize = ref(0);
function isClientOnline(email) {
return onlineClients.value.includes(email);
}
// Roll-up of {clients, active, deactive, depleted, expiring, online,
// comments} for a single inbound. Mirrors getClientCounts in the legacy
// template. Skipped for protocols that don't have multi-user clients
// (HTTP, MIXED, WireGuard) since their settings have no client list.
function rollupClients(dbInbound, inbound) {
const clientStats = Array.isArray(dbInbound.clientStats) ? dbInbound.clientStats : [];
const clients = inbound?.clients || [];
const active = [];
const deactive = [];
const depleted = [];
const expiring = [];
const online = [];
const comments = new Map();
const now = Date.now();
if (dbInbound.enable) {
for (const client of clients) {
if (client.comment) comments.set(client.email, client.comment);
if (client.enable) {
active.push(client.email);
if (isClientOnline(client.email)) online.push(client.email);
} else {
deactive.push(client.email);
}
}
for (const stats of clientStats) {
const exhausted = stats.total > 0 && stats.up + stats.down >= stats.total;
const expired = stats.expiryTime > 0 && stats.expiryTime <= now;
if (expired || exhausted) {
depleted.push(stats.email);
} else {
const expiringSoon =
(stats.expiryTime > 0 && stats.expiryTime - now < expireDiff.value) ||
(stats.total > 0 && stats.total - (stats.up + stats.down) < trafficDiff.value);
if (expiringSoon) expiring.push(stats.email);
}
}
} else {
for (const client of clients) deactive.push(client.email);
}
return {
clients: clients.length,
active,
deactive,
depleted,
expiring,
online,
comments,
};
}
function setInbounds(rows) {
const next = [];
const counts = {};
for (const row of rows) {
const dbInbound = new DBInbound(row);
const parsed = dbInbound.toInbound();
next.push(dbInbound);
const tracked = [
Protocols.VMESS,
Protocols.VLESS,
Protocols.TROJAN,
Protocols.SHADOWSOCKS,
Protocols.HYSTERIA,
];
if (tracked.includes(row.protocol)) {
if (dbInbound.isSS && !parsed.isSSMultiUser) continue;
counts[row.id] = rollupClients(dbInbound, parsed);
}
}
dbInbounds.value = next;
clientCount.value = counts;
fetched.value = true;
}
async function fetchOnlineUsers() {
const msg = await HttpUtil.post('/panel/api/inbounds/onlines');
if (msg?.success) onlineClients.value = msg.obj || [];
}
async function fetchLastOnlineMap() {
const msg = await HttpUtil.post('/panel/api/inbounds/lastOnline');
if (msg?.success && msg.obj) lastOnlineMap.value = msg.obj;
}
async function fetchDefaultSettings() {
const msg = await HttpUtil.post('/panel/setting/defaultSettings');
if (!msg?.success) return;
const s = msg.obj || {};
expireDiff.value = (s.expireDiff ?? 0) * 86400000;
trafficDiff.value = (s.trafficDiff ?? 0) * 1073741824;
tgBotEnable.value = !!s.tgBotEnable;
subSettings.value = {
enable: !!s.subEnable,
subTitle: s.subTitle || '',
subURI: s.subURI || '',
subJsonURI: s.subJsonURI || '',
subJsonEnable: !!s.subJsonEnable,
};
pageSize.value = s.pageSize ?? 0;
remarkModel.value = s.remarkModel || '-ieo';
datepicker.value = s.datepicker || 'gregorian';
// Mirror into the global composable so date-pickers in modals can
// pick the right calendar without re-fetching the settings.
setDatepicker(datepicker.value);
ipLimitEnable.value = !!s.ipLimitEnable;
}
// ============ WebSocket live-update merge ===========================
// The xray traffic job and the node traffic sync job each broadcast
// a `traffic` payload every ~10s. We merge it into onlineClients +
// lastOnlineMap; per-inbound counters arrive in the parallel
// client_stats event below.
function applyTrafficEvent(payload) {
if (!payload || typeof payload !== 'object') return;
if (Array.isArray(payload.onlineClients)) {
onlineClients.value = payload.onlineClients;
}
if (payload.lastOnlineMap && typeof payload.lastOnlineMap === 'object') {
// Merge so a subsequent payload that drops a quiet client doesn't
// wipe their last-seen timestamp.
lastOnlineMap.value = { ...lastOnlineMap.value, ...payload.lastOnlineMap };
}
// Recompute per-inbound rollups so the "online" badges in the
// expand-row table flip without waiting for a full refresh.
rebuildClientCount();
}
// The client_stats payload carries absolute traffic counters for the
// clients that had activity in the latest window plus per-inbound
// totals. Both are absolute (not deltas), so we overwrite in place.
function applyClientStatsEvent(payload) {
if (!payload || typeof payload !== 'object') return;
let touched = false;
if (Array.isArray(payload.inbounds) && payload.inbounds.length > 0) {
const byId = new Map();
for (const row of payload.inbounds) {
if (row && row.id != null) byId.set(row.id, row);
}
for (const ib of dbInbounds.value) {
const upd = byId.get(ib.id);
if (!upd) continue;
if (typeof upd.up === 'number') ib.up = upd.up;
if (typeof upd.down === 'number') ib.down = upd.down;
if (typeof upd.allTime === 'number') ib.allTime = upd.allTime;
if (typeof upd.total === 'number') ib.total = upd.total;
if (typeof upd.enable === 'boolean') ib.enable = upd.enable;
touched = true;
}
}
if (Array.isArray(payload.clients) && payload.clients.length > 0) {
const byEmail = new Map();
for (const row of payload.clients) {
if (row && row.email) byEmail.set(row.email, row);
}
for (const ib of dbInbounds.value) {
if (!Array.isArray(ib.clientStats)) continue;
for (let i = 0; i < ib.clientStats.length; i++) {
const stat = ib.clientStats[i];
const upd = byEmail.get(stat.email);
if (!upd) continue;
if (typeof upd.up === 'number') stat.up = upd.up;
if (typeof upd.down === 'number') stat.down = upd.down;
if (typeof upd.total === 'number') stat.total = upd.total;
if (typeof upd.allTime === 'number') stat.allTime = upd.allTime;
if (typeof upd.expiryTime === 'number') stat.expiryTime = upd.expiryTime;
if (typeof upd.enable === 'boolean') stat.enable = upd.enable;
touched = true;
}
}
}
if (touched) {
dbInbounds.value = [...dbInbounds.value];
rebuildClientCount();
}
}
// The hub may decide a payload is too large to push directly and emit
// an `invalidate` event with the affected dataType instead. For the
// inbounds page that means "the inbound list changed elsewhere — go
// re-fetch via REST".
function applyInvalidate(payload) {
if (!payload || typeof payload !== 'object') return;
if (payload.type === 'inbounds') {
refresh();
}
}
function applyInboundsEvent(payload) {
if (!Array.isArray(payload)) return;
setInbounds(payload);
}
// Recompute the per-inbound roll-up after any in-place mutation.
// Cheap because rollupClients only iterates a single inbound's
// clients + clientStats arrays.
function rebuildClientCount() {
const counts = {};
const tracked = [
Protocols.VMESS,
Protocols.VLESS,
Protocols.TROJAN,
Protocols.SHADOWSOCKS,
Protocols.HYSTERIA,
];
for (const dbInbound of dbInbounds.value) {
const parsed = dbInbound.toInbound();
if (!tracked.includes(dbInbound.protocol)) continue;
if (dbInbound.isSS && !parsed.isSSMultiUser) continue;
counts[dbInbound.id] = rollupClients(dbInbound, parsed);
}
clientCount.value = counts;
}
async function refresh() {
refreshing.value = true;
try {
const msg = await HttpUtil.get('/panel/api/inbounds/list');
if (!msg?.success) return;
await fetchLastOnlineMap();
await fetchOnlineUsers();
setInbounds(Array.isArray(msg.obj) ? msg.obj : []);
} finally {
// Match legacy: keep the spinning-icon state visible briefly so
// a fast network doesn't make the button feel like it didn't fire.
setTimeout(() => { refreshing.value = false; }, 500);
}
}
// Aggregate totals shown in the dashboard summary card. allTime falls
// back to up+down when the per-inbound counter isn't populated yet.
const totals = computed(() => {
let up = 0;
let down = 0;
let allTime = 0;
let clients = 0;
const deactive = [];
const depleted = [];
const expiring = [];
for (const ib of dbInbounds.value) {
up += ib.up || 0;
down += ib.down || 0;
allTime += ib.allTime || (ib.up + ib.down) || 0;
const c = clientCount.value[ib.id];
if (c) {
clients += c.clients;
deactive.push(...c.deactive);
depleted.push(...c.depleted);
expiring.push(...c.expiring);
}
}
return { up, down, allTime, clients, deactive, depleted, expiring };
});
// ObjectUtil reference is wired at module load — keeping a no-op import
// here so the linter doesn't drop it; the legacy search uses it.
void ObjectUtil;
return {
fetched,
refreshing,
dbInbounds,
clientCount,
onlineClients,
lastOnlineMap,
totals,
expireDiff,
trafficDiff,
subSettings,
remarkModel,
datepicker,
tgBotEnable,
ipLimitEnable,
pageSize,
refresh,
fetchDefaultSettings,
applyTrafficEvent,
applyClientStatsEvent,
applyInvalidate,
applyInboundsEvent,
};
}
+101
View File
@@ -0,0 +1,101 @@
<script setup>
import { useI18n } from 'vue-i18n';
import { DownloadOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { HttpUtil, PromiseUtil } from '@/utils';
const { t } = useI18n();
defineProps({
open: { type: Boolean, default: false },
basePath: { type: String, default: '' },
});
const emit = defineEmits(['update:open', 'busy']);
function close() {
emit('update:open', false);
}
function exportDb() {
// The Go endpoint streams x-ui.db as a download. Setting
// window.location triggers a browser download without leaving
// the page (the Go side responds with Content-Disposition: attachment).
window.location = '/panel/api/server/getDb';
}
function importDb() {
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.db';
fileInput.addEventListener('change', async (e) => {
const dbFile = e.target.files?.[0];
if (!dbFile) return;
const formData = new FormData();
formData.append('db', dbFile);
close();
emit('busy', { busy: true, tip: t('pages.index.importDatabase') + '…' });
const upload = await HttpUtil.post('/panel/api/server/importDB', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
if (!upload?.success) {
emit('busy', { busy: false });
return;
}
emit('busy', { busy: true, tip: t('pages.settings.restartPanel') + '…' });
const restart = await HttpUtil.post('/panel/setting/restartPanel');
if (restart?.success) {
await PromiseUtil.sleep(5000);
window.location.reload();
} else {
emit('busy', { busy: false });
}
});
fileInput.click();
}
</script>
<template>
<a-modal :open="open" :title="t('pages.index.backupTitle')" :closable="true" :footer="null" @cancel="close">
<a-list bordered class="backup-list">
<a-list-item class="backup-item">
<a-list-item-meta>
<template #title>{{ t('pages.index.exportDatabase') }}</template>
<template #description>{{ t('pages.index.exportDatabaseDesc') }}</template>
</a-list-item-meta>
<a-button type="primary" @click="exportDb">
<template #icon>
<DownloadOutlined />
</template>
</a-button>
</a-list-item>
<a-list-item class="backup-item">
<a-list-item-meta>
<template #title>{{ t('pages.index.importDatabase') }}</template>
<template #description>{{ t('pages.index.importDatabaseDesc') }}</template>
</a-list-item-meta>
<a-button type="primary" @click="importDb">
<template #icon>
<UploadOutlined />
</template>
</a-button>
</a-list-item>
</a-list>
</a-modal>
</template>
<style scoped>
.backup-list {
width: 100%;
}
.backup-item {
display: flex;
align-items: center;
gap: 16px;
}
</style>
@@ -0,0 +1,106 @@
<script setup>
import { reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { message } from 'ant-design-vue';
import { HttpUtil } from '@/utils';
const { t } = useI18n();
const props = defineProps({
open: { type: Boolean, default: false },
// Populate with the record when editing; null/undefined when adding.
record: { type: Object, default: null },
});
const emit = defineEmits(['update:open', 'saved']);
const form = reactive({ type: 'geosite', alias: '', url: '' });
const saving = ref(false);
const editing = ref(false);
const editId = ref(null);
watch(() => props.open, (next) => {
if (!next) return;
if (props.record) {
editing.value = true;
editId.value = props.record.id;
form.type = props.record.type;
form.alias = props.record.alias;
form.url = props.record.url;
} else {
editing.value = false;
editId.value = null;
form.type = 'geosite';
form.alias = '';
form.url = '';
}
});
function close() {
emit('update:open', false);
}
function validate() {
// Backend expects a filesystem-safe alias; legacy enforces the same regex.
if (!/^[a-z0-9_-]+$/.test(form.alias || '')) {
message.error(t('pages.index.customGeoValidationAlias'));
return false;
}
const u = (form.url || '').trim();
if (!/^https?:\/\//i.test(u)) {
message.error(t('pages.index.customGeoValidationUrl'));
return false;
}
try {
const parsed = new URL(u);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
message.error(t('pages.index.customGeoValidationUrl'));
return false;
}
} catch (_e) {
message.error(t('pages.index.customGeoValidationUrl'));
return false;
}
return true;
}
async function submit() {
if (!validate()) return;
saving.value = true;
try {
const url = editing.value
? `/panel/api/custom-geo/update/${editId.value}`
: '/panel/api/custom-geo/add';
const msg = await HttpUtil.post(url, form);
if (msg?.success) {
emit('saved');
close();
}
} finally {
saving.value = false;
}
}
</script>
<template>
<a-modal :open="open" :title="editing ? t('pages.index.customGeoModalEdit') : t('pages.index.customGeoModalAdd')"
:confirm-loading="saving" :ok-text="t('pages.index.customGeoModalSave')" :cancel-text="t('close')" @ok="submit"
@cancel="close">
<a-form layout="vertical">
<a-form-item :label="t('pages.index.customGeoType')">
<a-select v-model:value="form.type" :disabled="editing">
<a-select-option value="geosite">geosite</a-select-option>
<a-select-option value="geoip">geoip</a-select-option>
</a-select>
</a-form-item>
<a-form-item :label="t('pages.index.customGeoAlias')">
<a-input v-model:value="form.alias" :disabled="editing"
:placeholder="t('pages.index.customGeoAliasPlaceholder')" />
</a-form-item>
<a-form-item :label="t('pages.index.customGeoUrl')">
<a-input v-model:value="form.url" placeholder="https://" />
</a-form-item>
</a-form>
</a-modal>
</template>
@@ -0,0 +1,311 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, message } from 'ant-design-vue';
import {
PlusOutlined,
ReloadOutlined,
EditOutlined,
DeleteOutlined,
InboxOutlined,
} from '@ant-design/icons-vue';
import { HttpUtil, ClipboardManager } from '@/utils';
import CustomGeoFormModal from './CustomGeoFormModal.vue';
const { t } = useI18n();
const props = defineProps({
// Re-fetch the list when the parent collapse expands this section.
active: { type: Boolean, default: false },
});
const list = ref([]);
const loading = ref(false);
const updatingAll = ref(false);
const actionId = ref(null);
const formOpen = ref(false);
const editingRecord = ref(null);
// Computed so column titles re-render after a locale swap.
const columns = computed(() => [
{ title: t('pages.index.customGeoAlias'), key: 'alias', width: 200 },
{ title: t('pages.index.customGeoUrl'), key: 'url', ellipsis: true },
{ title: t('pages.index.customGeoExtColumn'), key: 'extDat', width: 220 },
{ title: t('pages.index.customGeoLastUpdated'), key: 'lastUpdatedAt', width: 140 },
{ title: t('pages.index.customGeoActions'), key: 'action', width: 120 },
]);
async function loadList() {
loading.value = true;
try {
const msg = await HttpUtil.get('/panel/api/custom-geo/list');
if (msg?.success && Array.isArray(msg.obj)) list.value = msg.obj;
} finally {
loading.value = false;
}
}
function openAdd() {
editingRecord.value = null;
formOpen.value = true;
}
function openEdit(record) {
editingRecord.value = record;
formOpen.value = true;
}
function extDisplay(record) {
const fn = record.type === 'geoip'
? `geoip_${record.alias}.dat`
: `geosite_${record.alias}.dat`;
return `ext:${fn}:tag`;
}
async function copyExt(record) {
const text = extDisplay(record);
const ok = await ClipboardManager.copyText(text);
if (ok) message.success(`${t('copied')}: ${text}`);
}
function formatTime(ts) {
if (!ts) return '';
const d = new Date(ts * 1000);
if (isNaN(d.getTime())) return String(ts);
const pad = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
// Tiny inline relative-time formatter so we don't pull in moment.
function relativeTime(ts) {
if (!ts) return '';
const diff = Math.floor(Date.now() / 1000) - ts;
if (diff < 60) return 'just now';
if (diff < 3600) return `${Math.floor(diff / 60)} min ago`;
if (diff < 86400) return `${Math.floor(diff / 3600)} h ago`;
if (diff < 2592000) return `${Math.floor(diff / 86400)} d ago`;
return formatTime(ts);
}
function confirmDelete(record) {
Modal.confirm({
title: t('pages.index.customGeoDelete'),
content: t('pages.index.customGeoDeleteConfirm'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await HttpUtil.post(`/panel/api/custom-geo/delete/${record.id}`);
if (msg?.success) await loadList();
},
});
}
async function downloadOne(id) {
actionId.value = id;
try {
const msg = await HttpUtil.post(`/panel/api/custom-geo/download/${id}`);
if (msg?.success) await loadList();
} finally {
actionId.value = null;
}
}
async function updateAll() {
updatingAll.value = true;
try {
const msg = await HttpUtil.post('/panel/api/custom-geo/update-all');
const ok = msg?.obj?.succeeded?.length || 0;
const failed = msg?.obj?.failed?.length || 0;
if (msg?.success || ok > 0) {
await loadList();
if (failed > 0) message.warning(`Updated ${ok}, failed ${failed}`);
}
} finally {
updatingAll.value = false;
}
}
// Lazy-load: only fetch when the parent collapse opens this panel.
watch(() => props.active, (next) => { if (next) loadList(); }, { immediate: true });
</script>
<template>
<div class="custom-geo-section">
<a-alert type="info" show-icon class="mb-10" :message="t('pages.index.customGeoRoutingHint')" />
<div class="toolbar">
<a-button type="primary" :loading="loading" @click="openAdd">
<template #icon>
<PlusOutlined />
</template>
{{ t('pages.index.customGeoAdd') }}
</a-button>
<a-button :loading="updatingAll" :disabled="!list.length" @click="updateAll">
<template #icon>
<ReloadOutlined />
</template>
{{ t('pages.index.geofilesUpdateAll') }}
</a-button>
<span v-if="list.length" class="custom-geo-count">{{ list.length }}</span>
</div>
<a-table :columns="columns" :data-source="list" :pagination="false" :row-key="(r) => r.id" :loading="loading"
size="small" :scroll="{ x: 760 }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'alias'">
<div class="custom-geo-alias-cell">
<a-tag :color="record.type === 'geoip' ? 'cyan' : 'purple'" class="custom-geo-type-tag">
{{ record.type }}
</a-tag>
<span class="custom-geo-alias">{{ record.alias }}</span>
</div>
</template>
<template v-else-if="column.key === 'url'">
<a-tooltip placement="topLeft" :title="record.url">
<a :href="record.url" target="_blank" rel="noopener noreferrer" class="custom-geo-url">
{{ record.url }}
</a>
</a-tooltip>
</template>
<template v-else-if="column.key === 'extDat'">
<a-tooltip :title="t('copy')">
<code class="custom-geo-ext-code custom-geo-copyable" @click="copyExt(record)">
{{ extDisplay(record) }}
</code>
</a-tooltip>
</template>
<template v-else-if="column.key === 'lastUpdatedAt'">
<a-tooltip v-if="record.lastUpdatedAt" :title="formatTime(record.lastUpdatedAt)">
<span>{{ relativeTime(record.lastUpdatedAt) }}</span>
</a-tooltip>
<span v-else class="custom-geo-muted">—</span>
</template>
<template v-else-if="column.key === 'action'">
<a-space size="small">
<a-tooltip :title="t('pages.index.customGeoEdit')">
<a-button type="link" size="small" @click="openEdit(record)">
<template #icon>
<EditOutlined />
</template>
</a-button>
</a-tooltip>
<a-tooltip :title="t('pages.index.customGeoDownload')">
<a-button type="link" size="small" :loading="actionId === record.id" @click="downloadOne(record.id)">
<template #icon>
<ReloadOutlined />
</template>
</a-button>
</a-tooltip>
<a-tooltip :title="t('pages.index.customGeoDelete')">
<a-button type="link" size="small" danger @click="confirmDelete(record)">
<template #icon>
<DeleteOutlined />
</template>
</a-button>
</a-tooltip>
</a-space>
</template>
</template>
<template #emptyText>
<div class="custom-geo-empty">
<InboxOutlined class="custom-geo-empty-icon" />
<div>{{ t('pages.index.customGeoEmpty') }}</div>
</div>
</template>
</a-table>
<CustomGeoFormModal v-model:open="formOpen" :record="editingRecord" @saved="loadList" />
</div>
</template>
<style scoped>
.mb-10 {
margin-bottom: 10px;
}
.toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 10px;
}
.custom-geo-count {
margin-left: 4px;
padding: 2px 8px;
border-radius: 10px;
background: rgba(0, 0, 0, 0.05);
font-size: 12px;
opacity: 0.75;
}
:global(body.dark) .custom-geo-count {
background: rgba(255, 255, 255, 0.08);
}
.custom-geo-alias-cell {
display: flex;
align-items: center;
gap: 6px;
}
.custom-geo-alias {
font-weight: 500;
word-break: break-all;
}
.custom-geo-type-tag {
margin: 0;
}
.custom-geo-url {
word-break: break-all;
}
.custom-geo-ext-code {
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
padding: 2px 6px;
border-radius: 4px;
background: rgba(0, 0, 0, 0.05);
user-select: all;
}
.custom-geo-copyable:hover {
background: rgba(0, 0, 0, 0.1);
}
:global(body.dark) .custom-geo-ext-code {
background: rgba(255, 255, 255, 0.08);
}
:global(body.dark) .custom-geo-copyable:hover {
background: rgba(255, 255, 255, 0.14);
}
.custom-geo-muted {
opacity: 0.5;
}
.custom-geo-empty {
text-align: center;
padding: 18px 0;
opacity: 0.6;
}
.custom-geo-empty-icon {
font-size: 32px;
margin-bottom: 6px;
display: block;
}
</style>
+420
View File
@@ -0,0 +1,420 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
BarsOutlined,
ControlOutlined,
CloudServerOutlined,
CloudDownloadOutlined,
CloudUploadOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
AreaChartOutlined,
GlobalOutlined,
SwapOutlined,
EyeOutlined,
EyeInvisibleOutlined,
} from '@ant-design/icons-vue';
const { t } = useI18n();
import { HttpUtil, SizeFormatter, TimeFormatter } from '@/utils';
import { theme as themeState, antdThemeConfig } from '@/composables/useTheme.js';
import { useStatus } from '@/composables/useStatus.js';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
import AppSidebar from '@/components/AppSidebar.vue';
import CustomStatistic from '@/components/CustomStatistic.vue';
import TextModal from '@/components/TextModal.vue';
import StatusCard from './StatusCard.vue';
import XrayStatusCard from './XrayStatusCard.vue';
import PanelUpdateModal from './PanelUpdateModal.vue';
import LogModal from './LogModal.vue';
import BackupModal from './BackupModal.vue';
import SystemHistoryModal from './SystemHistoryModal.vue';
import XrayLogModal from './XrayLogModal.vue';
import VersionModal from './VersionModal.vue';
const { status, fetched, refresh } = useStatus();
const { isMobile } = useMediaQuery();
// `/panel/setting/defaultSettings` returns ipLimitEnable; the xray
// card hides its log button when access logs are off.
const ipLimitEnable = ref(false);
HttpUtil.post('/panel/setting/defaultSettings').then((msg) => {
if (msg?.success && msg.obj) ipLimitEnable.value = !!msg.obj.ipLimitEnable;
});
// Panel-update info — fetched once on mount, drives both the badge
// in QuickActions and the contents of PanelUpdateModal.
const panelUpdateInfo = ref({ currentVersion: '', latestVersion: '', updateAvailable: false });
onMounted(() => {
HttpUtil.get('/panel/api/server/getPanelUpdateInfo').then((msg) => {
if (msg?.success && msg.obj) panelUpdateInfo.value = msg.obj;
});
});
const basePath = window.__X_UI_BASE_PATH__ || '';
const requestUri = window.location.pathname;
// In production, dist.go injects window.__X_UI_CUR_VER__ at serve time.
// In dev, Vite serves the HTML directly so the global is missing — fall
// back to currentVersion from the panel-update API once it answers.
const displayVersion = computed(
() => panelUpdateInfo.value?.currentVersion || window.__X_UI_CUR_VER__ || '?',
);
// Hide/reveal the public IPv4/IPv6 — same pattern as legacy.
const showIp = ref(false);
// Modal open state.
const logsOpen = ref(false);
const backupOpen = ref(false);
const panelUpdateOpen = ref(false);
const sysHistoryOpen = ref(false);
const xrayLogsOpen = ref(false);
const versionOpen = ref(false);
const configTextOpen = ref(false);
const configText = ref('');
// Page-level loading overlay; modals can request it via @busy.
const loading = ref(false);
const loadingTip = ref(t('loading'));
function setBusy({ busy, tip }) {
loading.value = busy;
if (tip) loadingTip.value = tip;
}
// Xray controls
async function stopXray() {
await HttpUtil.post('/panel/api/server/stopXrayService');
await refresh();
}
async function restartXray() {
await HttpUtil.post('/panel/api/server/restartXrayService');
await refresh();
}
function openSystemHistory() { sysHistoryOpen.value = true; }
function openXrayLogs() { xrayLogsOpen.value = true; }
function openVersionSwitch() { versionOpen.value = true; }
// Legacy "Config" action — fetch the rendered xray config and show
// it as JSON in the shared TextModal (same UX as main).
async function openConfig() {
loading.value = true;
try {
const msg = await HttpUtil.get('/panel/api/server/getConfigJson');
if (!msg?.success) return;
configText.value = JSON.stringify(msg.obj, null, 2);
configTextOpen.value = true;
} finally {
loading.value = false;
}
}
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout class="index-page" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
<AppSidebar :base-path="basePath" :request-uri="requestUri" />
<a-layout class="content-shell">
<a-layout-content class="content-area">
<a-spin :spinning="loading || !fetched" :delay="200" :tip="loading ? loadingTip : t('loading')" size="large">
<div v-if="!fetched" class="loading-spacer" />
<a-row v-else :gutter="[isMobile ? 8 : 16, 12]">
<a-col :span="24">
<StatusCard :status="status" :is-mobile="isMobile" />
</a-col>
<a-col :xs="24" :lg="12">
<XrayStatusCard :status="status" :is-mobile="isMobile" :ip-limit-enable="ipLimitEnable"
@stop-xray="stopXray" @restart-xray="restartXray" @open-xray-logs="openXrayLogs"
@open-logs="logsOpen = true" @open-version-switch="openVersionSwitch" />
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('menu.link')" hoverable>
<template #actions>
<a-space class="action" @click="logsOpen = true">
<BarsOutlined />
<span v-if="!isMobile">{{ t('pages.index.logs') }}</span>
</a-space>
<a-space class="action" @click="openConfig">
<ControlOutlined />
<span v-if="!isMobile">{{ t('pages.index.config') }}</span>
</a-space>
<a-space class="action" @click="backupOpen = true">
<CloudServerOutlined />
<span v-if="!isMobile">{{ t('pages.index.backupTitle') }}</span>
</a-space>
</template>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card title="3X-UI" hoverable>
<template v-if="panelUpdateInfo.updateAvailable" #extra>
<a-tooltip :title="`${t('pages.index.updatePanel')}: ${panelUpdateInfo.latestVersion}`">
<a-tag color="orange" class="update-tag" @click="panelUpdateOpen = true">
<CloudDownloadOutlined />
{{ panelUpdateInfo.latestVersion }}
<span v-if="!isMobile">{{ t('pages.index.updatePanel') }}</span>
</a-tag>
</a-tooltip>
</template>
<div class="link-tags">
<a href="https://github.com/MHSanaei/3x-ui/releases" target="_blank" rel="noopener noreferrer">
<a-tag color="green">v{{ displayVersion }}</a-tag>
</a>
<a href="https://t.me/XrayUI" target="_blank" rel="noopener noreferrer">
<a-tag color="green">@XrayUI</a-tag>
</a>
<a href="https://github.com/MHSanaei/3x-ui/wiki" target="_blank" rel="noopener noreferrer">
<a-tag color="purple">{{ t('pages.index.documentation') }}</a-tag>
</a>
</div>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('pages.index.operationHours')" hoverable>
<a-tag :color="status.xray.color">
Xray: {{ TimeFormatter.formatSecond(status.appStats.uptime) }}
</a-tag>
<a-tag color="green">OS: {{ TimeFormatter.formatSecond(status.uptime) }}</a-tag>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('pages.index.systemLoad')" hoverable>
<template #extra>
<a-tag color="blue" class="history-tag" @click="openSystemHistory">
<AreaChartOutlined />
{{ t('pages.index.systemHistoryTitle') }}
</a-tag>
</template>
<a-tooltip :title="t('pages.index.systemLoadDesc')">
<a-tag color="green">
{{ status.loads[0] }} | {{ status.loads[1] }} | {{ status.loads[2] }}
</a-tag>
</a-tooltip>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('usage')" hoverable>
<a-tag color="green">
{{ t('pages.index.memory') }}: {{ SizeFormatter.sizeFormat(status.appStats.mem) }}
</a-tag>
<a-tag color="green">
{{ t('pages.index.threads') }}: {{ status.appStats.threads }}
</a-tag>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('pages.index.overallSpeed')" hoverable>
<a-row :gutter="isMobile ? [8, 8] : 0">
<a-col :span="12">
<CustomStatistic :title="t('pages.index.upload')"
:value="SizeFormatter.sizeFormat(status.netIO.up)">
<template #prefix>
<ArrowUpOutlined />
</template>
<template #suffix>/s</template>
</CustomStatistic>
</a-col>
<a-col :span="12">
<CustomStatistic :title="t('pages.index.download')"
:value="SizeFormatter.sizeFormat(status.netIO.down)">
<template #prefix>
<ArrowDownOutlined />
</template>
<template #suffix>/s</template>
</CustomStatistic>
</a-col>
</a-row>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('pages.index.totalData')" hoverable>
<a-row :gutter="isMobile ? [8, 8] : 0">
<a-col :span="12">
<CustomStatistic :title="t('pages.index.sent')"
:value="SizeFormatter.sizeFormat(status.netTraffic.sent)">
<template #prefix>
<CloudUploadOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :span="12">
<CustomStatistic :title="t('pages.index.received')"
:value="SizeFormatter.sizeFormat(status.netTraffic.recv)">
<template #prefix>
<CloudDownloadOutlined />
</template>
</CustomStatistic>
</a-col>
</a-row>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('pages.index.ipAddresses')" hoverable>
<template #extra>
<a-tooltip :title="t('pages.index.toggleIpVisibility')" :placement="isMobile ? 'topRight' : 'top'">
<component :is="showIp ? EyeOutlined : EyeInvisibleOutlined" class="ip-toggle-icon"
@click="showIp = !showIp" />
</a-tooltip>
</template>
<a-row :class="showIp ? 'ip-visible' : 'ip-hidden'" :gutter="isMobile ? [8, 8] : 0">
<a-col :span="isMobile ? 24 : 12">
<CustomStatistic title="IPv4" :value="status.publicIP.ipv4">
<template #prefix>
<GlobalOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :span="isMobile ? 24 : 12">
<CustomStatistic title="IPv6" :value="status.publicIP.ipv6">
<template #prefix>
<GlobalOutlined />
</template>
</CustomStatistic>
</a-col>
</a-row>
</a-card>
</a-col>
<a-col :xs="24" :lg="12">
<a-card :title="t('pages.index.connectionCount')" hoverable>
<a-row :gutter="isMobile ? [8, 8] : 0">
<a-col :span="12">
<CustomStatistic title="TCP" :value="status.tcpCount">
<template #prefix>
<SwapOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :span="12">
<CustomStatistic title="UDP" :value="status.udpCount">
<template #prefix>
<SwapOutlined />
</template>
</CustomStatistic>
</a-col>
</a-row>
</a-card>
</a-col>
</a-row>
</a-spin>
</a-layout-content>
</a-layout>
<PanelUpdateModal v-model:open="panelUpdateOpen" :info="panelUpdateInfo" @busy="setBusy" />
<LogModal v-model:open="logsOpen" />
<BackupModal v-model:open="backupOpen" :base-path="basePath" @busy="setBusy" />
<SystemHistoryModal v-model:open="sysHistoryOpen" :status="status" />
<XrayLogModal v-model:open="xrayLogsOpen" />
<VersionModal v-model:open="versionOpen" :status="status" @busy="setBusy" />
<TextModal v-model:open="configTextOpen" :title="t('pages.index.config')" :content="configText"
file-name="config.json" />
</a-layout>
</a-config-provider>
</template>
<style scoped>
.index-page {
--bg-page: #e6e8ec;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.index-page.is-dark {
--bg-page: #0a1222;
--bg-card: #151f31;
}
.index-page.is-dark.is-ultra {
--bg-page: #050505;
--bg-card: #0c0e12;
}
.index-page :deep(.ant-layout),
.index-page :deep(.ant-layout-content) {
background: transparent;
}
.content-shell {
background: transparent;
}
.content-area {
padding: 24px;
}
@media (max-width: 768px) {
.content-area {
padding: 12px;
padding-top: 64px;
}
}
.loading-spacer {
min-height: calc(100vh - 120px);
}
.action {
cursor: pointer;
justify-content: center;
}
.update-tag {
cursor: pointer;
margin: 0;
display: inline-flex;
align-items: center;
gap: 4px;
}
.history-tag {
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 4px;
margin-inline-end: 0;
}
.link-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.link-tags a {
display: inline-flex;
}
.link-tags :deep(.ant-tag) {
margin-inline-end: 0;
}
.ip-toggle-icon {
cursor: pointer;
font-size: 16px;
}
.ip-hidden :deep(.ant-statistic-content-value) {
filter: blur(6px);
transition: filter 0.2s ease;
}
.ip-visible :deep(.ant-statistic-content-value) {
filter: none;
}
</style>
+355
View File
@@ -0,0 +1,355 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { DownloadOutlined, SyncOutlined } from '@ant-design/icons-vue';
import { HttpUtil, FileManager, PromiseUtil } from '@/utils';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
const { t } = useI18n();
const { isMobile } = useMediaQuery();
const props = defineProps({
open: { type: Boolean, default: false },
});
const emit = defineEmits(['update:open']);
const rows = ref('20');
const level = ref('info');
const syslog = ref(false);
const loading = ref(false);
const logs = ref([]);
const LEVELS = ['DEBUG', 'INFO', 'NOTICE', 'WARNING', 'ERROR'];
const LEVEL_CLASSES = ['level-debug', 'level-info', 'level-notice', 'level-warning', 'level-error'];
// Parses "YYYY-MM-DD HH:MM:SS LEVEL - message". Lines without the
// 3-token header degrade gracefully: the unparsed head becomes the
// level so it still gets color-coded.
function parseLogLine(line) {
const [head, ...rest] = (line || '').split(' - ');
const message = rest.join(' - ');
const parts = head.split(' ');
let date = '';
let time = '';
let levelText;
if (parts.length >= 3) {
[date, time, levelText] = parts;
} else {
levelText = head;
}
const li = LEVELS.indexOf(levelText);
const levelClass = li >= 0 ? LEVEL_CLASSES[li] : 'level-unknown';
let service = '';
let body = message || '';
if (body.startsWith('XRAY:')) {
service = 'XRAY:';
body = body.slice('XRAY:'.length).trimStart();
} else if (body) {
service = 'X-UI:';
}
return { date, time, levelText, levelClass, service, body };
}
const parsedLogs = computed(() => logs.value.map(parseLogLine));
async function refresh() {
loading.value = true;
try {
const msg = await HttpUtil.post(`/panel/api/server/logs/${rows.value}`, {
level: level.value,
syslog: syslog.value,
});
if (msg?.success) {
logs.value = msg.obj || [];
}
await PromiseUtil.sleep(300);
} finally {
loading.value = false;
}
}
function close() {
emit('update:open', false);
}
function download() {
FileManager.downloadTextFile(logs.value.join('\n'), 'x-ui.log');
}
watch(() => props.open, (next) => { if (next) refresh(); });
watch([rows, level, syslog], () => { if (props.open) refresh(); });
const modalWidth = computed(() => (isMobile.value ? '100vw' : '800px'));
</script>
<template>
<a-modal :open="open" :closable="true" :footer="null" :width="modalWidth" :class="{ 'logmodal-mobile': isMobile }"
@cancel="close">
<template #title>
{{ t('pages.index.logs') }}
<SyncOutlined :spin="loading" class="reload-icon" @click="refresh" />
</template>
<a-form layout="inline" class="log-toolbar">
<a-form-item>
<a-input-group compact>
<a-select v-model:value="rows" size="small" :style="{ width: '70px' }">
<a-select-option value="10">10</a-select-option>
<a-select-option value="20">20</a-select-option>
<a-select-option value="50">50</a-select-option>
<a-select-option value="100">100</a-select-option>
<a-select-option value="500">500</a-select-option>
</a-select>
<a-select v-model:value="level" size="small" :style="{ width: '95px' }">
<a-select-option value="debug">Debug</a-select-option>
<a-select-option value="info">Info</a-select-option>
<a-select-option value="notice">Notice</a-select-option>
<a-select-option value="warning">Warning</a-select-option>
<a-select-option value="err">Error</a-select-option>
</a-select>
</a-input-group>
</a-form-item>
<a-form-item>
<a-checkbox v-model:checked="syslog">SysLog</a-checkbox>
</a-form-item>
<a-form-item class="download-item">
<a-button type="primary" @click="download">
<template #icon>
<DownloadOutlined />
</template>
</a-button>
</a-form-item>
</a-form>
<div class="log-container" :class="{ 'log-container-mobile': isMobile }">
<div v-if="parsedLogs.length === 0" class="log-empty">No Record...</div>
<template v-else-if="isMobile">
<div v-for="(log, idx) in parsedLogs" :key="idx" class="log-card">
<div class="log-card-head">
<span v-if="log.date || log.time" class="log-time">
<span v-if="log.time">{{ log.time }}</span>
<span v-if="log.date" class="log-date">{{ log.date }}</span>
</span>
<span v-if="log.levelText" class="log-level-badge" :class="log.levelClass">
{{ log.levelText }}
</span>
</div>
<div v-if="log.body || log.service" class="log-body">
<b v-if="log.service">{{ log.service }}</b>
<span v-if="log.body" class="log-body-text">{{ log.body }}</span>
</div>
</div>
</template>
<template v-else>
<div v-for="(log, idx) in parsedLogs" :key="idx" class="log-line">
<span v-if="log.date || log.time" class="log-stamp">
{{ log.date }}<template v-if="log.date && log.time"> </template>{{ log.time }}
</span>
<span v-if="log.levelText" class="log-level" :class="log.levelClass">
{{ log.levelText }}
</span>
<template v-if="log.body || log.service">
<span> - </span>
<b v-if="log.service">{{ log.service }} </b>
<span>{{ log.body }}</span>
</template>
</div>
</template>
</div>
</a-modal>
</template>
<style scoped>
.reload-icon {
cursor: pointer;
vertical-align: middle;
margin-left: 10px;
}
.log-toolbar {
flex-wrap: wrap;
row-gap: 8px;
}
.log-toolbar .download-item {
margin-left: auto;
}
.log-container {
/* Per-theme palette — overridden in body.dark / [data-theme="ultra-dark"]
below so each level keeps ≥4.5:1 contrast against the container. */
--log-stamp: #3c89e8;
--log-debug: #3c89e8;
--log-info: #008771;
--log-notice: #008771;
--log-warning: #f37b24;
--log-error: #e04141;
--log-unknown: #595959;
--log-divider: rgba(128, 128, 128, 0.18);
margin-top: 12px;
padding: 10px 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
max-height: 60vh;
overflow-y: auto;
border: 1px solid rgba(128, 128, 128, 0.25);
border-radius: 6px;
background: rgba(0, 0, 0, 0.04);
}
.log-stamp {
color: var(--log-stamp);
}
.log-level {
margin-left: 4px;
}
.level-debug {
color: var(--log-debug);
}
.level-info {
color: var(--log-info);
}
.level-notice {
color: var(--log-notice);
}
.level-warning {
color: var(--log-warning);
}
.level-error {
color: var(--log-error);
}
.level-unknown {
color: var(--log-unknown);
}
.log-container-mobile {
padding: 8px;
white-space: normal;
max-height: 70vh;
}
.log-empty {
text-align: center;
opacity: 0.5;
padding: 20px 0;
}
.log-line+.log-line {
margin-top: 2px;
}
.log-card {
border-bottom: 1px solid var(--log-divider);
padding: 8px 0;
}
.log-card:last-child {
border-bottom: 0;
}
.log-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 4px;
}
.log-time {
display: inline-flex;
align-items: baseline;
gap: 6px;
font-weight: 600;
font-size: 12px;
letter-spacing: 0.02em;
}
.log-date {
font-size: 10px;
font-weight: 500;
opacity: 0.55;
}
.log-level-badge {
display: inline-block;
font-size: 10px;
line-height: 14px;
padding: 0 6px;
border-radius: 4px;
border: 1px solid currentColor;
letter-spacing: 0.04em;
font-weight: 600;
white-space: nowrap;
background: color-mix(in srgb, currentColor 14%, transparent);
}
.log-body {
font-size: 12px;
word-break: break-word;
}
.log-body-text {
margin-left: 4px;
}
:global(body.dark) .log-container {
background: rgba(255, 255, 255, 0.03);
border-color: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.88);
--log-stamp: #6aa6ee;
--log-debug: #6aa6ee;
--log-info: #4ed3a6;
--log-notice: #4ed3a6;
--log-warning: #ffb872;
--log-error: #ff7575;
--log-unknown: #b5b5b5;
--log-divider: rgba(255, 255, 255, 0.1);
}
:global([data-theme="ultra-dark"]) .log-container {
--log-stamp: #7fb6f1;
--log-debug: #7fb6f1;
--log-info: #5fd9b0;
--log-notice: #5fd9b0;
--log-warning: #ffcc88;
--log-error: #ff8a8a;
--log-unknown: #c4c4c4;
--log-divider: rgba(255, 255, 255, 0.12);
}
/* Mobile: pull the modal flush with the screen edges. */
:global(.logmodal-mobile) {
top: 0 !important;
padding-bottom: 0 !important;
max-width: 100vw !important;
}
:global(.logmodal-mobile .ant-modal-content) {
border-radius: 0;
height: 100vh;
}
:global(.logmodal-mobile .ant-modal-body) {
padding: 12px;
}
</style>
@@ -0,0 +1,112 @@
<script setup>
import { useI18n } from 'vue-i18n';
import { Modal, message } from 'ant-design-vue';
import { CloudDownloadOutlined } from '@ant-design/icons-vue';
import { HttpUtil, PromiseUtil } from '@/utils';
import axios from 'axios';
const { t } = useI18n();
const props = defineProps({
open: { type: Boolean, default: false },
info: {
type: Object,
default: () => ({ currentVersion: '', latestVersion: '', updateAvailable: false }),
},
});
const emit = defineEmits(['update:open', 'busy']);
function close() {
emit('update:open', false);
}
function updatePanel() {
Modal.confirm({
title: t('pages.index.panelUpdateDialog'),
content: t('pages.index.panelUpdateDialogDesc').replace('#version#', props.info.latestVersion || ''),
okText: t('confirm'),
cancelText: t('cancel'),
onOk: async () => {
const baseTip = t('pages.index.dontRefresh');
const tip = props.info.latestVersion ? `${baseTip} (${props.info.latestVersion})` : baseTip;
close();
emit('busy', { busy: true, tip });
const msg = await HttpUtil.post('/panel/api/server/updatePanel');
if (!msg?.success) {
emit('busy', { busy: false });
return;
}
// Wait for the running process to exit, then poll the new panel
// until it answers (up to ~90s). Reload as soon as it's back.
await PromiseUtil.sleep(5000);
const deadline = Date.now() + 90_000;
let back = false;
while (Date.now() < deadline) {
try {
const r = await axios.get('/panel/api/server/status', { timeout: 2000 });
if (r?.data?.success) { back = true; break; }
} catch (_) { /* still restarting */ }
await PromiseUtil.sleep(2000);
}
if (back) {
message.success(t('pages.index.panelUpdateStartedPopover'));
await PromiseUtil.sleep(800);
}
window.location.reload();
},
});
}
</script>
<template>
<a-modal :open="open" :title="t('pages.index.updatePanel')" :closable="true" :footer="null" @cancel="close">
<a-alert v-if="info.updateAvailable" type="warning" class="mb-12" :message="t('pages.index.panelUpdateDesc')"
show-icon />
<a-list bordered class="version-list">
<a-list-item class="version-list-item">
<span>{{ t('pages.index.currentPanelVersion') }}</span>
<a-tag color="green">v{{ info.currentVersion || '?' }}</a-tag>
</a-list-item>
<a-list-item v-if="info.updateAvailable" class="version-list-item">
<span>{{ t('pages.index.latestPanelVersion') }}</span>
<a-tag color="purple">{{ info.latestVersion || '-' }}</a-tag>
</a-list-item>
<a-list-item v-else class="version-list-item">
<span>{{ t('pages.index.panelUpToDate') }}</span>
<a-tag color="green">{{ t('pages.index.panelUpToDate') }}</a-tag>
</a-list-item>
</a-list>
<div class="actions-row">
<a-button type="primary" :disabled="!info.updateAvailable" @click="updatePanel">
<template #icon>
<CloudDownloadOutlined />
</template>
{{ t('pages.index.updatePanel') }}
</a-button>
</div>
</a-modal>
</template>
<style scoped>
.mb-12 {
margin-bottom: 12px;
}
.version-list {
width: 100%;
}
.version-list-item {
display: flex;
justify-content: space-between;
}
.actions-row {
display: flex;
justify-content: flex-end;
margin-top: 12px;
}
</style>
+96
View File
@@ -0,0 +1,96 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { AreaChartOutlined } from '@ant-design/icons-vue';
import { CPUFormatter, SizeFormatter } from '@/utils';
const { t } = useI18n();
const props = defineProps({
status: { type: Object, required: true },
isMobile: { type: Boolean, default: false },
});
// AD-Vue's default 120px dashboard renders the percent text at ~36px
// which dwarfs the rest of the card. 70 (60 on mobile) plus the
// :deep(.ant-progress-text) override below keep the gauges compact.
const gaugeSize = computed(() => (props.isMobile ? 60 : 70));
// AD-Vue's default unfinished trail (rgba(0,0,0,0.06) /
// rgba(255,255,255,0.08)) is invisible against the light card; a
// neutral mid-gray reads on both themes.
const trailColor = 'rgba(128, 128, 128, 0.25)';
</script>
<template>
<a-card hoverable>
<a-row :gutter="[0, isMobile ? 16 : 0]">
<!-- CPU + Memory -->
<a-col :xs="24" :md="12">
<a-row>
<a-col :span="12" class="text-center">
<a-progress type="dashboard" status="normal" :stroke-color="status.cpu.color" :trail-color="trailColor"
:percent="status.cpu.percent" :width="gaugeSize" />
<div>
<b>{{ t('pages.index.cpu') }}:</b> {{ CPUFormatter.cpuCoreFormat(status.cpuCores) }}
<a-tooltip>
<template #title>
<div><b>{{ t('pages.index.logicalProcessors') }}:</b> {{ status.logicalPro }}</div>
<div><b>{{ t('pages.index.frequency') }}:</b> {{ CPUFormatter.cpuSpeedFormat(status.cpuSpeedMhz) }}
</div>
</template>
<AreaChartOutlined />
</a-tooltip>
</div>
</a-col>
<a-col :span="12" class="text-center">
<a-progress type="dashboard" status="normal" :stroke-color="status.mem.color" :trail-color="trailColor"
:percent="status.mem.percent" :width="gaugeSize" />
<div>
<b>{{ t('pages.index.memory') }}:</b> {{ SizeFormatter.sizeFormat(status.mem.current) }} /
{{ SizeFormatter.sizeFormat(status.mem.total) }}
</div>
</a-col>
</a-row>
</a-col>
<!-- Swap + Disk -->
<a-col :xs="24" :md="12">
<a-row>
<a-col :span="12" class="text-center">
<a-progress type="dashboard" status="normal" :stroke-color="status.swap.color" :trail-color="trailColor"
:percent="status.swap.percent" :width="gaugeSize" />
<div>
<b>{{ t('pages.index.swap') }}:</b> {{ SizeFormatter.sizeFormat(status.swap.current) }} /
{{ SizeFormatter.sizeFormat(status.swap.total) }}
</div>
</a-col>
<a-col :span="12" class="text-center">
<a-progress type="dashboard" status="normal" :stroke-color="status.disk.color" :trail-color="trailColor"
:percent="status.disk.percent" :width="gaugeSize" />
<div>
<b>{{ t('pages.index.storage') }}:</b> {{ SizeFormatter.sizeFormat(status.disk.current) }} /
{{ SizeFormatter.sizeFormat(status.disk.total) }}
</div>
</a-col>
</a-row>
</a-col>
</a-row>
</a-card>
</template>
<style scoped>
.text-center {
text-align: center;
}
/* Pin the percent number to a label-sized 14px — AD-Vue scales it
* from the SVG's intrinsic size, so :width alone leaves it too big. */
:deep(.ant-progress-text) {
font-size: 14px !important;
font-weight: 500;
}
</style>
@@ -0,0 +1,160 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { HttpUtil, SizeFormatter } from '@/utils';
import Sparkline from '@/components/Sparkline.vue';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
const { t } = useI18n();
const { isMobile } = useMediaQuery();
const modalWidth = computed(() => (isMobile.value ? '95vw' : '900px'));
const props = defineProps({
open: { type: Boolean, default: false },
status: { type: Object, required: true },
});
const emit = defineEmits(['update:open']);
// One tab per system metric. The order here drives the tab order in
// the UI; everything else (axis label, tooltip unit, fetch URL) is
// looked up from the active key. Adding another metric is one row.
const metrics = [
{ key: 'cpu', tab: 'CPU', valueMax: 100, unit: '%', stroke: '' },
{ key: 'mem', tab: 'RAM', valueMax: 100, unit: '%', stroke: '#7c4dff' },
{ key: 'netUp', tab: 'Net Up', valueMax: null, unit: 'B/s', stroke: '#1890ff' },
{ key: 'netDown', tab: 'Net Down', valueMax: null, unit: 'B/s', stroke: '#13c2c2' },
{ key: 'online', tab: 'Online', valueMax: null, unit: '', stroke: '#52c41a' },
{ key: 'load1', tab: 'Load 1m', valueMax: null, unit: '', stroke: '#fa8c16' },
{ key: 'load5', tab: 'Load 5m', valueMax: null, unit: '', stroke: '#f5222d' },
{ key: 'load15', tab: 'Load 15m', valueMax: null, unit: '', stroke: '#a0d911' },
];
const activeKey = ref('cpu');
const bucket = ref(2);
const points = ref([]);
const labels = ref([]);
const activeMetric = computed(() => metrics.find((m) => m.key === activeKey.value));
// CPU keeps using the status-card color so the modal visually echoes
// the dot in StatusCard. Non-CPU tabs each get their own constant color.
const strokeColor = computed(() => {
const m = activeMetric.value;
if (m?.stroke) return m.stroke;
return props.status?.cpu?.color || '#008771';
});
function unitFormatter(unit) {
if (unit === 'B/s') {
return (v) => `${SizeFormatter.sizeFormat(Math.max(0, Number(v) || 0))}/s`;
}
if (unit === '%') {
return (v) => `${Number(v).toFixed(1)}%`;
}
// Plain numbers: load averages get two decimals, online client count
// is integer. Heuristic on the unit-less metric key is good enough.
return (v) => {
const n = Number(v) || 0;
if (activeKey.value === 'online') return String(Math.round(n));
return n.toFixed(2);
};
}
const yFormatter = computed(() => unitFormatter(activeMetric.value?.unit ?? ''));
async function fetchBucket() {
const m = activeMetric.value;
if (!m) return;
try {
const url = `/panel/api/server/history/${m.key}/${bucket.value}`;
const msg = await HttpUtil.get(url);
if (msg?.success && Array.isArray(msg.obj)) {
const vals = [];
const labs = [];
for (const p of msg.obj) {
const d = new Date(p.t * 1000);
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
labs.push(bucket.value >= 60 ? `${hh}:${mm}` : `${hh}:${mm}:${ss}`);
vals.push(Number(p.v) || 0);
}
labels.value = labs;
points.value = vals;
} else {
labels.value = [];
points.value = [];
}
} catch (e) {
console.error('Failed to fetch history bucket', e);
labels.value = [];
points.value = [];
}
}
function close() {
emit('update:open', false);
}
watch(() => props.open, (next) => {
if (next) {
activeKey.value = 'cpu';
fetchBucket();
}
});
watch([activeKey, bucket], () => {
if (props.open) fetchBucket();
});
</script>
<template>
<a-modal :open="open" :closable="true" :footer="null" :width="modalWidth" @cancel="close">
<template #title>
{{ t('pages.index.systemHistoryTitle') }}
<a-select v-model:value="bucket" size="small" class="bucket-select">
<a-select-option :value="2">2m</a-select-option>
<a-select-option :value="30">30m</a-select-option>
<a-select-option :value="60">1h</a-select-option>
<a-select-option :value="120">2h</a-select-option>
<a-select-option :value="180">3h</a-select-option>
<a-select-option :value="300">5h</a-select-option>
</a-select>
</template>
<a-tabs v-model:active-key="activeKey" size="small" class="history-tabs">
<a-tab-pane v-for="m in metrics" :key="m.key" :tab="m.tab" />
</a-tabs>
<div class="cpu-chart-wrap">
<div class="cpu-chart-meta">
Timeframe: {{ bucket }} sec per point (total {{ points.length }} points)
</div>
<Sparkline :data="points" :labels="labels" :vb-width="840" :height="220" :stroke="strokeColor" :stroke-width="2.2"
:show-grid="true" :show-axes="true" :tick-count-x="5" :max-points="points.length || 1" :fill-opacity="0.18"
:marker-radius="3.2" :show-tooltip="true" :value-min="0" :value-max="activeMetric?.valueMax ?? null"
:y-formatter="yFormatter" />
</div>
</a-modal>
</template>
<style scoped>
.bucket-select {
width: 80px;
margin-left: 10px;
}
.history-tabs {
margin-bottom: 4px;
}
.cpu-chart-wrap {
padding: 8px 16px 16px;
}
.cpu-chart-meta {
margin-bottom: 10px;
font-size: 11px;
opacity: 0.65;
}
</style>
+147
View File
@@ -0,0 +1,147 @@
<script setup>
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { HttpUtil } from '@/utils';
import CustomGeoSection from './CustomGeoSection.vue';
const { t } = useI18n();
const props = defineProps({
open: { type: Boolean, default: false },
status: { type: Object, required: true },
});
const emit = defineEmits(['update:open', 'busy']);
const activeKey = ref('1');
const versions = ref([]);
const loading = ref(false);
// Geofiles list is hardcoded in the legacy panel — same set of files
// served from /panel/api/server/updateGeofile/{name}.
const GEOFILES = ['geosite.dat', 'geoip.dat', 'geosite_IR.dat', 'geoip_IR.dat', 'geosite_RU.dat', 'geoip_RU.dat'];
async function fetchVersions() {
loading.value = true;
try {
const msg = await HttpUtil.get('/panel/api/server/getXrayVersion');
if (msg?.success) versions.value = msg.obj || [];
} finally {
loading.value = false;
}
}
function close() {
emit('update:open', false);
}
function switchXrayVersion(version) {
Modal.confirm({
title: t('pages.index.xraySwitchVersionDialog'),
content: t('pages.index.xraySwitchVersionDialogDesc').replace('#version#', version),
okText: t('confirm'),
cancelText: t('cancel'),
onOk: async () => {
close();
emit('busy', { busy: true, tip: t('pages.index.dontRefresh') });
try {
await HttpUtil.post(`/panel/api/server/installXray/${version}`);
} finally {
emit('busy', { busy: false });
}
},
});
}
function updateGeofile(fileName) {
const isSingle = !!fileName;
Modal.confirm({
title: t('pages.index.geofileUpdateDialog'),
content: isSingle
? t('pages.index.geofileUpdateDialogDesc').replace('#filename#', fileName)
: t('pages.index.geofilesUpdateDialogDesc'),
okText: t('confirm'),
cancelText: t('cancel'),
onOk: async () => {
close();
emit('busy', { busy: true, tip: t('pages.index.dontRefresh') });
const url = isSingle
? `/panel/api/server/updateGeofile/${fileName}`
: '/panel/api/server/updateGeofile';
try {
await HttpUtil.post(url);
} finally {
emit('busy', { busy: false });
}
},
});
}
watch(() => props.open, (next) => { if (next) fetchVersions(); });
</script>
<template>
<a-modal :open="open" :title="t('pages.index.xrayUpdates')" :closable="true" :footer="null" @cancel="close">
<a-spin :spinning="loading">
<a-collapse v-model:active-key="activeKey" accordion>
<a-collapse-panel key="1" header="Xray">
<a-alert type="warning" class="mb-12" :message="t('pages.index.xraySwitchClickDesk')" show-icon />
<a-list bordered class="version-list">
<a-list-item v-for="(version, index) in versions" :key="version" class="version-list-item">
<a-tag :color="index % 2 === 0 ? 'purple' : 'green'">{{ version }}</a-tag>
<a-radio :checked="version === `v${status?.xray?.version}`" @click="switchXrayVersion(version)" />
</a-list-item>
</a-list>
</a-collapse-panel>
<a-collapse-panel key="2" header="Geofiles">
<a-list bordered class="version-list">
<a-list-item v-for="(file, index) in GEOFILES" :key="file" class="version-list-item">
<a-tag :color="index % 2 === 0 ? 'purple' : 'green'">{{ file }}</a-tag>
<a-tooltip :title="t('update')">
<ReloadOutlined class="reload-icon" @click="updateGeofile(file)" />
</a-tooltip>
</a-list-item>
</a-list>
<div class="actions-row">
<a-button @click="updateGeofile('')">{{ t('pages.index.geofilesUpdateAll') }}</a-button>
</div>
</a-collapse-panel>
<a-collapse-panel key="3" :header="t('pages.index.customGeoTitle')">
<CustomGeoSection :active="activeKey === '3'" />
</a-collapse-panel>
</a-collapse>
</a-spin>
</a-modal>
</template>
<style scoped>
.mb-12 {
margin-bottom: 12px;
}
.version-list {
width: 100%;
}
.version-list-item {
display: flex;
justify-content: space-between;
align-items: center;
}
.reload-icon {
cursor: pointer;
font-size: 16px;
margin-right: 8px;
}
.actions-row {
display: flex;
justify-content: flex-end;
margin-top: 12px;
}
</style>
+357
View File
@@ -0,0 +1,357 @@
<script setup>
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { DownloadOutlined, SyncOutlined } from '@ant-design/icons-vue';
import { HttpUtil, FileManager, IntlUtil, PromiseUtil } from '@/utils';
import { useDatepicker } from '@/composables/useDatepicker.js';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
const { t } = useI18n();
const { datepicker } = useDatepicker();
const { isMobile } = useMediaQuery();
const props = defineProps({
open: { type: Boolean, default: false },
});
const emit = defineEmits(['update:open']);
const rows = ref('20');
const filter = ref('');
const showDirect = ref(true);
const showBlocked = ref(true);
const showProxy = ref(true);
const loading = ref(false);
const logs = ref([]);
// Newest first.
const orderedLogs = computed(() => [...logs.value].reverse());
const EVENT_LABELS = { 0: 'DIRECT', 1: 'BLOCKED', 2: 'PROXY' };
const EVENT_COLORS = { 0: 'green', 1: 'red', 2: 'blue' };
function eventLabel(ev) { return EVENT_LABELS[ev] || String(ev ?? ''); }
function eventColor(ev) { return EVENT_COLORS[ev] || 'default'; }
function fullDate(value) {
return IntlUtil.formatDate(value, datepicker.value);
}
function shortTime(value) {
if (!value) return '';
const d = new Date(value);
if (isNaN(d.getTime())) return '';
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
async function refresh() {
loading.value = true;
try {
const msg = await HttpUtil.post(`/panel/api/server/xraylogs/${rows.value}`, {
filter: filter.value,
showDirect: showDirect.value,
showBlocked: showBlocked.value,
showProxy: showProxy.value,
});
if (msg?.success) logs.value = msg.obj || [];
await PromiseUtil.sleep(300);
} finally {
loading.value = false;
}
}
function close() {
emit('update:open', false);
}
function download() {
if (!Array.isArray(logs.value) || logs.value.length === 0) {
FileManager.downloadTextFile('', 'x-ui.log');
return;
}
const lines = logs.value.map((l) => {
try {
const dt = l.DateTime ? new Date(l.DateTime) : null;
const dateStr = dt && !isNaN(dt.getTime()) ? dt.toISOString() : '';
const eventText = eventLabel(l.Event);
const emailPart = l.Email ? ` Email=${l.Email}` : '';
return `${dateStr} FROM=${l.FromAddress || ''} TO=${l.ToAddress || ''} INBOUND=${l.Inbound || ''} OUTBOUND=${l.Outbound || ''}${emailPart} EVENT=${eventText}`.trim();
} catch (_e) {
return JSON.stringify(l);
}
}).join('\n');
FileManager.downloadTextFile(lines, 'x-ui.log');
}
watch(() => props.open, (next) => { if (next) refresh(); });
watch([rows, showDirect, showBlocked, showProxy], () => { if (props.open) refresh(); });
const modalWidth = computed(() => (isMobile.value ? '100vw' : '80vw'));
</script>
<template>
<a-modal :open="open" :closable="true" :footer="null" :width="modalWidth"
:class="{ 'xraylog-modal-mobile': isMobile }" @cancel="close">
<template #title>
{{ t('pages.index.logs') }}
<SyncOutlined :spin="loading" class="reload-icon" @click="refresh" />
</template>
<a-form layout="inline" class="log-toolbar">
<a-form-item>
<a-select v-model:value="rows" size="small" :style="{ width: '70px' }">
<a-select-option value="10">10</a-select-option>
<a-select-option value="20">20</a-select-option>
<a-select-option value="50">50</a-select-option>
<a-select-option value="100">100</a-select-option>
<a-select-option value="500">500</a-select-option>
</a-select>
</a-form-item>
<a-form-item :label="t('filter')" class="filter-item">
<a-input v-model:value="filter" size="small" @keyup.enter="refresh" />
</a-form-item>
<a-form-item>
<a-checkbox v-model:checked="showDirect">Direct</a-checkbox>
<a-checkbox v-model:checked="showBlocked">Blocked</a-checkbox>
<a-checkbox v-model:checked="showProxy">Proxy</a-checkbox>
</a-form-item>
<a-form-item class="download-item">
<a-button type="primary" @click="download">
<template #icon>
<DownloadOutlined />
</template>
</a-button>
</a-form-item>
</a-form>
<div class="log-container" :class="{ 'log-container-mobile': isMobile }">
<div v-if="orderedLogs.length === 0" class="log-empty">No Record...</div>
<template v-else-if="isMobile">
<div v-for="(log, idx) in orderedLogs" :key="idx" class="log-card">
<div class="log-card-head">
<span class="log-time" :title="fullDate(log.DateTime)">{{ shortTime(log.DateTime) }}</span>
<a-tag :color="eventColor(log.Event)" class="log-event-tag">{{ eventLabel(log.Event) }}</a-tag>
</div>
<div class="log-route">
<span class="log-addr">{{ log.FromAddress }}</span>
<span class="log-arrow"></span>
<span class="log-addr">{{ log.ToAddress }}</span>
</div>
<div class="log-meta">
<span v-if="log.Inbound" class="log-meta-pair">
<span class="log-meta-key">in</span>
<span class="log-meta-val">{{ log.Inbound }}</span>
</span>
<span v-if="log.Outbound" class="log-meta-pair">
<span class="log-meta-key">out</span>
<span class="log-meta-val">{{ log.Outbound }}</span>
</span>
<span v-if="log.Email" class="log-meta-pair">
<span class="log-meta-key">email</span>
<span class="log-meta-val">{{ log.Email }}</span>
</span>
</div>
</div>
</template>
<table v-else class="xraylog-table">
<thead>
<tr>
<th>Date</th>
<th>From</th>
<th>To</th>
<th>Inbound</th>
<th>Outbound</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr v-for="(log, idx) in orderedLogs" :key="idx" :class="`log-row-${log.Event}`">
<td><b>{{ fullDate(log.DateTime) }}</b></td>
<td>{{ log.FromAddress }}</td>
<td>{{ log.ToAddress }}</td>
<td>{{ log.Inbound }}</td>
<td>{{ log.Outbound }}</td>
<td>{{ log.Email }}</td>
</tr>
</tbody>
</table>
</div>
</a-modal>
</template>
<style scoped>
.reload-icon {
cursor: pointer;
vertical-align: middle;
margin-left: 10px;
}
.log-toolbar {
flex-wrap: wrap;
row-gap: 8px;
}
.log-toolbar .filter-item {
flex: 1 1 160px;
}
.log-toolbar .download-item {
margin-left: auto;
}
.log-container {
/* Per-theme palette — overridden in body.dark / [data-theme="ultra-dark"]
below so blocked/proxy rows keep ≥4.5:1 contrast on darker surfaces. */
--log-blocked: #e04141;
--log-proxy: #3c89e8;
--log-divider: rgba(128, 128, 128, 0.18);
margin-top: 12px;
padding: 10px 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
line-height: 1.5;
max-height: 60vh;
overflow: auto;
border: 1px solid rgba(128, 128, 128, 0.25);
border-radius: 6px;
background: rgba(0, 0, 0, 0.04);
}
.log-container-mobile {
padding: 8px;
font-size: 12px;
max-height: 70vh;
}
.log-empty {
text-align: center;
opacity: 0.5;
padding: 20px 0;
}
.log-card {
border-bottom: 1px solid var(--log-divider);
padding: 8px 0;
}
.log-card:last-child {
border-bottom: 0;
}
.log-card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 4px;
}
.log-time {
font-weight: 600;
font-size: 12px;
letter-spacing: 0.02em;
}
.log-event-tag {
margin: 0;
font-size: 10px;
line-height: 16px;
padding: 0 6px;
}
.log-route {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
font-size: 12px;
margin-bottom: 4px;
}
.log-addr {
word-break: break-all;
}
.log-arrow {
opacity: 0.5;
}
.log-meta {
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
font-size: 11px;
opacity: 0.75;
}
.log-meta-pair {
display: inline-flex;
align-items: baseline;
gap: 4px;
word-break: break-all;
}
.log-meta-key {
font-size: 10px;
text-transform: uppercase;
opacity: 0.6;
letter-spacing: 0.04em;
}
:global(body.dark) .log-container {
background: rgba(255, 255, 255, 0.03);
border-color: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.88);
--log-blocked: #ff7575;
--log-proxy: #6aa6ee;
--log-divider: rgba(255, 255, 255, 0.1);
}
:global([data-theme="ultra-dark"]) .log-container {
--log-blocked: #ff8a8a;
--log-proxy: #7fb6f1;
--log-divider: rgba(255, 255, 255, 0.12);
}
/* Mobile: pull the modal flush with the screen edges. */
:global(.xraylog-modal-mobile) {
top: 0 !important;
padding-bottom: 0 !important;
max-width: 100vw !important;
}
:global(.xraylog-modal-mobile .ant-modal-content) {
border-radius: 0;
height: 100vh;
}
:global(.xraylog-modal-mobile .ant-modal-body) {
padding: 12px;
}
.xraylog-table {
border-collapse: collapse;
width: 100%;
}
.xraylog-table td,
.xraylog-table th {
padding: 2px 15px;
text-align: left;
}
.xraylog-table .log-row-1 {
color: var(--log-blocked);
}
.xraylog-table .log-row-2 {
color: var(--log-proxy);
}
</style>
+151
View File
@@ -0,0 +1,151 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
BarsOutlined,
PoweroffOutlined,
ReloadOutlined,
ToolOutlined,
} from '@ant-design/icons-vue';
const { t } = useI18n();
const props = defineProps({
status: { type: Object, required: true },
isMobile: { type: Boolean, default: false },
ipLimitEnable: { type: Boolean, default: false },
});
defineEmits(['stop-xray', 'restart-xray', 'open-logs', 'open-xray-logs', 'open-version-switch']);
const XRAY_STATE_KEYS = {
running: 'pages.index.xrayStatusRunning',
stop: 'pages.index.xrayStatusStop',
error: 'pages.index.xrayStatusError',
};
const stateText = computed(() =>
t(XRAY_STATE_KEYS[props.status.xray.state] ?? 'pages.index.xrayStatusUnknown'),
);
function badgeAnimationClass(color) {
if (color === 'green') return 'xray-running-animation';
if (color === 'orange') return 'xray-stop-animation';
if (color === 'red') return 'xray-error-animation';
return 'xray-processing-animation';
}
</script>
<template>
<a-card hoverable>
<template #title>
<a-space direction="horizontal">
<span>{{ t('pages.index.xrayStatus') }}</span>
<a-tag v-if="isMobile && status.xray.version && status.xray.version !== 'Unknown'" color="green">
v{{ status.xray.version }}
</a-tag>
</a-space>
</template>
<template #extra>
<template v-if="status.xray.state !== 'error'">
<a-badge status="processing" :class="['xray-processing-animation', badgeAnimationClass(status.xray.color)]"
:text="stateText" :color="status.xray.color" />
</template>
<template v-else>
<a-popover>
<template #title>
<a-row type="flex" align="middle" justify="space-between">
<a-col><span>{{ t('pages.index.xrayStatusError') }}</span></a-col>
<a-col>
<BarsOutlined class="cursor-pointer" @click="$emit('open-logs')" />
</a-col>
</a-row>
</template>
<template #content>
<span v-for="(line, i) in (status.xray.errorMsg || '').split('\n')" :key="i" class="error-line">
{{ line }}
</span>
</template>
<a-badge status="processing" :text="stateText" :color="status.xray.color"
:class="['xray-processing-animation', 'xray-error-animation']" />
</a-popover>
</template>
</template>
<template #actions>
<a-space v-if="ipLimitEnable" direction="horizontal" class="action" @click="$emit('open-xray-logs')">
<BarsOutlined />
<span v-if="!isMobile">{{ t('pages.index.logs') }}</span>
</a-space>
<a-space direction="horizontal" class="action" @click="$emit('stop-xray')">
<PoweroffOutlined />
<span v-if="!isMobile">{{ t('pages.index.stopXray') }}</span>
</a-space>
<a-space direction="horizontal" class="action" @click="$emit('restart-xray')">
<ReloadOutlined />
<span v-if="!isMobile">{{ t('pages.index.restartXray') }}</span>
</a-space>
<a-space direction="horizontal" class="action" @click="$emit('open-version-switch')">
<ToolOutlined />
<span v-if="!isMobile">
{{ status.xray.version && status.xray.version !== 'Unknown'
? `v${status.xray.version}`
: t('pages.index.xraySwitch') }}
</span>
</a-space>
</template>
</a-card>
</template>
<style scoped>
.action {
cursor: pointer;
justify-content: center;
}
.error-line {
display: block;
max-width: 400px;
white-space: pre-wrap;
}
.cursor-pointer {
cursor: pointer;
}
</style>
<style>
/* Legacy xray-*-animation classes — they need to be global so they
* pierce the AD-Vue badge's internal DOM (.ant-badge-status-*). */
.xray-processing-animation .ant-badge-status-dot {
animation: xray-pulse 1.2s linear infinite;
}
.xray-running-animation .ant-badge-status-processing::after {
border-color: #1677ff;
}
.xray-stop-animation .ant-badge-status-processing::after {
border-color: #fa8c16;
}
.xray-error-animation .ant-badge-status-processing::after {
border-color: #f5222d;
}
@keyframes xray-pulse {
0%,
50%,
100% {
transform: scale(1);
opacity: 1;
}
10% {
transform: scale(1.5);
opacity: 0.2;
}
}
</style>
+350
View File
@@ -0,0 +1,350 @@
<script setup>
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { UserOutlined, LockOutlined, KeyOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { HttpUtil, LanguageManager } from '@/utils';
import {
antdThemeConfig,
currentTheme,
theme as themeState,
} from '@/composables/useTheme.js';
import ThemeSwitchLogin from '@/components/ThemeSwitchLogin.vue';
const { t } = useI18n();
const headlineWords = computed(() => [t('pages.login.hello'), t('pages.login.title')]);
const HEADLINE_INTERVAL_MS = 2000;
const headlineIndex = ref(0);
let headlineTimer = null;
onMounted(() => {
headlineTimer = window.setInterval(() => {
headlineIndex.value = (headlineIndex.value + 1) % headlineWords.value.length;
}, HEADLINE_INTERVAL_MS);
});
onBeforeUnmount(() => {
if (headlineTimer != null) window.clearInterval(headlineTimer);
});
const fetched = ref(false);
const submitting = ref(false);
const twoFactorEnable = ref(false);
const user = reactive({
username: '',
password: '',
twoFactorCode: '',
});
const basePath = window.__X_UI_BASE_PATH__ || '';
onMounted(async () => {
const msg = await HttpUtil.post('/getTwoFactorEnable');
if (msg.success) {
twoFactorEnable.value = !!msg.obj;
}
fetched.value = true;
});
async function login() {
submitting.value = true;
try {
const msg = await HttpUtil.post('/login', user);
if (msg.success) {
window.location.href = basePath + 'panel/';
}
} finally {
submitting.value = false;
}
}
const lang = ref(LanguageManager.getLanguage());
function onLangChange(next) {
LanguageManager.setLanguage(next);
}
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout class="login-app" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
<a-layout-content class="login-content">
<div class="waves-header">
<div class="waves-inner-header"></div>
<svg class="waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
<defs>
<path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" />
</defs>
<g class="parallax">
<use xlink:href="#gentle-wave" x="48" y="0" />
<use xlink:href="#gentle-wave" x="48" y="3" />
<use xlink:href="#gentle-wave" x="48" y="5" />
<use xlink:href="#gentle-wave" x="48" y="7" />
</g>
</svg>
</div>
<a-row type="flex" justify="center" align="middle" class="login-row">
<a-col class="login-card">
<div v-if="!fetched" class="login-loading">
<a-spin size="large" />
</div>
<div v-else>
<div class="login-settings">
<a-popover :overlay-class-name="currentTheme" :title="t('menu.settings')" placement="bottomRight"
trigger="click">
<template #content>
<a-space direction="vertical" :size="10" class="settings-popover">
<ThemeSwitchLogin />
<span>{{ t('pages.settings.language') }}</span>
<a-select v-model:value="lang" class="lang-select" @change="onLangChange">
<a-select-option v-for="l in LanguageManager.supportedLanguages" :key="l.value"
:value="l.value">
<span :aria-label="l.name">{{ l.icon }}</span>
&nbsp;&nbsp;<span>{{ l.name }}</span>
</a-select-option>
</a-select>
</a-space>
</template>
<a-button shape="circle">
<template #icon>
<SettingOutlined />
</template>
</a-button>
</a-popover>
</div>
<a-row justify="center">
<a-col :span="24">
<h2 class="login-title">
<Transition name="headline" mode="out-in">
<b :key="headlineIndex">{{ headlineWords[headlineIndex] }}</b>
</Transition>
</h2>
</a-col>
</a-row>
<a-form layout="vertical" @submit.prevent="login">
<a-form-item>
<a-input v-model:value="user.username" autocomplete="username" name="username"
:placeholder="t('username')" autofocus required>
<template #prefix>
<UserOutlined />
</template>
</a-input>
</a-form-item>
<a-form-item>
<a-input-password v-model:value="user.password" autocomplete="current-password" name="password"
:placeholder="t('password')" required>
<template #prefix>
<LockOutlined />
</template>
</a-input-password>
</a-form-item>
<a-form-item v-if="twoFactorEnable">
<a-input v-model:value="user.twoFactorCode" autocomplete="one-time-code" name="twoFactorCode"
:placeholder="t('twoFactorCode')" required>
<template #prefix>
<KeyOutlined />
</template>
</a-input>
</a-form-item>
<a-form-item>
<a-row justify="center">
<a-button type="primary" html-type="submit" :loading="submitting" block>
{{ submitting ? '' : t('login') }}
</a-button>
</a-row>
</a-form-item>
</a-form>
</div>
</a-col>
</a-row>
</a-layout-content>
</a-layout>
</a-config-provider>
</template>
<style scoped>
.login-app {
--bg-page: #c7ebe2;
--bg-wave-header: #dbf5ed;
--bg-card: #ffffff;
--color-title: #008771;
--shadow-card: 0 2px 8px rgba(0, 0, 0, 0.09);
--wave-fill: rgba(0, 135, 113, 0.12);
--wave-fill-bottom: #c7ebe2;
min-height: 100vh;
}
.login-app.is-dark {
--bg-page: #222d42;
--bg-wave-header: #0a1222;
--bg-card: #151f31;
--color-title: rgba(255, 255, 255, 0.92);
--shadow-card: 0 4px 16px rgba(0, 0, 0, 0.45);
--wave-fill: #222d42;
--wave-fill-bottom: #222d42;
}
.login-app.is-dark.is-ultra {
--bg-page: #0f2d32;
--bg-wave-header: #0a2227;
--bg-card: #0c0e12;
--wave-fill: #1f4d52;
--wave-fill-bottom: #0f2d32;
}
.login-app,
.login-app :deep(.ant-layout-content) {
background: transparent;
}
.login-app {
background: var(--bg-page);
}
.login-card {
background: var(--bg-card);
box-shadow: var(--shadow-card);
}
.login-title {
color: var(--color-title);
}
.login-settings {
display: flex;
justify-content: flex-end;
margin-bottom: 8px;
}
.settings-popover {
min-width: 220px;
}
.lang-select {
width: 100%;
}
.login-content {
position: relative;
}
.login-row {
position: relative;
z-index: 1;
min-height: 100vh;
padding: 24px 0;
}
.login-card {
width: clamp(280px, 90vw, 300px);
border-radius: 2rem;
padding: clamp(2rem, 5vw, 4rem) 1.5rem;
transition: background 0.3s, box-shadow 0.3s;
}
.login-loading {
text-align: center;
padding: 40px 0;
}
.login-title {
text-align: center;
margin-bottom: 32px;
font-size: 2rem;
font-weight: 500;
min-height: 2.5rem;
}
.login-title b {
display: inline-block;
}
.headline-enter-active,
.headline-leave-active {
transition: opacity 0.4s ease, transform 0.4s ease;
}
.headline-enter-from {
opacity: 0;
transform: translateY(-12px);
}
.headline-leave-to {
opacity: 0;
transform: translateY(12px);
}
.waves-header {
position: fixed;
inset: 0 0 auto 0;
width: 100%;
z-index: 0;
pointer-events: none;
background: var(--bg-wave-header);
}
.waves-inner-header {
height: 50vh;
width: 100%;
}
.waves {
position: relative;
display: block;
width: 100%;
height: 15vh;
min-height: 100px;
max-height: 150px;
margin-bottom: -8px;
}
.parallax>use {
fill: var(--wave-fill);
animation: move-forever 25s cubic-bezier(0.55, 0.5, 0.45, 0.5) infinite;
}
.parallax>use:nth-child(1) {
animation-delay: -2s;
animation-duration: 4s;
opacity: 0.2;
}
.parallax>use:nth-child(2) {
animation-delay: -3s;
animation-duration: 7s;
opacity: 0.4;
}
.parallax>use:nth-child(3) {
animation-delay: -4s;
animation-duration: 10s;
opacity: 0.6;
}
.parallax>use:nth-child(4) {
animation-delay: -5s;
animation-duration: 13s;
fill: var(--wave-fill-bottom);
opacity: 1;
}
@keyframes move-forever {
0% {
transform: translate3d(-90px, 0, 0);
}
100% {
transform: translate3d(85px, 0, 0);
}
}
</style>
+202
View File
@@ -0,0 +1,202 @@
<script setup>
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { message } from 'ant-design-vue';
const props = defineProps({
open: { type: Boolean, default: false },
mode: { type: String, default: 'add' }, // 'add' | 'edit'
node: { type: Object, default: null },
testConnection: { type: Function, required: true },
save: { type: Function, required: true }, // (payload) => Promise<msg>
});
const emit = defineEmits(['update:open']);
const { t } = useI18n();
// Default form shape — used for "add" mode and to reset between
// edits. Sane defaults: HTTPS, port 2053, base path '/', enabled.
function defaultForm() {
return {
id: 0,
name: '',
remark: '',
scheme: 'https',
address: '',
port: 2053,
basePath: '/',
apiToken: '',
enable: true,
};
}
const form = reactive(defaultForm());
const submitting = ref(false);
const testing = ref(false);
const testResult = ref(null); // { status, latencyMs, xrayVersion, error }
// Reset the form whenever the modal is opened. In edit mode we copy
// the existing node into the form fields; in add mode we wipe back
// to defaults so a previous edit doesn't leak through.
watch(
() => props.open,
(open) => {
if (!open) return;
Object.assign(form, defaultForm());
testResult.value = null;
if (props.mode === 'edit' && props.node) {
Object.assign(form, props.node);
}
},
);
const title = computed(() =>
props.mode === 'edit' ? t('pages.nodes.editNode') : t('pages.nodes.addNode'),
);
function close() {
if (!submitting.value) emit('update:open', false);
}
function buildPayload() {
return {
id: form.id || 0,
name: form.name?.trim() || '',
remark: form.remark?.trim() || '',
scheme: form.scheme || 'https',
address: form.address?.trim() || '',
port: Number(form.port) || 0,
basePath: form.basePath?.trim() || '/',
apiToken: form.apiToken?.trim() || '',
enable: !!form.enable,
};
}
async function onTest() {
testing.value = true;
testResult.value = null;
try {
const payload = buildPayload();
if (!payload.address || !payload.port) {
message.error(t('pages.nodes.toasts.fillRequired'));
return;
}
const msg = await props.testConnection(payload);
if (msg?.success) {
testResult.value = msg.obj;
} else {
testResult.value = { status: 'offline', error: msg?.msg || 'unknown error' };
}
} finally {
testing.value = false;
}
}
async function onSave() {
const payload = buildPayload();
if (!payload.name || !payload.address || !payload.port) {
message.error(t('pages.nodes.toasts.fillRequired'));
return;
}
submitting.value = true;
try {
const msg = await props.save(payload);
if (msg?.success) {
emit('update:open', false);
}
} finally {
submitting.value = false;
}
}
</script>
<template>
<a-modal :open="open" :title="title" :confirm-loading="submitting" :ok-text="t('save')" :cancel-text="t('cancel')"
:mask-closable="false" width="640px" @ok="onSave" @cancel="close">
<a-form layout="vertical" :model="form">
<a-row :gutter="16">
<a-col :span="12">
<a-form-item :label="t('pages.nodes.name')" required>
<a-input v-model:value="form.name" :placeholder="t('pages.nodes.namePlaceholder')" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item :label="t('pages.nodes.remark')">
<a-input v-model:value="form.remark" />
</a-form-item>
</a-col>
</a-row>
<a-row :gutter="16">
<a-col :span="6">
<a-form-item :label="t('pages.nodes.scheme')">
<a-select v-model:value="form.scheme">
<a-select-option value="https">https</a-select-option>
<a-select-option value="http">http</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item :label="t('pages.nodes.address')" required>
<a-input v-model:value="form.address" :placeholder="t('pages.nodes.addressPlaceholder')" />
</a-form-item>
</a-col>
<a-col :span="6">
<a-form-item :label="t('pages.nodes.port')" required>
<a-input-number v-model:value="form.port" :min="1" :max="65535" style="width: 100%" />
</a-form-item>
</a-col>
</a-row>
<a-row :gutter="16">
<a-col :span="12">
<a-form-item :label="t('pages.nodes.basePath')">
<a-input v-model:value="form.basePath" placeholder="/" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item :label="t('pages.nodes.enable')">
<a-switch v-model:checked="form.enable" />
</a-form-item>
</a-col>
</a-row>
<a-form-item :label="t('pages.nodes.apiToken')" required>
<a-input-password v-model:value="form.apiToken" :placeholder="t('pages.nodes.apiTokenPlaceholder')" />
<div class="hint">{{ t('pages.nodes.apiTokenHint') }}</div>
</a-form-item>
<div class="test-row">
<a-button :loading="testing" @click="onTest">
{{ t('pages.nodes.testConnection') }}
</a-button>
<div v-if="testResult" class="test-result">
<a-alert v-if="testResult.status === 'online'" type="success" show-icon
:message="t('pages.nodes.connectionOk', { ms: testResult.latencyMs })"
:description="testResult.xrayVersion ? `Xray ${testResult.xrayVersion}` : undefined" />
<a-alert v-else type="error" show-icon :message="t('pages.nodes.connectionFailed')"
:description="testResult.error" />
</div>
</div>
</a-form>
</a-modal>
</template>
<style scoped>
.hint {
font-size: 12px;
opacity: 0.6;
margin-top: 4px;
}
.test-row {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 8px;
}
.test-result {
width: 100%;
}
</style>
@@ -0,0 +1,116 @@
<script setup>
import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { HttpUtil } from '@/utils';
import Sparkline from '@/components/Sparkline.vue';
const { t } = useI18n();
const props = defineProps({
node: { type: Object, required: true },
// Bucket size in seconds — matches the SystemHistoryModal selector.
bucket: { type: Number, default: 30 },
});
// Two parallel series so the panel renders CPU and Mem side-by-side
// in a single fetch round-trip per refresh.
const cpuPoints = ref([]);
const cpuLabels = ref([]);
const memPoints = ref([]);
const memLabels = ref([]);
const REFRESH_MS = 15000;
let timer = null;
function bucketLabel(unixSec) {
const d = new Date(unixSec * 1000);
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
if (props.bucket >= 60) return `${hh}:${mm}`;
const ss = String(d.getSeconds()).padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
async function fetchSeries(metric) {
try {
const url = `/panel/api/nodes/history/${props.node.id}/${metric}/${props.bucket}`;
const msg = await HttpUtil.get(url);
if (msg?.success && Array.isArray(msg.obj)) {
const vals = [];
const labs = [];
for (const p of msg.obj) {
labs.push(bucketLabel(p.t));
vals.push(Math.max(0, Math.min(100, Number(p.v) || 0)));
}
return { vals, labs };
}
} catch (e) {
console.error('node history fetch failed', metric, e);
}
return { vals: [], labs: [] };
}
async function refresh() {
const [cpu, mem] = await Promise.all([fetchSeries('cpu'), fetchSeries('mem')]);
cpuPoints.value = cpu.vals;
cpuLabels.value = cpu.labs;
memPoints.value = mem.vals;
memLabels.value = mem.labs;
}
onMounted(() => {
refresh();
timer = window.setInterval(refresh, REFRESH_MS);
});
onBeforeUnmount(() => {
if (timer != null) window.clearInterval(timer);
});
// If the parent table re-emits a node row with a different id (rare —
// happens when the list is sorted or filtered while the panel is open),
// reset and re-fetch.
watch(() => props.node?.id, (a, b) => {
if (a !== b) refresh();
});
</script>
<template>
<div class="node-history-panel">
<div class="series">
<div class="series-title">{{ t('pages.nodes.cpu') }}</div>
<Sparkline :data="cpuPoints" :labels="cpuLabels" :vb-width="640" :height="120" stroke="#008771" :show-grid="true"
:show-axes="true" :tick-count-x="4" :max-points="cpuPoints.length || 1" :fill-opacity="0.18"
:marker-radius="2.6" :show-tooltip="true" />
</div>
<div class="series">
<div class="series-title">{{ t('pages.nodes.mem') }}</div>
<Sparkline :data="memPoints" :labels="memLabels" :vb-width="640" :height="120" stroke="#7c4dff" :show-grid="true"
:show-axes="true" :tick-count-x="4" :max-points="memPoints.length || 1" :fill-opacity="0.18"
:marker-radius="2.6" :show-tooltip="true" />
</div>
</div>
</template>
<style scoped>
.node-history-panel {
padding: 8px 0;
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
}
@media (max-width: 768px) {
.node-history-panel {
grid-template-columns: 1fr;
gap: 12px;
}
}
.series-title {
font-size: 12px;
font-weight: 500;
opacity: 0.75;
margin-bottom: 4px;
}
</style>
+206
View File
@@ -0,0 +1,206 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
EditOutlined,
DeleteOutlined,
PlusOutlined,
ThunderboltOutlined,
ExclamationCircleOutlined,
} from '@ant-design/icons-vue';
import NodeHistoryPanel from './NodeHistoryPanel.vue';
const props = defineProps({
nodes: { type: Array, default: () => [] },
loading: { type: Boolean, default: false },
isMobile: { type: Boolean, default: false },
});
const emit = defineEmits([
'add',
'edit',
'delete',
'probe',
'toggle-enable',
]);
const { t } = useI18n();
// Render the address column as a clickable URL so admins can jump to
// the remote panel directly from the list.
const dataSource = computed(() =>
props.nodes.map((n) => ({
...n,
url: `${n.scheme}://${n.address}:${n.port}${n.basePath || '/'}`,
key: n.id,
})),
);
function statusColor(status) {
switch (status) {
case 'online': return 'green';
case 'offline': return 'red';
default: return 'default';
}
}
// Relative-time formatter — keeps the column compact and avoids
// pulling dayjs just for this single use.
function relativeTime(unixSeconds) {
if (!unixSeconds) return t('pages.nodes.never');
const diffSec = Math.max(0, Math.floor(Date.now() / 1000 - unixSeconds));
if (diffSec < 5) return t('pages.nodes.justNow');
if (diffSec < 60) return `${diffSec}s`;
if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m`;
if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h`;
return `${Math.floor(diffSec / 86400)}d`;
}
function formatUptime(secs) {
if (!secs) return '-';
const days = Math.floor(secs / 86400);
const hours = Math.floor((secs % 86400) / 3600);
if (days > 0) return `${days}d ${hours}h`;
const mins = Math.floor((secs % 3600) / 60);
if (hours > 0) return `${hours}h ${mins}m`;
return `${mins}m`;
}
function formatPct(p) {
if (typeof p !== 'number' || isNaN(p)) return '-';
return `${p.toFixed(1)}%`;
}
</script>
<template>
<a-card size="small" hoverable>
<div class="toolbar">
<a-button type="primary" @click="emit('add')">
<template #icon>
<PlusOutlined />
</template>
{{ t('pages.nodes.addNode') }}
</a-button>
</div>
<a-table :data-source="dataSource" :pagination="false" :loading="loading" :scroll="{ x: 'max-content' }"
size="middle" row-key="id">
<template #expandedRowRender="{ record }">
<NodeHistoryPanel :node="record" />
</template>
<a-table-column :title="t('pages.nodes.name')" data-index="name" :ellipsis="true">
<template #default="{ record }">
<div class="name-cell">
<span class="name">{{ record.name }}</span>
<span v-if="record.remark" class="remark">{{ record.remark }}</span>
</div>
</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.address')" data-index="url" :ellipsis="true">
<template #default="{ record }">
<a :href="record.url" target="_blank" rel="noopener noreferrer">{{ record.url }}</a>
</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.status')" data-index="status" align="center">
<template #default="{ record }">
<a-space :size="4">
<a-badge
:status="statusColor(record.status) === 'green' ? 'success' : (statusColor(record.status) === 'red' ? 'error' : 'default')" />
<span>{{ t(`pages.nodes.statusValues.${record.status || 'unknown'}`) }}</span>
<a-tooltip v-if="record.lastError" :title="record.lastError">
<ExclamationCircleOutlined style="color: #faad14" />
</a-tooltip>
</a-space>
</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.cpu')" data-index="cpuPct" align="center" :width="90">
<template #default="{ record }">{{ formatPct(record.cpuPct) }}</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.mem')" data-index="memPct" align="center" :width="90">
<template #default="{ record }">{{ formatPct(record.memPct) }}</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.xrayVersion')" data-index="xrayVersion" align="center">
<template #default="{ record }">
{{ record.xrayVersion || '-' }}
</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.uptime')" data-index="uptimeSecs" align="center">
<template #default="{ record }">{{ formatUptime(record.uptimeSecs) }}</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.latency')" data-index="latencyMs" align="center" :width="100">
<template #default="{ record }">
<span v-if="record.latencyMs > 0">{{ record.latencyMs }} ms</span>
<span v-else>-</span>
</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.lastHeartbeat')" data-index="lastHeartbeat" align="center" :width="120">
<template #default="{ record }">{{ relativeTime(record.lastHeartbeat) }}</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.enable')" data-index="enable" align="center" :width="80">
<template #default="{ record }">
<a-switch :checked="record.enable" size="small" @change="(v) => emit('toggle-enable', record, v)" />
</template>
</a-table-column>
<a-table-column :title="t('pages.nodes.actions')" align="center" :width="160" fixed="right">
<template #default="{ record }">
<a-space>
<a-tooltip :title="t('pages.nodes.probe')">
<a-button type="text" size="small" @click="emit('probe', record)">
<template #icon>
<ThunderboltOutlined />
</template>
</a-button>
</a-tooltip>
<a-tooltip :title="t('edit')">
<a-button type="text" size="small" @click="emit('edit', record)">
<template #icon>
<EditOutlined />
</template>
</a-button>
</a-tooltip>
<a-tooltip :title="t('delete')">
<a-button type="text" size="small" danger @click="emit('delete', record)">
<template #icon>
<DeleteOutlined />
</template>
</a-button>
</a-tooltip>
</a-space>
</template>
</a-table-column>
</a-table>
</a-card>
</template>
<style scoped>
.toolbar {
margin-bottom: 12px;
display: flex;
justify-content: space-between;
align-items: center;
}
.name-cell {
display: flex;
flex-direction: column;
}
.name {
font-weight: 500;
}
.remark {
font-size: 12px;
opacity: 0.65;
}
</style>
+216
View File
@@ -0,0 +1,216 @@
<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, message } from 'ant-design-vue';
import {
CloudServerOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
ThunderboltOutlined,
} from '@ant-design/icons-vue';
import { theme as themeState, antdThemeConfig } from '@/composables/useTheme.js';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
import AppSidebar from '@/components/AppSidebar.vue';
import CustomStatistic from '@/components/CustomStatistic.vue';
import NodeList from './NodeList.vue';
import NodeFormModal from './NodeFormModal.vue';
import { useNodes } from './useNodes.js';
import { useWebSocket } from '@/composables/useWebSocket.js';
const { t } = useI18n();
const {
nodes,
loading,
fetched,
totals,
applyNodesEvent,
create,
update,
remove,
setEnable,
testConnection,
probe,
} = useNodes();
// Live updates — NodeHeartbeatJob pushes the fresh list every 10s.
useWebSocket({ nodes: applyNodesEvent });
const { isMobile } = useMediaQuery();
const basePath = window.__X_UI_BASE_PATH__ || '';
const requestUri = window.location.pathname;
// === Form modal state =================================================
const formOpen = ref(false);
const formMode = ref('add');
const formNode = ref(null);
function onAdd() {
formMode.value = 'add';
formNode.value = null;
formOpen.value = true;
}
function onEdit(node) {
formMode.value = 'edit';
formNode.value = { ...node };
formOpen.value = true;
}
// Save callback the modal hands its payload to. We hide the create vs.
// update branching here so the modal stays mode-agnostic.
async function onSave(payload) {
if (formMode.value === 'edit' && formNode.value?.id) {
return update(formNode.value.id, payload);
}
return create(payload);
}
function onDelete(node) {
Modal.confirm({
title: t('pages.nodes.deleteConfirmTitle', { name: node.name }),
content: t('pages.nodes.deleteConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await remove(node.id);
if (msg?.success) message.success(t('pages.nodes.toasts.deleted'));
},
});
}
async function onProbe(node) {
const msg = await probe(node.id);
if (msg?.success && msg.obj) {
if (msg.obj.status === 'online') {
message.success(t('pages.nodes.connectionOk', { ms: msg.obj.latencyMs }));
} else {
message.error(msg.obj.error || t('pages.nodes.toasts.probeFailed'));
}
}
}
async function onToggleEnable(node, next) {
await setEnable(node.id, next);
}
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout class="nodes-page" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
<AppSidebar :base-path="basePath" :request-uri="requestUri" />
<a-layout class="content-shell">
<a-layout-content id="content-layout" class="content-area">
<a-spin :spinning="!fetched" :delay="200" tip="Loading…" size="large">
<div v-if="!fetched" class="loading-spacer" />
<a-row v-else :gutter="[isMobile ? 8 : 16, isMobile ? 0 : 12]">
<!-- Summary statistics card -->
<a-col :span="24">
<a-card size="small" hoverable class="summary-card">
<a-row :gutter="[16, 12]">
<a-col :sm="12" :md="6">
<CustomStatistic :title="t('pages.nodes.totalNodes')" :value="String(totals.total)">
<template #prefix>
<CloudServerOutlined />
</template>
</CustomStatistic>
</a-col>
<a-col :sm="12" :md="6">
<CustomStatistic :title="t('pages.nodes.onlineNodes')" :value="String(totals.online)">
<template #prefix>
<CheckCircleOutlined style="color: #52c41a" />
</template>
</CustomStatistic>
</a-col>
<a-col :sm="12" :md="6">
<CustomStatistic :title="t('pages.nodes.offlineNodes')" :value="String(totals.offline)">
<template #prefix>
<CloseCircleOutlined style="color: #ff4d4f" />
</template>
</CustomStatistic>
</a-col>
<a-col :sm="12" :md="6">
<CustomStatistic :title="t('pages.nodes.avgLatency')"
:value="totals.avgLatency > 0 ? `${totals.avgLatency} ms` : '-'">
<template #prefix>
<ThunderboltOutlined />
</template>
</CustomStatistic>
</a-col>
</a-row>
</a-card>
</a-col>
<!-- Node table -->
<a-col :span="24">
<NodeList :nodes="nodes" :loading="loading" :is-mobile="isMobile" @add="onAdd" @edit="onEdit"
@delete="onDelete" @probe="onProbe" @toggle-enable="onToggleEnable" />
</a-col>
</a-row>
</a-spin>
</a-layout-content>
</a-layout>
<NodeFormModal v-model:open="formOpen" :mode="formMode" :node="formNode" :test-connection="testConnection"
:save="onSave" />
</a-layout>
</a-config-provider>
</template>
<style scoped>
.nodes-page {
--bg-page: #e6e8ec;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.nodes-page.is-dark {
--bg-page: #0a1222;
--bg-card: #151f31;
}
.nodes-page.is-dark.is-ultra {
--bg-page: #050505;
--bg-card: #0c0e12;
}
.nodes-page :deep(.ant-layout),
.nodes-page :deep(.ant-layout-content) {
background: transparent;
}
.content-shell {
background: transparent;
}
.content-area {
padding: 24px;
}
@media (max-width: 768px) {
.content-area {
padding: 8px;
}
}
.loading-spacer {
min-height: calc(100vh - 120px);
}
.summary-card {
padding: 16px;
}
@media (max-width: 768px) {
.summary-card {
padding: 8px;
}
}
</style>
+120
View File
@@ -0,0 +1,120 @@
// Loads the node list and runs CRUD/probe actions against the
// /panel/api/nodes/* endpoints. Live updates arrive over WebSocket
// (pushed by NodeHeartbeatJob every 10s) so we don't poll.
import { computed, onMounted, ref, shallowRef } from 'vue';
import { HttpUtil } from '@/utils';
export function useNodes() {
const nodes = shallowRef([]);
const loading = ref(false);
const fetched = ref(false);
async function refresh() {
loading.value = true;
try {
const msg = await HttpUtil.get('/panel/api/nodes/list');
if (msg?.success) {
nodes.value = Array.isArray(msg.obj) ? msg.obj : [];
}
fetched.value = true;
} finally {
loading.value = false;
}
}
// Replaces the local list with the snapshot pushed by the heartbeat job.
// shallowRef means a fresh assignment is enough to retrigger reactivity;
// we always assign a new array so Vue notices.
function applyNodesEvent(payload) {
if (Array.isArray(payload)) {
nodes.value = payload;
if (!fetched.value) fetched.value = true;
}
}
async function create(payload) {
const msg = await HttpUtil.post('/panel/api/nodes/add', payload);
if (msg?.success) await refresh();
return msg;
}
async function update(id, payload) {
const msg = await HttpUtil.post(`/panel/api/nodes/update/${id}`, payload);
if (msg?.success) await refresh();
return msg;
}
async function remove(id) {
const msg = await HttpUtil.post(`/panel/api/nodes/del/${id}`);
if (msg?.success) await refresh();
return msg;
}
async function setEnable(id, enable) {
const msg = await HttpUtil.post(`/panel/api/nodes/setEnable/${id}`, { enable });
if (msg?.success) await refresh();
return msg;
}
// testConnection probes a transient (unsaved) node config so the form
// can validate before save. Returns the ProbeResultUI shape from Go.
async function testConnection(payload) {
const msg = await HttpUtil.post('/panel/api/nodes/test', payload);
return msg;
}
// probe forces an immediate heartbeat against an already-saved node.
async function probe(id) {
const msg = await HttpUtil.post(`/panel/api/nodes/probe/${id}`);
if (msg?.success) await refresh();
return msg;
}
// Aggregate cards on the dashboard. Computed off the live list so a
// refresh (or a WS push) picks up new totals automatically.
const totals = computed(() => {
const list = nodes.value;
let online = 0;
let offline = 0;
let latencySum = 0;
let latencyCount = 0;
for (const n of list) {
if (!n.enable) continue;
if (n.status === 'online') {
online += 1;
if (n.latencyMs > 0) {
latencySum += n.latencyMs;
latencyCount += 1;
}
} else if (n.status === 'offline') {
offline += 1;
}
}
return {
total: list.length,
online,
offline,
avgLatency: latencyCount > 0 ? Math.round(latencySum / latencyCount) : 0,
};
});
// Initial fetch — WebSocket takes over after the first heartbeat tick
// (~10s) but the page should populate immediately on mount.
onMounted(refresh);
return {
nodes,
loading,
fetched,
totals,
refresh,
applyNodesEvent,
create,
update,
remove,
setEnable,
testConnection,
probe,
};
}
+425
View File
@@ -0,0 +1,425 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { HttpUtil, LanguageManager } from '@/utils';
import SettingListItem from '@/components/SettingListItem.vue';
const { t } = useI18n();
const props = defineProps({
// Reactive AllSetting instance shared with the parent page.
allSetting: { type: Object, required: true },
});
// Remark model — legacy stores it as a single string where index 0 is
// the separator char and the rest is the order of model keys
// (i=Inbound, e=Email, o=Other). Surface it as two v-models that read
// and write the underlying string.
const remarkModels = { i: 'Inbound', e: 'Email', o: 'Other' };
const remarkSeparators = [' ', '-', '_', '@', ':', '~', '|', ',', '.', '/'];
const remarkModel = computed({
get: () => {
const rm = props.allSetting.remarkModel || '';
return rm.length > 1 ? rm.substring(1).split('') : [];
},
set: (value) => {
const sep = (props.allSetting.remarkModel || '-').charAt(0);
props.allSetting.remarkModel = sep + value.join('');
},
});
const remarkSeparator = computed({
get: () => {
const rm = props.allSetting.remarkModel || '-';
return rm.length > 1 ? rm.charAt(0) : '-';
},
set: (value) => {
const tail = (props.allSetting.remarkModel || '-').substring(1);
props.allSetting.remarkModel = value + tail;
},
});
const remarkSample = computed(() => {
const parts = remarkModel.value.map((k) => remarkModels[k]);
return parts.length === 0 ? '' : parts.join(remarkSeparator.value);
});
const datepicker = computed({
get: () => props.allSetting.datepicker || 'gregorian',
set: (value) => { props.allSetting.datepicker = value; },
});
const datepickerList = [
{ name: 'Gregorian (Standard)', value: 'gregorian' },
{ name: 'Jalalian (شمسی)', value: 'jalalian' },
];
// Language is stored client-side in a cookie, NOT in AllSetting. The
// legacy panel reloads on change so the Go side renders templates in
// the new language.
const lang = ref(LanguageManager.getLanguage());
function onLangChange() {
LanguageManager.setLanguage(lang.value);
}
// LDAP inbound tags are CSV on the wire; expose as an array so the
// multi-select v-model works directly.
const ldapInboundTagList = computed({
get: () => {
const csv = props.allSetting.ldapInboundTags || '';
return csv.length ? csv.split(',').map((s) => s.trim()).filter(Boolean) : [];
},
set: (list) => {
props.allSetting.ldapInboundTags = Array.isArray(list) ? list.join(',') : '';
},
});
const inboundOptions = ref([]);
async function loadInboundTags() {
const msg = await HttpUtil.get('/panel/api/inbounds/list');
if (msg?.success && Array.isArray(msg.obj)) {
inboundOptions.value = msg.obj.map((ib) => ({
label: `${ib.tag} (${ib.protocol}@${ib.port})`,
value: ib.tag,
}));
} else {
inboundOptions.value = [];
}
}
onMounted(loadInboundTags);
</script>
<template>
<a-collapse default-active-key="1">
<a-collapse-panel key="1" :header="t('pages.settings.panelSettings')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.remarkModel') }}</template>
<template #description>{{ t('pages.settings.sampleRemark') }}: <i>#{{ remarkSample }}</i></template>
<template #control>
<a-input-group :style="{ width: '100%' }">
<a-select v-model:value="remarkModel" mode="multiple"
:style="{ paddingRight: '.5rem', minWidth: '80%', width: 'auto' }">
<a-select-option v-for="(label, key) in remarkModels" :key="key" :value="key">
{{ label }}
</a-select-option>
</a-select>
<a-select v-model:value="remarkSeparator" :style="{ width: '20%' }">
<a-select-option v-for="sep in remarkSeparators" :key="sep" :value="sep">{{ sep }}</a-select-option>
</a-select>
</a-input-group>
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.panelListeningIP') }}</template>
<template #description>{{ t('pages.settings.panelListeningIPDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.webListen" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.panelListeningDomain') }}</template>
<template #description>{{ t('pages.settings.panelListeningDomainDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.webDomain" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.panelPort') }}</template>
<template #description>{{ t('pages.settings.panelPortDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.webPort" :min="1" :max="65535" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.panelUrlPath') }}</template>
<template #description>{{ t('pages.settings.panelUrlPathDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.webBasePath" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.sessionMaxAge') }}</template>
<template #description>{{ t('pages.settings.sessionMaxAgeDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.sessionMaxAge" :min="60" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.pageSize') }}</template>
<template #description>{{ t('pages.settings.pageSizeDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.pageSize" :min="0" :step="5" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.language') }}</template>
<template #control>
<a-select v-model:value="lang" :style="{ width: '100%' }" @change="onLangChange">
<a-select-option v-for="l in LanguageManager.supportedLanguages" :key="l.value" :value="l.value"
:label="l.value">
<span role="img" :aria-label="l.name">{{ l.icon }}</span>
&nbsp;&nbsp;<span>{{ l.name }}</span>
</a-select-option>
</a-select>
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="2" :header="t('pages.settings.notifications')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.expireTimeDiff') }}</template>
<template #description>{{ t('pages.settings.expireTimeDiffDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.expireDiff" :min="0" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.trafficDiff') }}</template>
<template #description>{{ t('pages.settings.trafficDiffDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.trafficDiff" :min="0" :style="{ width: '100%' }" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="3" :header="t('pages.settings.certs')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.publicKeyPath') }}</template>
<template #description>{{ t('pages.settings.publicKeyPathDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.webCertFile" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.privateKeyPath') }}</template>
<template #description>{{ t('pages.settings.privateKeyPathDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.webKeyFile" type="text" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="4" :header="t('pages.settings.externalTraffic')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.externalTrafficInformEnable') }}</template>
<template #description>{{ t('pages.settings.externalTrafficInformEnableDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.externalTrafficInformEnable" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.externalTrafficInformURI') }}</template>
<template #description>{{ t('pages.settings.externalTrafficInformURIDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.externalTrafficInformURI" placeholder="(http|https)://domain[:port]/path/"
type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.restartXrayOnClientDisable') }}</template>
<template #description>{{ t('pages.settings.restartXrayOnClientDisableDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.restartXrayOnClientDisable" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="5" :header="t('pages.settings.dateAndTime')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.timeZone') }}</template>
<template #description>{{ t('pages.settings.timeZoneDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.timeLocation" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.datepicker') }}</template>
<template #description>{{ t('pages.settings.datepickerDescription') }}</template>
<template #control>
<a-select v-model:value="datepicker" :style="{ width: '100%' }">
<a-select-option v-for="item in datepickerList" :key="item.value" :value="item.value">
{{ item.name }}
</a-select-option>
</a-select>
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="6" header="LDAP">
<SettingListItem paddings="small">
<template #title>Enable LDAP sync</template>
<template #control>
<a-switch v-model:checked="allSetting.ldapEnable" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>LDAP host</template>
<template #control>
<a-input v-model:value="allSetting.ldapHost" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>LDAP port</template>
<template #control>
<a-input-number v-model:value="allSetting.ldapPort" :min="1" :max="65535" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Use TLS (LDAPS)</template>
<template #control>
<a-switch v-model:checked="allSetting.ldapUseTLS" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Bind DN</template>
<template #control>
<a-input v-model:value="allSetting.ldapBindDN" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('password') }}</template>
<template #control>
<a-input-password v-model:value="allSetting.ldapPassword" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Base DN</template>
<template #control>
<a-input v-model:value="allSetting.ldapBaseDN" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>User filter</template>
<template #control>
<a-input v-model:value="allSetting.ldapUserFilter" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>User attribute (username/email)</template>
<template #control>
<a-input v-model:value="allSetting.ldapUserAttr" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>VLESS flag attribute</template>
<template #control>
<a-input v-model:value="allSetting.ldapVlessField" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Generic flag attribute (optional)</template>
<template #description>If set, overrides VLESS flag e.g. shadowInactive.</template>
<template #control>
<a-input v-model:value="allSetting.ldapFlagField" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Truthy values</template>
<template #description>Comma-separated; default: true,1,yes,on</template>
<template #control>
<a-input v-model:value="allSetting.ldapTruthyValues" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Invert flag</template>
<template #description>Enable when the attribute means disabled (e.g. shadowInactive).</template>
<template #control>
<a-switch v-model:checked="allSetting.ldapInvertFlag" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Sync schedule</template>
<template #description>Cron-like string, e.g. @every 1m</template>
<template #control>
<a-input v-model:value="allSetting.ldapSyncCron" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Inbound tags</template>
<template #description>Inbounds that LDAP sync may auto-create or auto-delete clients on.</template>
<template #control>
<a-select v-model:value="ldapInboundTagList" mode="multiple" :style="{ width: '100%' }">
<a-select-option v-for="opt in inboundOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</a-select-option>
</a-select>
<div v-if="inboundOptions.length === 0" class="ldap-no-inbounds">
No inbounds found. Create one in Inbounds first.
</div>
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Auto create clients</template>
<template #control>
<a-switch v-model:checked="allSetting.ldapAutoCreate" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Auto delete clients</template>
<template #control>
<a-switch v-model:checked="allSetting.ldapAutoDelete" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Default total (GB)</template>
<template #control>
<a-input-number v-model:value="allSetting.ldapDefaultTotalGB" :min="0" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Default expiry (days)</template>
<template #control>
<a-input-number v-model:value="allSetting.ldapDefaultExpiryDays" :min="0" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Default IP limit</template>
<template #control>
<a-input-number v-model:value="allSetting.ldapDefaultLimitIP" :min="0" :style="{ width: '100%' }" />
</template>
</SettingListItem>
</a-collapse-panel>
</a-collapse>
</template>
<style scoped>
.ldap-no-inbounds {
margin-top: 6px;
color: #999;
font-size: 12px;
}
</style>
+240
View File
@@ -0,0 +1,240 @@
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, message } from 'ant-design-vue';
import { HttpUtil, RandomUtil } from '@/utils';
import SettingListItem from '@/components/SettingListItem.vue';
import TwoFactorModal from './TwoFactorModal.vue';
const { t } = useI18n();
const props = defineProps({
allSetting: { type: Object, required: true },
});
// 2FA modal state — both the "set" (enabling) and "confirm" (changing
// password / disabling) flows route through the same component.
const tfa = reactive({
open: false,
title: '',
description: '',
token: '',
type: 'set',
// resolveConfirm is called by the modal's @confirm with the success bool;
// it then routes the value back to whichever flow opened the modal.
resolveConfirm: (_success) => { },
});
function openTfa({ title, description = '', token = '', type, onConfirm }) {
tfa.title = title;
tfa.description = description;
tfa.token = token;
tfa.type = type;
tfa.resolveConfirm = onConfirm;
tfa.open = true;
}
function onTfaConfirm(success) {
tfa.resolveConfirm(success);
}
const user = reactive({
oldUsername: '',
oldPassword: '',
newUsername: '',
newPassword: '',
});
const updating = ref(false);
async function sendUpdateUser() {
updating.value = true;
try {
const msg = await HttpUtil.post('/panel/setting/updateUser', user);
if (msg?.success) {
// Force re-login at the standard logout path; basePath is handled
// by the Go router so a relative redirect is correct here.
const basePath = window.__X_UI_BASE_PATH__ || '';
window.location.replace(`${basePath}logout`);
}
} finally {
updating.value = false;
}
}
function updateUser() {
if (props.allSetting.twoFactorEnable) {
openTfa({
title: t('pages.settings.security.twoFactorModalChangeCredentialsTitle'),
description: t('pages.settings.security.twoFactorModalChangeCredentialsStep'),
token: props.allSetting.twoFactorToken,
type: 'confirm',
onConfirm: (ok) => { if (ok) sendUpdateUser(); },
});
} else {
sendUpdateUser();
}
}
// === API Token =========================================================
// Surfaces the panel's API token so a remote central panel can register
// this instance as a node. Lazy-loaded on tab mount; rotation requires
// confirmation since it invalidates any cached value upstream.
const apiToken = ref('');
const apiTokenLoading = ref(false);
const apiTokenRotating = ref(false);
async function loadApiToken() {
apiTokenLoading.value = true;
try {
const msg = await HttpUtil.get('/panel/setting/getApiToken');
if (msg?.success) apiToken.value = msg.obj || '';
} finally {
apiTokenLoading.value = false;
}
}
async function copyApiToken() {
if (!apiToken.value) return;
try {
await navigator.clipboard.writeText(apiToken.value);
message.success(t('copySuccess'));
} catch (_e) {
// navigator.clipboard can be undefined on http:// — fall back to
// a transient input + execCommand path.
const ta = document.createElement('textarea');
ta.value = apiToken.value;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
message.success(t('copySuccess'));
}
}
function regenerateApiToken() {
Modal.confirm({
title: t('pages.nodes.regenerateConfirm'),
okText: t('confirm'),
cancelText: t('cancel'),
okType: 'danger',
onOk: async () => {
apiTokenRotating.value = true;
try {
const msg = await HttpUtil.post('/panel/setting/regenerateApiToken');
if (msg?.success) {
apiToken.value = msg.obj || '';
message.success(t('success'));
}
} finally {
apiTokenRotating.value = false;
}
},
});
}
onMounted(loadApiToken);
function toggleTwoFactor() {
// Switch read-only — the actual flip happens after the modal succeeds.
if (!props.allSetting.twoFactorEnable) {
const newToken = RandomUtil.randomBase32String();
openTfa({
title: t('pages.settings.security.twoFactorModalSetTitle'),
token: newToken,
type: 'set',
onConfirm: (ok) => {
if (ok) {
message.success(t('pages.settings.security.twoFactorModalSetSuccess'));
props.allSetting.twoFactorToken = newToken;
}
props.allSetting.twoFactorEnable = ok;
},
});
} else {
openTfa({
title: t('pages.settings.security.twoFactorModalDeleteTitle'),
description: t('pages.settings.security.twoFactorModalRemoveStep'),
token: props.allSetting.twoFactorToken,
type: 'confirm',
onConfirm: (ok) => {
if (!ok) return;
message.success(t('pages.settings.security.twoFactorModalDeleteSuccess'));
props.allSetting.twoFactorEnable = false;
props.allSetting.twoFactorToken = '';
},
});
}
}
</script>
<template>
<a-collapse default-active-key="1">
<a-collapse-panel key="1" :header="t('pages.settings.security.admin')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.oldUsername') }}</template>
<template #control>
<a-input v-model:value="user.oldUsername" autocomplete="username" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.currentPassword') }}</template>
<template #control>
<a-input-password v-model:value="user.oldPassword" autocomplete="current-password" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.newUsername') }}</template>
<template #control>
<a-input v-model:value="user.newUsername" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.newPassword') }}</template>
<template #control>
<a-input-password v-model:value="user.newPassword" autocomplete="new-password" />
</template>
</SettingListItem>
<a-list-item>
<a-space direction="horizontal" :style="{ padding: '0 20px' }">
<a-button type="primary" :loading="updating" @click="updateUser">{{ t('confirm') }}</a-button>
</a-space>
</a-list-item>
</a-collapse-panel>
<a-collapse-panel key="2" :header="t('pages.settings.security.twoFactor')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.security.twoFactorEnable') }}</template>
<template #description>{{ t('pages.settings.security.twoFactorEnableDesc') }}</template>
<template #control>
<a-switch :checked="allSetting.twoFactorEnable" @click="toggleTwoFactor" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="3" :header="t('pages.nodes.apiToken')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.nodes.apiToken') }}</template>
<template #description>{{ t('pages.nodes.apiTokenHint') }}</template>
<template #control>
<a-input-password :value="apiToken" readonly :loading="apiTokenLoading" style="min-width: 240px" />
</template>
</SettingListItem>
<a-list-item>
<a-space direction="horizontal" :style="{ padding: '0 20px' }">
<a-button :disabled="!apiToken" @click="copyApiToken">{{ t('copy') }}</a-button>
<a-button danger :loading="apiTokenRotating" @click="regenerateApiToken">
{{ t('pages.nodes.regenerate') }}
</a-button>
</a-space>
</a-list-item>
</a-collapse-panel>
</a-collapse>
<TwoFactorModal v-model:open="tfa.open" :title="tfa.title" :description="tfa.description" :token="tfa.token"
:type="tfa.type" @confirm="onTfaConfirm" />
</template>
@@ -0,0 +1,307 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal } from 'ant-design-vue';
import {
SettingOutlined,
SafetyOutlined,
MessageOutlined,
CloudServerOutlined,
CodeOutlined,
} from '@ant-design/icons-vue';
import { HttpUtil, PromiseUtil } from '@/utils';
import { theme as themeState, antdThemeConfig } from '@/composables/useTheme.js';
import { useMediaQuery } from '@/composables/useMediaQuery.js';
import AppSidebar from '@/components/AppSidebar.vue';
import { useAllSetting } from './useAllSetting.js';
import GeneralTab from './GeneralTab.vue';
import SecurityTab from './SecurityTab.vue';
import TelegramTab from './TelegramTab.vue';
import SubscriptionGeneralTab from './SubscriptionGeneralTab.vue';
import SubscriptionFormatsTab from './SubscriptionFormatsTab.vue';
const { t } = useI18n();
const { fetched, spinning, saveDisabled, allSetting, saveAll } = useAllSetting();
const { isMobile } = useMediaQuery();
const basePath = window.__X_UI_BASE_PATH__ || '';
const requestUri = window.location.pathname;
// AD-Vue 4's <a-back-top> calls `target()` after mount to find the
// scrolled element. Inline-arrow `() => document.getElementById(...)`
// in the template threw "Cannot read properties of undefined (reading
// 'getElementById')" because of how Vue 3 evaluates the expression
// outside the script-setup scope — wrap in a regular function so
// `document` resolves to the window global at call time.
function scrollTarget() {
return document.getElementById('content-layout');
}
// `entry*` mirrors the URL the user opened the panel with so the page
// can rebuild it after a restart that may change host/port/scheme.
const entryHost = ref('');
const entryPort = ref('');
const entryIsIP = ref(false);
function isIp(h) {
if (typeof h !== 'string') return false;
// IPv4: four dot-separated octets 0-255.
const v4 = h.split('.');
if (v4.length === 4 && v4.every((p) => /^\d{1,3}$/.test(p) && Number(p) <= 255)) return true;
// IPv6: hex groups, optional single :: compression.
if (!h.includes(':') || h.includes(':::')) return false;
const parts = h.split('::');
if (parts.length > 2) return false;
const split = (s) => (s ? s.split(':').filter(Boolean) : []);
const head = split(parts[0]);
const tail = split(parts[1]);
const valid = (seg) => /^[0-9a-fA-F]{1,4}$/.test(seg);
if (![...head, ...tail].every(valid)) return false;
const groups = head.length + tail.length;
return parts.length === 2 ? groups < 8 : groups === 8;
}
onMounted(() => {
entryHost.value = window.location.hostname;
entryPort.value = window.location.port;
entryIsIP.value = isIp(entryHost.value);
});
// Rebuild the URL after a restart — host/port/scheme may have changed
// (cert toggled on, port edited, base path edited).
function rebuildUrlAfterRestart() {
const { webDomain, webPort, webBasePath, webCertFile, webKeyFile } = allSetting;
const newProtocol = (webCertFile || webKeyFile) ? 'https:' : 'http:';
let base = webBasePath ? webBasePath.replace(/^\//, '') : '';
if (base && !base.endsWith('/')) base += '/';
if (!entryIsIP.value) {
const url = new URL(window.location.href);
url.pathname = `/${base}panel/settings`;
url.protocol = newProtocol;
return url.toString();
}
let finalHost = entryHost.value;
let finalPort = entryPort.value || '';
if (webDomain && isIp(webDomain)) finalHost = webDomain;
if (webPort && Number(webPort) !== Number(entryPort.value)) finalPort = String(webPort);
const url = new URL(`${newProtocol}//${finalHost}`);
if (finalPort) url.port = finalPort;
url.pathname = `/${base}panel/settings`;
return url.toString();
}
function restartPanel() {
Modal.confirm({
title: t('pages.settings.restartPanel'),
content: t('pages.settings.restartPanelDesc'),
okText: t('pages.settings.restartPanel'),
okButtonProps: { danger: true },
cancelText: t('cancel'),
async onOk() {
spinning.value = true;
try {
const msg = await HttpUtil.post('/panel/setting/restartPanel');
if (!msg?.success) return;
await PromiseUtil.sleep(5000);
window.location.replace(rebuildUrlAfterRestart());
} finally {
spinning.value = false;
}
},
});
}
// Conf alerts mirror the legacy banner — pure derivation off allSetting.
const confAlerts = computed(() => {
const out = [];
if (window.location.protocol !== 'https:') {
out.push('Panel is served over plain HTTP — set up TLS for production.');
}
if (allSetting.webPort === 2053) {
out.push('Default port 2053 is well-known — change it to a random port.');
}
const segs = window.location.pathname.split('/').length < 4;
if (segs && allSetting.webBasePath === '/') {
out.push('Default base path "/" is well-known — change it to a random path.');
}
if (allSetting.subEnable) {
let subPath = allSetting.subPath;
if (allSetting.subURI) {
try { subPath = new URL(allSetting.subURI).pathname; } catch (_e) { }
}
if (subPath === '/sub/') {
out.push('Default subscription path "/sub/" is well-known — change it.');
}
}
if (allSetting.subJsonEnable) {
let p = allSetting.subJsonPath;
if (allSetting.subJsonURI) {
try { p = new URL(allSetting.subJsonURI).pathname; } catch (_e) { }
}
if (p === '/json/') {
out.push('Default JSON subscription path "/json/" is well-known — change it.');
}
}
return out;
});
const alertVisible = ref(true);
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout class="settings-page" :class="{ 'is-dark': themeState.isDark, 'is-ultra': themeState.isUltra }">
<AppSidebar :base-path="basePath" :request-uri="requestUri" />
<a-layout class="content-shell">
<a-layout-content id="content-layout" class="content-area">
<a-spin :spinning="spinning || !fetched" :delay="200" tip="Loading…" size="large">
<div v-if="!fetched" class="loading-spacer" />
<template v-else>
<a-alert v-if="confAlerts.length > 0 && alertVisible" type="error" show-icon closable class="conf-alert"
@close="alertVisible = false">
<template #message>Security warnings</template>
<template #description>
<b>Your panel may be exposed:</b>
<ul>
<li v-for="(msg, i) in confAlerts" :key="i">{{ msg }}</li>
</ul>
</template>
</a-alert>
<a-row :gutter="[isMobile ? 8 : 16, isMobile ? 0 : 12]">
<a-col :span="24">
<a-card hoverable>
<a-row class="header-row">
<a-col :xs="24" :sm="10" class="header-actions">
<a-space direction="horizontal">
<a-button type="primary" :disabled="saveDisabled" @click="saveAll">
{{ t('pages.settings.save') }}
</a-button>
<a-button type="primary" danger :disabled="!saveDisabled" @click="restartPanel">
{{ t('pages.settings.restartPanel') }}
</a-button>
</a-space>
</a-col>
<a-col :xs="24" :sm="14" class="header-info">
<a-back-top :target="scrollTarget" :visibility-height="200" />
<a-alert type="warning" show-icon :message="t('pages.settings.infoDesc')" />
</a-col>
</a-row>
</a-card>
</a-col>
<a-col :span="24">
<a-tabs default-active-key="1">
<a-tab-pane key="1" class="tab-pane">
<template #tab>
<SettingOutlined />
<span>{{ t('pages.settings.panelSettings') }}</span>
</template>
<GeneralTab :all-setting="allSetting" />
</a-tab-pane>
<a-tab-pane key="2" class="tab-pane">
<template #tab>
<SafetyOutlined />
<span>{{ t('pages.settings.securitySettings') }}</span>
</template>
<SecurityTab :all-setting="allSetting" />
</a-tab-pane>
<a-tab-pane key="3" class="tab-pane">
<template #tab>
<MessageOutlined />
<span>{{ t('pages.settings.TGBotSettings') }}</span>
</template>
<TelegramTab :all-setting="allSetting" />
</a-tab-pane>
<a-tab-pane key="4" class="tab-pane">
<template #tab>
<CloudServerOutlined />
<span>{{ t('pages.settings.subSettings') }}</span>
</template>
<SubscriptionGeneralTab :all-setting="allSetting" />
</a-tab-pane>
<a-tab-pane v-if="allSetting.subJsonEnable || allSetting.subClashEnable" key="5" class="tab-pane">
<template #tab>
<CodeOutlined />
<span>{{ t('pages.settings.subSettings') }} (Formats)</span>
</template>
<SubscriptionFormatsTab :all-setting="allSetting" />
</a-tab-pane>
</a-tabs>
</a-col>
</a-row>
</template>
</a-spin>
</a-layout-content>
</a-layout>
</a-layout>
</a-config-provider>
</template>
<style scoped>
.settings-page {
--bg-page: #e6e8ec;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.settings-page.is-dark {
--bg-page: #0a1222;
--bg-card: #151f31;
}
.settings-page.is-dark.is-ultra {
--bg-page: #050505;
--bg-card: #0c0e12;
}
.settings-page :deep(.ant-layout),
.settings-page :deep(.ant-layout-content) {
background: transparent;
}
.content-shell {
background: transparent;
}
.content-area {
padding: 24px;
}
.loading-spacer {
min-height: calc(100vh - 120px);
}
.conf-alert {
margin-bottom: 10px;
}
.header-row {
display: flex;
flex-wrap: wrap;
align-items: center;
}
.header-actions {
padding: 4px;
}
.header-info {
display: flex;
justify-content: flex-end;
}
.tab-pane {
padding-top: 20px;
}
</style>
@@ -0,0 +1,433 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import SettingListItem from '@/components/SettingListItem.vue';
const { t } = useI18n();
const props = defineProps({
allSetting: { type: Object, required: true },
});
// === Defaults (match legacy) ============================================
const DEFAULT_FRAGMENT = {
packets: 'tlshello',
length: '100-200',
interval: '10-20',
maxSplit: '300-400',
};
const DEFAULT_NOISES = [{ type: 'rand', packet: '10-20', delay: '10-16', applyTo: 'ip' }];
const DEFAULT_MUX = {
enabled: true,
concurrency: 8,
xudpConcurrency: 16,
xudpProxyUDP443: 'reject',
};
const DEFAULT_RULES = [
{ type: 'field', outboundTag: 'direct', domain: ['geosite:category-ir'] },
{ type: 'field', outboundTag: 'direct', ip: ['geoip:private', 'geoip:ir'] },
];
const directIPsOptions = [
{ label: 'Private IP', value: 'geoip:private' },
{ label: '🇮🇷 Iran', value: 'geoip:ir' },
{ label: '🇨🇳 China', value: 'geoip:cn' },
{ label: '🇷🇺 Russia', value: 'geoip:ru' },
{ label: '🇻🇳 Vietnam', value: 'geoip:vn' },
{ label: '🇪🇸 Spain', value: 'geoip:es' },
{ label: '🇮🇩 Indonesia', value: 'geoip:id' },
{ label: '🇺🇦 Ukraine', value: 'geoip:ua' },
{ label: '🇹🇷 Türkiye', value: 'geoip:tr' },
{ label: '🇧🇷 Brazil', value: 'geoip:br' },
];
const directDomainsOptions = [
{ label: 'Private DNS', value: 'geosite:private' },
{ label: '🇮🇷 Iran', value: 'geosite:category-ir' },
{ label: '🇨🇳 China', value: 'geosite:cn' },
{ label: '🇷🇺 Russia', value: 'geosite:category-ru' },
{ label: 'Apple', value: 'geosite:apple' },
{ label: 'Meta', value: 'geosite:meta' },
{ label: 'Google', value: 'geosite:google' },
];
// === Path helpers (json + clash share the same shape) ===================
function makePath(field) {
return computed({
get: () => props.allSetting[field],
set: (v) => {
props.allSetting[field] = String(v ?? '').replace(/[:*]/g, '');
},
});
}
function normalizePath(field) {
let p = props.allSetting[field] || '/';
if (!p.startsWith('/')) p = '/' + p;
if (!p.endsWith('/')) p += '/';
p = p.replace(/\/+/g, '/');
props.allSetting[field] = p;
}
const subJsonPath = makePath('subJsonPath');
const subClashPath = makePath('subClashPath');
// === Fragment ===========================================================
// `subJsonFragment` is a JSON-encoded object when enabled, "" when off.
function readJson(field, fallback) {
try {
const raw = props.allSetting[field];
if (!raw) return fallback;
return JSON.parse(raw);
} catch (_e) {
return fallback;
}
}
function writeJson(field, value) {
props.allSetting[field] = JSON.stringify(value);
}
const fragment = computed({
get: () => props.allSetting.subJsonFragment !== '',
set: (v) => {
props.allSetting.subJsonFragment = v ? JSON.stringify(DEFAULT_FRAGMENT) : '';
},
});
function makeFragmentField(key) {
return computed({
get: () => (fragment.value ? readJson('subJsonFragment', DEFAULT_FRAGMENT)[key] : ''),
set: (v) => {
if (v === '') return;
const f = readJson('subJsonFragment', { ...DEFAULT_FRAGMENT });
f[key] = v;
writeJson('subJsonFragment', f);
},
});
}
const fragmentPackets = makeFragmentField('packets');
const fragmentLength = makeFragmentField('length');
const fragmentInterval = makeFragmentField('interval');
const fragmentMaxSplit = makeFragmentField('maxSplit');
// === Noises =============================================================
const noises = computed({
get: () => props.allSetting.subJsonNoises !== '',
set: (v) => {
props.allSetting.subJsonNoises = v ? JSON.stringify(DEFAULT_NOISES) : '';
},
});
const noisesArray = computed({
get: () => (noises.value ? readJson('subJsonNoises', DEFAULT_NOISES) : []),
set: (value) => { if (noises.value) writeJson('subJsonNoises', value); },
});
function addNoise() {
noisesArray.value = [...noisesArray.value, { ...DEFAULT_NOISES[0] }];
}
function removeNoise(index) {
const next = [...noisesArray.value];
next.splice(index, 1);
noisesArray.value = next;
}
function updateNoiseField(index, field, value) {
const next = [...noisesArray.value];
next[index] = { ...next[index], [field]: value };
noisesArray.value = next;
}
// === Mux ================================================================
const enableMux = computed({
get: () => props.allSetting.subJsonMux !== '',
set: (v) => {
props.allSetting.subJsonMux = v ? JSON.stringify(DEFAULT_MUX) : '';
},
});
function makeMuxField(key, fallback) {
return computed({
get: () => (enableMux.value ? readJson('subJsonMux', DEFAULT_MUX)[key] : fallback),
set: (v) => {
const m = readJson('subJsonMux', { ...DEFAULT_MUX });
m[key] = v;
writeJson('subJsonMux', m);
},
});
}
const muxConcurrency = makeMuxField('concurrency', -1);
const muxXudpConcurrency = makeMuxField('xudpConcurrency', -1);
const muxXudpProxyUDP443 = makeMuxField('xudpProxyUDP443', 'reject');
// === Direct routing rules ==============================================
// `subJsonRules` is a JSON array of xray routing rules. We surface the
// IP and domain fields of the two seed rules as multi-select tags.
const enableDirect = computed({
get: () => props.allSetting.subJsonRules !== '',
set: (v) => {
props.allSetting.subJsonRules = v ? JSON.stringify(DEFAULT_RULES) : '';
},
});
function ruleArray() {
if (!enableDirect.value) return null;
const rules = readJson('subJsonRules', null);
return Array.isArray(rules) ? rules : null;
}
const directIPs = computed({
get: () => {
const rules = ruleArray();
if (!rules) return [];
const ipRule = rules.find((r) => r.ip);
return ipRule?.ip ?? [];
},
set: (value) => {
let rules = ruleArray();
if (!rules) return;
if (value.length === 0) {
rules = rules.filter((r) => !r.ip);
} else {
let idx = rules.findIndex((r) => r.ip);
if (idx === -1) idx = rules.push({ ...DEFAULT_RULES[1] }) - 1;
rules[idx].ip = [...value];
}
writeJson('subJsonRules', rules);
},
});
const directDomains = computed({
get: () => {
const rules = ruleArray();
if (!rules) return [];
const dRule = rules.find((r) => r.domain);
return dRule?.domain ?? [];
},
set: (value) => {
let rules = ruleArray();
if (!rules) return;
if (value.length === 0) {
rules = rules.filter((r) => !r.domain);
} else {
let idx = rules.findIndex((r) => r.domain);
if (idx === -1) idx = rules.push({ ...DEFAULT_RULES[0] }) - 1;
rules[idx].domain = [...value];
}
writeJson('subJsonRules', rules);
},
});
</script>
<template>
<a-collapse default-active-key="1">
<a-collapse-panel key="1" :header="t('pages.settings.panelSettings')">
<SettingListItem v-if="allSetting.subJsonEnable" paddings="small">
<template #title>JSON {{ t('pages.settings.subPath') }}</template>
<template #description>{{ t('pages.settings.subPathDesc') }}</template>
<template #control>
<a-input v-model:value="subJsonPath" type="text" placeholder="/json/" @blur="normalizePath('subJsonPath')" />
</template>
</SettingListItem>
<SettingListItem v-if="allSetting.subJsonEnable" paddings="small">
<template #title>JSON {{ t('pages.settings.subURI') }}</template>
<template #description>{{ t('pages.settings.subURIDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subJsonURI" type="text" placeholder="(http|https)://domain[:port]/path/" />
</template>
</SettingListItem>
<SettingListItem v-if="allSetting.subClashEnable" paddings="small">
<template #title>Clash {{ t('pages.settings.subPath') }}</template>
<template #description>{{ t('pages.settings.subPathDesc') }}</template>
<template #control>
<a-input v-model:value="subClashPath" type="text" placeholder="/clash/"
@blur="normalizePath('subClashPath')" />
</template>
</SettingListItem>
<SettingListItem v-if="allSetting.subClashEnable" paddings="small">
<template #title>Clash {{ t('pages.settings.subURI') }}</template>
<template #description>{{ t('pages.settings.subURIDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subClashURI" type="text"
placeholder="(http|https)://domain[:port]/path/" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="2" :header="t('pages.settings.fragment')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.fragment') }}</template>
<template #description>{{ t('pages.settings.fragmentDesc') }}</template>
<template #control>
<a-switch v-model:checked="fragment" />
</template>
</SettingListItem>
<a-list-item v-if="fragment" class="nested-block">
<a-collapse>
<a-collapse-panel :header="t('pages.settings.fragmentSett')">
<SettingListItem paddings="small">
<template #title>Packets</template>
<template #control>
<a-input v-model:value="fragmentPackets" placeholder="1-1 | 1-3 | tlshello | …" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Length</template>
<template #control>
<a-input v-model:value="fragmentLength" placeholder="100-200" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Interval</template>
<template #control>
<a-input v-model:value="fragmentInterval" placeholder="10-20" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Max split</template>
<template #control>
<a-input v-model:value="fragmentMaxSplit" placeholder="300-400" />
</template>
</SettingListItem>
</a-collapse-panel>
</a-collapse>
</a-list-item>
</a-collapse-panel>
<a-collapse-panel key="3" header="Noises">
<SettingListItem paddings="small">
<template #title>Noises</template>
<template #description>{{ t('pages.settings.noisesDesc') }}</template>
<template #control>
<a-switch v-model:checked="noises" />
</template>
</SettingListItem>
<a-list-item v-if="noises" class="nested-block">
<a-collapse>
<a-collapse-panel v-for="(noise, index) in noisesArray" :key="index" :header="`Noise №${index + 1}`">
<SettingListItem paddings="small">
<template #title>Type</template>
<template #control>
<a-select :value="noise.type" :style="{ width: '100%' }"
@change="(v) => updateNoiseField(index, 'type', v)">
<a-select-option v-for="p in ['rand', 'base64', 'str', 'hex']" :key="p" :value="p">
{{ p }}
</a-select-option>
</a-select>
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Packet</template>
<template #control>
<a-input :value="noise.packet" placeholder="5-10"
@input="(e) => updateNoiseField(index, 'packet', e.target.value)" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Delay (ms)</template>
<template #control>
<a-input :value="noise.delay" placeholder="10-20"
@input="(e) => updateNoiseField(index, 'delay', e.target.value)" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Apply to</template>
<template #control>
<a-select :value="noise.applyTo" :style="{ width: '100%' }"
@change="(v) => updateNoiseField(index, 'applyTo', v)">
<a-select-option v-for="p in ['ip', 'ipv4', 'ipv6']" :key="p" :value="p">
{{ p }}
</a-select-option>
</a-select>
</template>
</SettingListItem>
<a-space direction="horizontal" :style="{ padding: '10px 20px' }">
<a-button v-if="noisesArray.length > 1" type="primary" danger @click="removeNoise(index)">
{{ t('delete') }}
</a-button>
</a-space>
</a-collapse-panel>
</a-collapse>
<a-button type="primary" :style="{ marginTop: '10px' }" @click="addNoise">+ Noise</a-button>
</a-list-item>
</a-collapse-panel>
<a-collapse-panel key="4" :header="t('pages.settings.mux')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.mux') }}</template>
<template #description>{{ t('pages.settings.muxDesc') }}</template>
<template #control>
<a-switch v-model:checked="enableMux" />
</template>
</SettingListItem>
<a-list-item v-if="enableMux" class="nested-block">
<a-collapse>
<a-collapse-panel :header="t('pages.settings.muxSett')">
<SettingListItem paddings="small">
<template #title>Concurrency</template>
<template #control>
<a-input-number v-model:value="muxConcurrency" :min="-1" :max="1024" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>xudp concurrency</template>
<template #control>
<a-input-number v-model:value="muxXudpConcurrency" :min="-1" :max="1024" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>xudp UDP 443</template>
<template #control>
<a-select v-model:value="muxXudpProxyUDP443" :style="{ width: '100%' }">
<a-select-option v-for="p in ['reject', 'allow', 'skip']" :key="p" :value="p">
{{ p }}
</a-select-option>
</a-select>
</template>
</SettingListItem>
</a-collapse-panel>
</a-collapse>
</a-list-item>
</a-collapse-panel>
<a-collapse-panel key="5" :header="t('pages.settings.direct')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.direct') }}</template>
<template #description>{{ t('pages.settings.directDesc') }}</template>
<template #control>
<a-switch v-model:checked="enableDirect" />
</template>
</SettingListItem>
<a-list-item v-if="enableDirect" class="nested-block">
<a-collapse>
<a-collapse-panel :header="t('pages.settings.direct')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.direct') }} IPs</template>
<template #control>
<a-select v-model:value="directIPs" mode="tags" :style="{ width: '100%' }">
<a-select-option v-for="p in directIPsOptions" :key="p.value" :value="p.value" :label="p.label">
{{ p.label }}
</a-select-option>
</a-select>
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.direct') }} {{ t('domainName') }}</template>
<template #control>
<a-select v-model:value="directDomains" mode="tags" :style="{ width: '100%' }">
<a-select-option v-for="p in directDomainsOptions" :key="p.value" :value="p.value" :label="p.label">
{{ p.label }}
</a-select-option>
</a-select>
</template>
</SettingListItem>
</a-collapse-panel>
</a-collapse>
</a-list-item>
</a-collapse-panel>
</a-collapse>
</template>
<style scoped>
.nested-block {
padding: 10px 20px;
}
</style>
@@ -0,0 +1,196 @@
<script setup>
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import SettingListItem from '@/components/SettingListItem.vue';
const { t } = useI18n();
const props = defineProps({
allSetting: { type: Object, required: true },
});
// Sub path is constrained: no `:` or `*`, must start and end with `/`,
// and no double slashes. Strip on input, normalize on blur — same
// behavior as the legacy template.
const subPath = computed({
get: () => props.allSetting.subPath,
set: (v) => {
props.allSetting.subPath = String(v ?? '').replace(/[:*]/g, '');
},
});
function normalizeSubPath() {
let p = props.allSetting.subPath || '/';
if (!p.startsWith('/')) p = '/' + p;
if (!p.endsWith('/')) p += '/';
p = p.replace(/\/+/g, '/');
props.allSetting.subPath = p;
}
</script>
<template>
<a-collapse default-active-key="1">
<a-collapse-panel key="1" :header="t('pages.settings.panelSettings')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subEnable') }}</template>
<template #description>{{ t('pages.settings.subEnableDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.subEnable" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>JSON subscription</template>
<template #description>{{ t('pages.settings.subJsonEnable') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.subJsonEnable" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>Clash / Mihomo subscription</template>
<template #control>
<a-switch v-model:checked="allSetting.subClashEnable" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subListen') }}</template>
<template #description>{{ t('pages.settings.subListenDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subListen" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subDomain') }}</template>
<template #description>{{ t('pages.settings.subDomainDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subDomain" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subPort') }}</template>
<template #description>{{ t('pages.settings.subPortDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.subPort" :min="1" :max="65535" :style="{ width: '100%' }" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subPath') }}</template>
<template #description>{{ t('pages.settings.subPathDesc') }}</template>
<template #control>
<a-input v-model:value="subPath" type="text" placeholder="/sub/" @blur="normalizeSubPath" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subURI') }}</template>
<template #description>{{ t('pages.settings.subURIDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subURI" type="text" placeholder="(http|https)://domain[:port]/path/" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="2" :header="t('pages.settings.information')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subEncrypt') }}</template>
<template #description>{{ t('pages.settings.subEncryptDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.subEncrypt" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subShowInfo') }}</template>
<template #description>{{ t('pages.settings.subShowInfoDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.subShowInfo" />
</template>
</SettingListItem>
<a-divider>{{ t('pages.settings.subTitle') }}</a-divider>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subTitle') }}</template>
<template #description>{{ t('pages.settings.subTitleDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subTitle" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subSupportUrl') }}</template>
<template #description>{{ t('pages.settings.subSupportUrlDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subSupportUrl" type="text" placeholder="https://example.com" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subProfileUrl') }}</template>
<template #description>{{ t('pages.settings.subProfileUrlDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subProfileUrl" type="text" placeholder="https://example.com" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subAnnounce') }}</template>
<template #description>{{ t('pages.settings.subAnnounceDesc') }}</template>
<template #control>
<a-textarea v-model:value="allSetting.subAnnounce" />
</template>
</SettingListItem>
<a-divider>Happ</a-divider>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subEnableRouting') }}</template>
<template #description>{{ t('pages.settings.subEnableRoutingDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.subEnableRouting" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subRoutingRules') }}</template>
<template #description>{{ t('pages.settings.subRoutingRulesDesc') }}</template>
<template #control>
<a-textarea v-model:value="allSetting.subRoutingRules" placeholder="happ://routing/add/..." />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="3" :header="t('pages.settings.certs')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subCertPath') }}</template>
<template #description>{{ t('pages.settings.subCertPathDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subCertFile" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subKeyPath') }}</template>
<template #description>{{ t('pages.settings.subKeyPathDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.subKeyFile" type="text" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="4" :header="t('pages.settings.intervals')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.subUpdates') }}</template>
<template #description>{{ t('pages.settings.subUpdatesDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.subUpdates" :min="1" :style="{ width: '100%' }" />
</template>
</SettingListItem>
</a-collapse-panel>
</a-collapse>
</template>
+106
View File
@@ -0,0 +1,106 @@
<script setup>
import { useI18n } from 'vue-i18n';
import { LanguageManager } from '@/utils';
import SettingListItem from '@/components/SettingListItem.vue';
const { t } = useI18n();
defineProps({
allSetting: { type: Object, required: true },
});
</script>
<template>
<a-collapse default-active-key="1">
<a-collapse-panel key="1" :header="t('pages.settings.panelSettings')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramBotEnable') }}</template>
<template #description>{{ t('pages.settings.telegramBotEnableDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.tgBotEnable" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramToken') }}</template>
<template #description>{{ t('pages.settings.telegramTokenDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.tgBotToken" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramChatId') }}</template>
<template #description>{{ t('pages.settings.telegramChatIdDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.tgBotChatId" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramBotLanguage') }}</template>
<template #control>
<a-select v-model:value="allSetting.tgLang" :style="{ width: '100%' }">
<a-select-option v-for="l in LanguageManager.supportedLanguages" :key="l.value" :value="l.value"
:label="l.value">
<span role="img" :aria-label="l.name">{{ l.icon }}</span>
&nbsp;&nbsp;<span>{{ l.name }}</span>
</a-select-option>
</a-select>
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="2" :header="t('pages.settings.notifications')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramNotifyTime') }}</template>
<template #description>{{ t('pages.settings.telegramNotifyTimeDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.tgRunTime" type="text" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.tgNotifyBackup') }}</template>
<template #description>{{ t('pages.settings.tgNotifyBackupDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.tgBotBackup" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.tgNotifyLogin') }}</template>
<template #description>{{ t('pages.settings.tgNotifyLoginDesc') }}</template>
<template #control>
<a-switch v-model:checked="allSetting.tgBotLoginNotify" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.tgNotifyCpu') }}</template>
<template #description>{{ t('pages.settings.tgNotifyCpuDesc') }}</template>
<template #control>
<a-input-number v-model:value="allSetting.tgCpu" :min="0" :max="100" :style="{ width: '100%' }" />
</template>
</SettingListItem>
</a-collapse-panel>
<a-collapse-panel key="3" :header="t('pages.settings.proxyAndServer')">
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramProxy') }}</template>
<template #description>{{ t('pages.settings.telegramProxyDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.tgBotProxy" type="text" placeholder="socks5://user:pass@host:port" />
</template>
</SettingListItem>
<SettingListItem paddings="small">
<template #title>{{ t('pages.settings.telegramAPIServer') }}</template>
<template #description>{{ t('pages.settings.telegramAPIServerDesc') }}</template>
<template #control>
<a-input v-model:value="allSetting.tgBotAPIServer" type="text" placeholder="https://api.example.com" />
</template>
</SettingListItem>
</a-collapse-panel>
</a-collapse>
</template>
@@ -0,0 +1,181 @@
<script setup>
import { nextTick, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { message } from 'ant-design-vue';
import * as OTPAuth from 'otpauth';
import QRious from 'qrious';
import { ClipboardManager } from '@/utils';
const { t } = useI18n();
// Two flavors of this modal:
// • type='set' shows a QR code + manual key + a 6-digit verifier
// (used when enabling 2FA the first time);
// • type='confirm' shows just the 6-digit verifier (used when
// toggling 2FA off and when changing the admin user/password).
//
// Either way the parent supplies a `confirm(success: boolean)`
// callback — we run it with `true` only if the entered code matches
// the live TOTP value, otherwise `false`.
const props = defineProps({
open: { type: Boolean, default: false },
title: { type: String, default: '' },
description: { type: String, default: '' },
token: { type: String, default: '' },
type: { type: String, default: 'set', validator: (v) => ['set', 'confirm'].includes(v) },
});
const emit = defineEmits(['update:open', 'confirm']);
const enteredCode = ref('');
const qrCanvas = ref(null);
let totp = null;
// Byte-mode capacities (level L) for QR versions 1..40 — used to pick
// the matrix width up front so the canvas size is an exact multiple of
// pixelSize. Without this, QRious renders at floor(size/matrix) and
// centers, leaving a white margin around the QR.
const QR_L_BYTE_CAPACITY = [
17, 32, 53, 78, 106, 134, 154, 192, 230, 271,
321, 367, 425, 458, 520, 586, 644, 718, 792, 858,
929, 1003, 1091, 1171, 1273, 1367, 1465, 1528, 1628, 1732,
1840, 1952, 2068, 2188, 2303, 2431, 2563, 2699, 2809, 2953,
];
function pickQrMatrixWidth(value) {
const byteLen = new TextEncoder().encode(value).length;
for (let i = 0; i < QR_L_BYTE_CAPACITY.length; i++) {
if (byteLen <= QR_L_BYTE_CAPACITY[i]) return 17 + 4 * (i + 1);
}
return 17 + 4 * 40;
}
function buildTotp() {
totp = new OTPAuth.TOTP({
issuer: '3x-ui',
label: 'Administrator',
algorithm: 'SHA1',
digits: 6,
period: 30,
secret: props.token,
});
}
async function paintQr() {
await nextTick();
if (!qrCanvas.value || !totp) return;
const value = totp.toString();
const matrixWidth = pickQrMatrixWidth(value);
const pixelSize = Math.max(1, Math.floor(200 / matrixWidth));
const exactSize = matrixWidth * pixelSize;
new QRious({
element: qrCanvas.value,
size: exactSize,
value,
background: 'white',
backgroundAlpha: 1,
foreground: 'black',
padding: 0,
level: 'L',
});
}
watch(() => props.open, (next) => {
if (!next) return;
enteredCode.value = '';
if (props.token) {
buildTotp();
if (props.type === 'set') paintQr();
}
});
function close(success) {
emit('confirm', success);
emit('update:open', false);
enteredCode.value = '';
}
function onOk() {
if (!totp) return;
if (totp.generate() === enteredCode.value) {
close(true);
} else {
message.error(t('pages.settings.security.twoFactorModalError'));
}
}
function onCancel() {
close(false);
}
async function copyToken() {
const ok = await ClipboardManager.copyText(props.token);
if (ok) message.success(t('copied'));
}
</script>
<template>
<a-modal :open="open" :title="title" :closable="true" @cancel="onCancel">
<template v-if="type === 'set'">
<p>{{ t('pages.settings.security.twoFactorModalSteps') }}</p>
<a-divider />
<p>{{ t('pages.settings.security.twoFactorModalFirstStep') }}</p>
<div class="qr-wrap">
<div class="qr-bg">
<canvas ref="qrCanvas" class="qr-cv" @click="copyToken" />
</div>
<span class="qr-token">{{ token }}</span>
</div>
<a-divider />
<p>{{ t('pages.settings.security.twoFactorModalSecondStep') }}</p>
<a-input v-model:value="enteredCode" :style="{ width: '100%' }" />
</template>
<template v-else>
<p>{{ description }}</p>
<a-input v-model:value="enteredCode" :style="{ width: '100%' }" />
</template>
<template #footer>
<a-button @click="onCancel">{{ t('cancel') }}</a-button>
<a-button type="primary" :disabled="enteredCode.length < 6" @click="onOk">{{ t('confirm') }}</a-button>
</template>
</a-modal>
</template>
<style scoped>
.qr-wrap {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
.qr-bg {
width: 180px;
height: 180px;
background: #fff;
padding: 4px;
border-radius: 6px;
}
.qr-cv {
cursor: pointer;
width: 100% !important;
height: 100% !important;
/* Drawing buffer is matrix-snapped (smaller than display size); scale
* up crisply so the QR fills the box without blurring. */
image-rendering: pixelated;
image-rendering: crisp-edges;
}
.qr-token {
font-size: 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
word-break: break-all;
text-align: center;
}
</style>
@@ -0,0 +1,80 @@
// Centralizes the AllSetting fetch/save lifecycle the legacy panel
// scattered across data() + methods + a busy-loop dirty checker.
//
// The dirty flag is recomputed once per second (matching the legacy
// `while (true) sleep(1000)` poll) — we don't deep-watch because the
// settings tree has many nested fields and a poll is cheap enough.
import { onMounted, onUnmounted, reactive, ref } from 'vue';
import { HttpUtil } from '@/utils';
import { AllSetting } from '@/models/setting.js';
const DIRTY_POLL_MS = 1000;
export function useAllSetting() {
const fetched = ref(false);
const spinning = ref(false);
const saveDisabled = ref(true);
// Two reactive snapshots: the last server-side state and the one the
// user is editing. `equals` compares enumerable props field-by-field.
const oldAllSetting = reactive(new AllSetting());
const allSetting = reactive(new AllSetting());
function applyServerState(obj) {
const fresh = new AllSetting(obj);
Object.assign(oldAllSetting, fresh);
Object.assign(allSetting, fresh);
saveDisabled.value = true;
}
async function fetchAll() {
const msg = await HttpUtil.post('/panel/setting/all');
if (msg?.success) {
fetched.value = true;
applyServerState(msg.obj);
}
}
async function saveAll() {
spinning.value = true;
try {
const msg = await HttpUtil.post('/panel/setting/update', allSetting);
if (msg?.success) await fetchAll();
} finally {
spinning.value = false;
}
}
let timer = null;
function startDirtyPoll() {
if (timer != null) return;
timer = setInterval(() => {
// ObjectUtil.equals walks own enumerable props; reactive proxies
// expose them transparently so this works without cloning.
saveDisabled.value = oldAllSetting.equals(allSetting);
}, DIRTY_POLL_MS);
}
function stopDirtyPoll() {
if (timer != null) {
clearInterval(timer);
timer = null;
}
}
onMounted(() => {
fetchAll();
startDirtyPoll();
});
onUnmounted(stopDirtyPoll);
return {
fetched,
spinning,
saveDisabled,
oldAllSetting,
allSetting,
fetchAll,
saveAll,
};
}
+469
View File
@@ -0,0 +1,469 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
SettingOutlined,
AndroidOutlined,
AppleOutlined,
DownOutlined,
CopyOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import QRious from 'qrious';
import { ClipboardManager, IntlUtil, LanguageManager } from '@/utils';
import {
theme as themeState,
antdThemeConfig,
} from '@/composables/useTheme.js';
import ThemeSwitchLogin from '@/components/ThemeSwitchLogin.vue';
const { t } = useI18n();
// Read the view-model Go injects via window.__SUB_PAGE_DATA__. Falls
// back to safe defaults so the page still renders if the global is
// missing (e.g. during local dev without the backend).
const subData = window.__SUB_PAGE_DATA__ || {};
const sId = subData.sId || '';
const enabled = !!subData.enabled;
const download = subData.download || '0';
const upload = subData.upload || '0';
const total = subData.total || '∞';
const used = subData.used || '0';
const remained = subData.remained || '';
const totalByte = Number(subData.totalByte || 0);
const expireMs = Number(subData.expire || 0) * 1000;
const lastOnlineMs = Number(subData.lastOnline || 0);
const subUrl = subData.subUrl || '';
const subJsonUrl = subData.subJsonUrl || '';
const subClashUrl = subData.subClashUrl || '';
const links = Array.isArray(subData.links) ? subData.links : [];
// Panel's "Calendar Type" setting; controls whether expiry / lastOnline
// render in Gregorian or Jalali on this standalone subscription page.
const datepicker = subData.datepicker || 'gregorian';
// Derived state ===============================================
const isUnlimited = computed(() => totalByte <= 0 && expireMs === 0);
const isActive = computed(() => {
if (!enabled) return false;
if (totalByte > 0) {
const used = Number(subData.usedByte || 0)
|| (Number(subData.downloadByte || 0) + Number(subData.uploadByte || 0));
if (used >= totalByte) return false;
}
if (expireMs > 0 && Date.now() >= expireMs) return false;
return true;
});
// Mobile-aware layout — shows app dropdowns full-width below 576px
const isMobile = ref(false);
function updateMobile() { isMobile.value = window.innerWidth < 576; }
onMounted(() => {
updateMobile();
window.addEventListener('resize', updateMobile);
});
// Language switcher mirrors the legacy panel: setting the language
// triggers a full-page reload which re-renders with the new locale.
const lang = ref(LanguageManager.getLanguage());
function onLangChange(next) {
LanguageManager.setLanguage(next);
}
// QR code rendering ===========================================
// Each ref points at a canvas element we paint after mount; QRious
// sizes itself from the element's `size` attribute.
const subQr = ref(null);
const subJsonQr = ref(null);
const subClashQr = ref(null);
function paintQr(canvas, value) {
if (!canvas || !value) return;
new QRious({
element: canvas,
size: 220,
value,
background: 'white',
backgroundAlpha: 1,
foreground: 'black',
padding: 4,
level: 'M',
});
}
onMounted(() => {
paintQr(subQr.value, subUrl);
paintQr(subJsonQr.value, subJsonUrl);
paintQr(subClashQr.value, subClashUrl);
});
// Actions =====================================================
async function copy(value) {
if (!value) return;
const ok = await ClipboardManager.copyText(value);
if (ok) message.success(t('copied'));
}
function open(url) {
if (!url) return;
window.open(url, '_blank');
}
// Pretty label per share link — pulls protocol + remark out of the
// URL fragment (most clients put the remark after the # sign).
function linkName(link, idx) {
if (!link) return `Link ${idx + 1}`;
const hashIdx = link.indexOf('#');
if (hashIdx >= 0 && hashIdx + 1 < link.length) {
try {
return decodeURIComponent(link.slice(hashIdx + 1));
} catch (_e) {
return link.slice(hashIdx + 1);
}
}
const proto = link.split('://')[0];
return `${proto.toUpperCase()} ${idx + 1}`;
}
// iOS deep links — taken verbatim from the legacy subpage. Each
// client expects the sub URL in a slightly different param name.
const shadowrocketUrl = computed(() => `sub://${btoa(subUrl)}`);
const v2boxUrl = computed(() => `v2box://install-sub?url=${encodeURIComponent(subUrl)}&name=${encodeURIComponent(sId)}`);
const streisandUrl = computed(() => `streisand://import/${encodeURIComponent(subUrl)}`);
const v2raytunUrl = computed(() => subUrl);
const npvtunUrl = computed(() => subUrl);
const happUrl = computed(() => `happ://add/${subUrl}`);
// Theme classes for the page wrapper.
const themeClass = computed(() => ({
'is-dark': themeState.isDark,
'is-ultra': themeState.isUltra,
}));
</script>
<template>
<a-config-provider :theme="antdThemeConfig">
<a-layout class="subscription-page" :class="themeClass">
<a-layout-content class="content">
<a-row type="flex" justify="center">
<a-col :xs="24" :sm="22" :md="18" :lg="14" :xl="12">
<a-card hoverable class="subscription-card">
<template #title>
<a-space>
<span>{{ t('subscription.title') }}</span>
<a-tag>{{ sId }}</a-tag>
</a-space>
</template>
<template #extra>
<a-popover :title="t('menu.settings')" placement="bottomRight" trigger="click">
<template #content>
<a-space direction="vertical" :size="10" class="settings-popover">
<ThemeSwitchLogin />
<span>{{ t('pages.settings.language') }}</span>
<a-select v-model:value="lang" class="lang-select" @change="onLangChange">
<a-select-option v-for="l in LanguageManager.supportedLanguages" :key="l.value"
:value="l.value">
<span :aria-label="l.name">{{ l.icon }}</span>
&nbsp;&nbsp;<span>{{ l.name }}</span>
</a-select-option>
</a-select>
</a-space>
</template>
<a-button shape="circle">
<template #icon>
<SettingOutlined />
</template>
</a-button>
</a-popover>
</template>
<!-- ============== QR codes ============== -->
<a-row :gutter="[8, 8]" justify="center" class="qr-row">
<a-col :xs="24" :sm="subJsonUrl || subClashUrl ? 12 : 24" class="qr-col">
<div class="qr-box">
<a-tag color="purple" class="qr-tag">{{ t('pages.settings.subSettings') }}</a-tag>
<canvas ref="subQr" class="qr-canvas" :title="t('copy')" @click="copy(subUrl)" />
</div>
</a-col>
<a-col v-if="subJsonUrl" :xs="24" :sm="12" class="qr-col">
<div class="qr-box">
<a-tag color="purple" class="qr-tag">
{{ t('pages.settings.subSettings') }} JSON
</a-tag>
<canvas ref="subJsonQr" class="qr-canvas" :title="t('copy')" @click="copy(subJsonUrl)" />
</div>
</a-col>
<a-col v-if="subClashUrl" :xs="24" :sm="12" class="qr-col">
<div class="qr-box">
<a-tag color="purple" class="qr-tag">Clash / Mihomo</a-tag>
<canvas ref="subClashQr" class="qr-canvas" :title="t('copy')" @click="copy(subClashUrl)" />
</div>
</a-col>
</a-row>
<!-- ============== Subscription details ============== -->
<a-descriptions bordered :column="1" size="small" class="info-table">
<a-descriptions-item :label="t('subscription.subId')">{{ sId }}</a-descriptions-item>
<a-descriptions-item :label="t('subscription.status')">
<a-tag v-if="!enabled" color="red">{{ t('subscription.inactive') }}</a-tag>
<a-tag v-else-if="isUnlimited" color="purple">{{ t('subscription.unlimited') }}</a-tag>
<a-tag v-else :color="isActive ? 'green' : 'red'">
{{ isActive ? t('subscription.active') : t('subscription.inactive') }}
</a-tag>
</a-descriptions-item>
<a-descriptions-item :label="t('subscription.downloaded')">{{ download }}</a-descriptions-item>
<a-descriptions-item :label="t('subscription.uploaded')">{{ upload }}</a-descriptions-item>
<a-descriptions-item :label="t('usage')">{{ used }}</a-descriptions-item>
<a-descriptions-item :label="t('subscription.totalQuota')">{{ total }}</a-descriptions-item>
<a-descriptions-item v-if="totalByte > 0" :label="t('remained')">
{{ remained }}
</a-descriptions-item>
<a-descriptions-item :label="t('lastOnline')">
<template v-if="lastOnlineMs > 0">{{ IntlUtil.formatDate(lastOnlineMs, datepicker) }}</template>
<template v-else>-</template>
</a-descriptions-item>
<a-descriptions-item :label="t('subscription.expiry')">
<template v-if="expireMs === 0">{{ t('subscription.noExpiry') }}</template>
<template v-else>{{ IntlUtil.formatDate(expireMs, datepicker) }}</template>
</a-descriptions-item>
</a-descriptions>
<!-- ============== Individual links ============== -->
<div v-if="links.length" class="links-section">
<div v-for="(link, idx) in links" :key="link" class="link-row" @click="copy(link)">
<a-tag color="purple" class="link-tag">{{ linkName(link, idx) }}</a-tag>
<div class="link-box">
<CopyOutlined class="link-copy-icon" />
{{ link }}
</div>
</div>
</div>
<!-- ============== App dropdowns ============== -->
<a-row :gutter="[8, 8]" justify="center" class="apps-row">
<a-col :xs="24" :sm="12" class="app-col">
<a-dropdown :trigger="['click']">
<a-button :block="isMobile" size="large" type="primary">
<AndroidOutlined /> Android
<DownOutlined />
</a-button>
<template #overlay>
<a-menu>
<a-menu-item key="android-v2box"
@click="open(`v2box://install-sub?url=${encodeURIComponent(subUrl)}&name=${encodeURIComponent(sId)}`)">V2Box</a-menu-item>
<a-menu-item key="android-v2rayng"
@click="open(`v2rayng://install-config?url=${encodeURIComponent(subUrl)}`)">V2RayNG</a-menu-item>
<a-menu-item key="android-singbox" @click="copy(subUrl)">Sing-box</a-menu-item>
<a-menu-item key="android-v2raytun" @click="copy(subUrl)">V2RayTun</a-menu-item>
<a-menu-item key="android-npvtunnel" @click="copy(subUrl)">NPV Tunnel</a-menu-item>
<a-menu-item key="android-happ" @click="open(`happ://add/${subUrl}`)">Happ</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</a-col>
<a-col :xs="24" :sm="12" class="app-col">
<a-dropdown :trigger="['click']">
<a-button :block="isMobile" size="large" type="primary">
<AppleOutlined /> iOS
<DownOutlined />
</a-button>
<template #overlay>
<a-menu>
<a-menu-item key="ios-shadowrocket" @click="open(shadowrocketUrl)">Shadowrocket</a-menu-item>
<a-menu-item key="ios-v2box" @click="open(v2boxUrl)">V2Box</a-menu-item>
<a-menu-item key="ios-streisand" @click="open(streisandUrl)">Streisand</a-menu-item>
<a-menu-item key="ios-v2raytun" @click="copy(v2raytunUrl)">V2RayTun</a-menu-item>
<a-menu-item key="ios-npvtunnel" @click="copy(npvtunUrl)">NPV Tunnel</a-menu-item>
<a-menu-item key="ios-happ" @click="open(happUrl)">Happ</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</a-col>
</a-row>
</a-card>
</a-col>
</a-row>
</a-layout-content>
</a-layout>
</a-config-provider>
</template>
<style scoped>
.subscription-page {
--bg-page: #e6e8ec;
--bg-card: #ffffff;
min-height: 100vh;
background: var(--bg-page);
}
.subscription-page.is-dark {
--bg-page: #0a1222;
--bg-card: #151f31;
}
.subscription-page.is-dark.is-ultra {
--bg-page: #050505;
--bg-card: #0c0e12;
}
.subscription-page :deep(.ant-layout),
.subscription-page :deep(.ant-layout-content) {
background: transparent;
}
.content {
padding: 24px 12px;
}
.subscription-card {
margin-top: 8px;
}
/* QR section */
.qr-row {
margin-bottom: 12px;
}
.qr-col {
display: flex;
justify-content: center;
}
.qr-box {
display: inline-flex;
flex-direction: column;
align-items: center;
gap: 4px;
width: 220px;
}
.qr-tag {
width: 100%;
text-align: center;
margin: 0;
}
.qr-canvas {
cursor: pointer;
background: #fff;
border-radius: 4px;
}
/* Description list spacing + visible borders. AD-Vue's default
* descriptions border is rgba(5,5,5,0.06) which disappears against
* the white card in light theme. AD-Vue puts the horizontal divider
* on <tr> with border-collapse:collapse — browsers treat <tr>
* borders inconsistently in collapse mode, so paint the divider on
* each cell's bottom edge instead. */
.info-table {
margin-top: 12px;
}
.info-table :deep(.ant-descriptions-view),
.info-table :deep(.ant-descriptions-view) table,
.info-table :deep(.ant-descriptions-view) th,
.info-table :deep(.ant-descriptions-view) td {
border-color: rgba(0, 0, 0, 0.18) !important;
}
.info-table :deep(tbody > tr > th),
.info-table :deep(tbody > tr > td) {
border-bottom: 1px solid rgba(0, 0, 0, 0.18) !important;
}
.info-table :deep(tbody > tr:last-child > th),
.info-table :deep(tbody > tr:last-child > td) {
border-bottom: none !important;
}
.is-dark .info-table :deep(.ant-descriptions-view),
.is-dark .info-table :deep(.ant-descriptions-view) table,
.is-dark .info-table :deep(.ant-descriptions-view) th,
.is-dark .info-table :deep(.ant-descriptions-view) td {
border-color: rgba(255, 255, 255, 0.18) !important;
}
.is-dark .info-table :deep(tbody > tr > th),
.is-dark .info-table :deep(tbody > tr > td) {
border-bottom: 1px solid rgba(255, 255, 255, 0.18) !important;
}
.is-dark .info-table :deep(tbody > tr:last-child > th),
.is-dark .info-table :deep(tbody > tr:last-child > td) {
border-bottom: none !important;
}
/* Share links */
.links-section {
margin-top: 16px;
}
.link-row {
position: relative;
margin-bottom: 16px;
text-align: center;
}
.link-tag {
margin-bottom: -10px;
position: relative;
z-index: 2;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
.link-box {
cursor: pointer;
border-radius: 12px;
padding: 22px 18px 14px;
margin-top: -10px;
word-break: break-all;
font-size: 13px;
line-height: 1.5;
text-align: left;
font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
transition: background 120ms ease, border-color 120ms ease;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.08);
background: rgba(0, 0, 0, 0.03);
border: 1px solid rgba(0, 0, 0, 0.08);
}
.link-box:hover {
background: rgba(0, 0, 0, 0.05);
border-color: rgba(0, 0, 0, 0.14);
}
.link-copy-icon {
margin-right: 6px;
opacity: 0.6;
}
.is-dark .link-box {
background: rgba(0, 0, 0, 0.2);
border-color: rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.85);
}
.is-dark .link-box:hover {
background: rgba(0, 0, 0, 0.3);
border-color: rgba(255, 255, 255, 0.2);
}
/* App dropdown row */
.apps-row {
margin-top: 24px;
}
.app-col {
text-align: center;
}
.settings-popover {
min-width: 220px;
}
.lang-select {
width: 100%;
}
</style>
@@ -0,0 +1,123 @@
<script setup>
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
// Balancer add/edit modal — mirrors xray_balancer_modal.html.
// Tag must be unique across other balancers; selector is a tag-mode
// list constrained to existing outbound tags (but lets users type
// new ones for forward-references).
const props = defineProps({
open: { type: Boolean, default: false },
balancer: { type: Object, default: null },
outboundTags: { type: Array, default: () => [] },
// All other balancer tags (excludes the one currently being edited)
// — used for the duplicate-tag check.
otherTags: { type: Array, default: () => [] },
});
const emit = defineEmits(['update:open', 'confirm']);
const STRATEGIES = [
{ value: 'random', label: 'Random' },
{ value: 'roundRobin', label: 'Round robin' },
{ value: 'leastLoad', label: 'Least load' },
{ value: 'leastPing', label: 'Least ping' },
];
const form = reactive({
tag: '',
strategy: 'random',
selector: [],
fallbackTag: '',
});
const isEdit = ref(false);
watch(() => props.open, (next) => {
if (!next) return;
if (props.balancer) {
isEdit.value = true;
form.tag = props.balancer.tag || '';
form.strategy = props.balancer.strategy || 'random';
form.selector = [...(props.balancer.selector || [])];
form.fallbackTag = props.balancer.fallbackTag || '';
} else {
isEdit.value = false;
form.tag = '';
form.strategy = 'random';
form.selector = [];
form.fallbackTag = '';
}
});
const tagEmpty = computed(() => !form.tag?.trim());
const duplicateTag = computed(
() => !!form.tag && props.otherTags.includes(form.tag.trim()),
);
const emptySelector = computed(() => form.selector.length === 0);
const isValid = computed(
() => !tagEmpty.value && !duplicateTag.value && !emptySelector.value,
);
const tagValidateStatus = computed(() => {
if (tagEmpty.value) return 'error';
if (duplicateTag.value) return 'warning';
return 'success';
});
const tagHelp = computed(() => {
if (tagEmpty.value) return 'Tag is required';
if (duplicateTag.value) return 'Tag already used by another balancer';
return '';
});
const selectorValidateStatus = computed(() => (emptySelector.value ? 'error' : 'success'));
const selectorHelp = computed(() => (emptySelector.value ? 'Pick at least one outbound' : ''));
function close() { emit('update:open', false); }
function onOk() {
if (!isValid.value) return;
emit('confirm', { ...form });
}
const title = computed(() =>
isEdit.value
? `${t('edit')} ${t('pages.xray.Balancers')}`
: `+ ${t('pages.xray.Balancers')}`,
);
const okText = computed(() =>
isEdit.value ? t('pages.client.submitEdit') : t('create'),
);
</script>
<template>
<a-modal :open="open" :title="title" :ok-text="okText" :cancel-text="t('close')"
:ok-button-props="{ disabled: !isValid }" :mask-closable="false" @ok="onOk" @cancel="close">
<a-form :colon="false" :label-col="{ md: { span: 8 } }" :wrapper-col="{ md: { span: 14 } }">
<a-form-item label="Tag" :validate-status="tagValidateStatus" :help="tagHelp" has-feedback>
<a-input v-model:value="form.tag" placeholder="unique balancer tag" />
</a-form-item>
<a-form-item label="Strategy">
<a-select v-model:value="form.strategy">
<a-select-option v-for="s in STRATEGIES" :key="s.value" :value="s.value">{{ s.label }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Selector" :validate-status="selectorValidateStatus" :help="selectorHelp" has-feedback>
<a-select v-model:value="form.selector" mode="tags" :token-separators="[',']">
<a-select-option v-for="tag in outboundTags" :key="tag" :value="tag">{{ tag }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="Fallback">
<a-select v-model:value="form.fallbackTag" allow-clear>
<a-select-option v-for="tag in ['', ...outboundTags]" :key="tag || '__empty'" :value="tag">
{{ tag || `(${t('none')})` }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</a-modal>
</template>
+216
View File
@@ -0,0 +1,216 @@
<script setup>
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import {
PlusOutlined,
MoreOutlined,
EditOutlined,
DeleteOutlined,
} from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
import BalancerFormModal from './BalancerFormModal.vue';
const { t } = useI18n();
// Balancers tab — list + add/edit/delete over
// templateSettings.routing.balancers. The legacy panel kept the wire
// shape's `strategy: { type: 'random' }` nesting only when non-default;
// we follow the same convention on submit.
const props = defineProps({
templateSettings: { type: Object, default: null },
clientReverseTags: { type: Array, default: () => [] },
});
const STRATEGY_LABELS = {
random: 'Random',
roundRobin: 'Round robin',
leastLoad: 'Least load',
leastPing: 'Least ping',
};
const rows = computed(() => {
const list = props.templateSettings?.routing?.balancers || [];
return list.map((b, idx) => ({
key: idx,
tag: b.tag || '',
strategy: b.strategy?.type || 'random',
selector: b.selector || [],
fallbackTag: b.fallbackTag || '',
}));
});
const outboundTags = computed(() => {
const tags = new Set();
for (const o of props.templateSettings?.outbounds || []) {
if (o.tag) tags.add(o.tag);
}
for (const t of props.clientReverseTags || []) {
if (t) tags.add(t);
}
return [...tags];
});
// === Modal state ====================================================
const modalOpen = ref(false);
const editingBalancer = ref(null);
const editingIndex = ref(null);
const otherTags = ref([]);
function tagPool(excludeIdx) {
return rows.value.filter((b) => b.key !== excludeIdx).map((b) => b.tag).filter(Boolean);
}
function openAdd() {
editingBalancer.value = null;
editingIndex.value = null;
otherTags.value = rows.value.map((b) => b.tag).filter(Boolean);
modalOpen.value = true;
}
function openEdit(idx) {
editingBalancer.value = rows.value[idx];
editingIndex.value = idx;
otherTags.value = tagPool(idx);
modalOpen.value = true;
}
function ensureBalancersArray() {
if (!props.templateSettings.routing) return null;
if (!Array.isArray(props.templateSettings.routing.balancers)) {
props.templateSettings.routing.balancers = [];
}
return props.templateSettings.routing.balancers;
}
function buildWireBalancer(form) {
const out = {
tag: form.tag,
selector: [...form.selector],
fallbackTag: form.fallbackTag,
};
if (form.strategy && form.strategy !== 'random') {
out.strategy = { type: form.strategy };
}
return out;
}
function onConfirm(form) {
const arr = ensureBalancersArray();
if (!arr) return;
const wire = buildWireBalancer(form);
if (editingIndex.value == null) {
arr.push(wire);
} else {
const oldTag = arr[editingIndex.value]?.tag;
arr[editingIndex.value] = wire;
// Preserve the legacy behaviour: when a balancer's tag is renamed,
// chase the rename across routing rules so existing references
// don't dangle.
if (oldTag && oldTag !== wire.tag) {
const rules = props.templateSettings.routing.rules || [];
for (const rule of rules) {
if (rule?.balancerTag === oldTag) rule.balancerTag = wire.tag;
}
}
}
modalOpen.value = false;
}
function confirmDelete(idx) {
Modal.confirm({
title: `${t('delete')} ${t('pages.xray.Balancers')} #${idx + 1}?`,
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
// Wrap in a block so we discard splice's return value — AD-Vue
// 4 leaves the modal open if onOk returns a truthy non-thenable
// (it expects a Promise to await), and splice() returns the array
// of removed items.
onOk: () => { props.templateSettings.routing.balancers.splice(idx, 1); },
});
}
const columns = computed(() => [
{ title: '#', key: 'action', align: 'center', width: 80 },
{ title: 'Tag', dataIndex: 'tag', key: 'tag', align: 'center', width: 160 },
{ title: 'Strategy', key: 'strategy', align: 'center', width: 140 },
{ title: 'Selector', key: 'selector', align: 'center' },
{ title: 'Fallback', dataIndex: 'fallbackTag', key: 'fallbackTag', align: 'center', width: 160 },
]);
</script>
<template>
<a-space direction="vertical" size="middle" :style="{ width: '100%' }">
<a-empty v-if="rows.length === 0" :description="t('emptyBalancersDesc')">
<a-button type="primary" @click="openAdd">
<template #icon>
<PlusOutlined />
</template>
{{ t('pages.xray.Balancers') }}
</a-button>
</a-empty>
<template v-else>
<a-button type="primary" @click="openAdd">
<template #icon>
<PlusOutlined />
</template>
{{ t('pages.xray.Balancers') }}
</a-button>
<a-table :columns="columns" :data-source="rows" :row-key="(r) => r.key" :pagination="false" size="small" bordered>
<template #bodyCell="{ column, record, index }">
<template v-if="column.key === 'action'">
<span class="row-index">{{ index + 1 }}</span>
<a-dropdown :trigger="['click']">
<a-button shape="circle" size="small" class="action-btn">
<MoreOutlined />
</a-button>
<template #overlay>
<a-menu>
<a-menu-item @click="openEdit(index)">
<EditOutlined /> {{ t('edit') }}
</a-menu-item>
<a-menu-item class="danger" @click="confirmDelete(index)">
<DeleteOutlined /> {{ t('delete') }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
<template v-else-if="column.key === 'strategy'">
<a-tag :color="record.strategy === 'random' ? 'purple' : 'green'">
{{ STRATEGY_LABELS[record.strategy] || record.strategy }}
</a-tag>
</template>
<template v-else-if="column.key === 'selector'">
<a-tag v-for="sel in record.selector" :key="sel" class="info-large-tag">{{ sel }}</a-tag>
</template>
</template>
</a-table>
</template>
<BalancerFormModal v-model:open="modalOpen" :balancer="editingBalancer" :outbound-tags="outboundTags"
:other-tags="otherTags" @confirm="onConfirm" />
</a-space>
</template>
<style scoped>
.row-index {
font-weight: 500;
opacity: 0.7;
margin-right: 6px;
}
.action-btn {
vertical-align: middle;
}
.danger {
color: #ff4d4f;
}
</style>

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