mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-05 08:44:48 +03:00
test(ssl): preserve installer migration during upstream merge
Keep both installer regressions and verify a failed certificate still allows one migration before service startup. Retain the current PostgreSQL gates.
This commit is contained in:
@@ -93,6 +93,16 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL maintenance fencing and recovery
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -p=1 . ./internal/database -run '^Test(PostgresCLIWorkFenceSurvivesSessionLoss|PostgresExclusiveRestoreFenceSurvivesSessionLoss|PostgresPendingRestoreRetriesBeforeServing|PostgresRuntimeMaintenanceReacquiresAfterSessionLoss|MaintenanceAcrossProcesses)$' -count=1 -v | tee /tmp/postgres-maintenance.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-maintenance.log || true)
|
||||
if [ "$passed" -ne 5 ]; then
|
||||
echo "expected 5 passing PostgreSQL maintenance tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL inbound add orphan cleanup
|
||||
run: |
|
||||
set -o pipefail
|
||||
@@ -163,13 +173,56 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL inbound catalog scope and projection
|
||||
run: go test ./internal/web -run '^TestRemoteInboundCatalogScopeAndProjection$' -count=1 -v
|
||||
|
||||
- name: PostgreSQL online attribution regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -p=1 ./internal/web/job ./internal/web/service -run '^Test(InboundOnlineAvailabilityDistinguishesEmptyFromMissing|SetRemoteTraffic_RemapsActiveInboundTreeAndCentralTags|XrayTrafficRetryDoesNotPublishOnlineStateAcrossCoreReplacement)$' -count=1 -v | tee /tmp/postgres-online-attribution.log
|
||||
passed=$(grep -c -- '^--- PASS: Test' /tmp/postgres-online-attribution.log || true)
|
||||
if [ "$passed" -ne 3 ]; then
|
||||
echo "expected 3 passing PostgreSQL online attribution tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL node client push ordering
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log
|
||||
go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush|Create(GroupsCompatibleInboundsOnOneRemote|SplitsFlowAndSendsResolvedInbounds|UsesEffectiveAllowedIPsOnRemote|DispatchesReadyLaneBeforeBlockedLane|CancellationStopsFurtherNodeWaves)|GroupedCreate(ReconcilesUnsentRebasedSettings|RecoversIndeterminateDelivery|RepairsDeferredTargets|DispatchesIndependentReadyPayload|OrdersLaterClientMutations|ReconcileBarrierDrainsAfterAcknowledgment|KeepsFifthNodeDurablyPendingWhenBudgetExpires|PreservesProtocolCredentials))$' -count=1 -v | tee /tmp/postgres-node-client-order.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true)
|
||||
if [ "$passed" -ne 8 ]; then
|
||||
echo "expected 8 passing PostgreSQL node client ordering tests, got $passed" >&2
|
||||
if [ "$passed" -ne 21 ]; then
|
||||
echo "expected 21 passing PostgreSQL node client ordering tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL client inbound read regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^Test(ClientCreate(ReadsInboundSettingsOnlyForMutation|ClearsFlowOnIneligibleInbound|PreservesSettingsBasedDefaults)|UpdateInboundClientReadsSettingsOnceBeforeCommit|Slim(Create(UsesLockedFlowForGroupedDelivery|HealthyTargetsProgressWithBlockedPeer|ProjectionPreservesNodeIDAndProtocolSettings)|AttachUsesLockedFlowAndPreservesRawAdd|UpdateRebasesConcurrentSettings))$' -count=1 -v | tee /tmp/postgres-client-inbound-reads.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-inbound-reads.log || true)
|
||||
if [ "$passed" -ne 9 ]; then
|
||||
echo "expected 9 passing PostgreSQL client inbound read tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL paged group client workflows
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/controller -run '^Test(GroupClientPageAndFrozenWriteHTTP|GroupBulkOperationsRespectFrozenMembersHTTP|GroupBulkAddResolvesInboundMembershipHTTP|GroupSubscriptionExportAndPagingHTTP|GroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses)$' -count=1 -v | tee /tmp/postgres-group-clients.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-group-clients.log || true)
|
||||
if [ "$passed" -ne 5 ]; then
|
||||
echo "expected 5 passing PostgreSQL group client tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL frozen group identity
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^TestFrozenGroupBulk(RejectsIdentityAndMembershipChanges|AppliesLinkedTargets|AdjustSurvivesMembershipMoveAfterCommit|AdjustRollsBackWhenTrafficWriteFails)$' -count=1 -v | tee /tmp/postgres-frozen-group-identity.log
|
||||
passed=$(grep -c -- '^--- PASS: TestFrozenGroupBulk' /tmp/postgres-frozen-group-identity.log || true)
|
||||
if [ "$passed" -ne 4 ]; then
|
||||
echo "expected 4 passing PostgreSQL frozen group tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -213,6 +266,12 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL scoped detach regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^TestScopedDetach' -count=1 -v | tee /tmp/postgres-scoped-detach.log
|
||||
test "$(grep -c -- '^--- PASS: TestScopedDetach' /tmp/postgres-scoped-detach.log)" -eq 3
|
||||
|
||||
- name: PostgreSQL depletion query regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
@@ -223,6 +282,36 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL database maintenance contention
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -p=1 . ./internal/database ./internal/web/job -run '^Test(MaintenanceAcrossProcesses|PostgresRuntimeMaintenanceReacquiresAfterSessionLoss|PostgresPendingRestoreRetriesBeforeServing|DatabaseRestoreDrainsAnInFlightNodePoll)$' -count=1 -v | tee /tmp/postgres-maintenance.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-maintenance.log || true)
|
||||
if [ "$passed" -ne 4 ]; then
|
||||
echo "expected 4 passing PostgreSQL database maintenance tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL inbound migration contention
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test -p=1 ./internal/database ./internal/web/service -run '^(TestInitDBKeepsRestorePoolPrivate|TestMigrationRequirementsRejectsLiveNodeMergePostgres|TestInboundMigrationAllowsPostgresReaders)$' -count=1 -v | tee /tmp/postgres-inbound-migration.log
|
||||
passed=$(grep -c -- '^--- PASS' /tmp/postgres-inbound-migration.log || true)
|
||||
if [ "$passed" -ne 3 ]; then
|
||||
echo "expected 3 passing PostgreSQL inbound migration and restore tests, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL slim inbound cache regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^TestSlimInboundListReusesOnlyTheMatchingSettingsRevision$' -count=1 -v | tee /tmp/postgres-slim-inbound-cache.log
|
||||
passed=$(grep -c -- '^--- PASS: TestSlimInboundListReusesOnlyTheMatchingSettingsRevision ' /tmp/postgres-slim-inbound-cache.log || true)
|
||||
if [ "$passed" -ne 1 ]; then
|
||||
echo "expected the PostgreSQL slim inbound cache regression to pass, got $passed" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL node snapshot regressions
|
||||
run: |
|
||||
set -o pipefail
|
||||
|
||||
@@ -148,8 +148,8 @@ jobs:
|
||||
rm -f geoip.dat geosite.dat
|
||||
fetch https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||
fetch https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat
|
||||
fetch -O geoip_IR.dat https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat
|
||||
fetch -O geosite_IR.dat https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat
|
||||
fetch -O geoip_IR.dat https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geoip.dat
|
||||
fetch -O geosite_IR.dat https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geosite.dat
|
||||
fetch -O geoip_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||
fetch -O geosite_RU.dat https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat
|
||||
mv xray xray-linux-${{ matrix.platform }}
|
||||
@@ -290,8 +290,8 @@ jobs:
|
||||
Remove-Item geoip.dat, geosite.dat -ErrorAction SilentlyContinue
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat" -OutFile "geoip.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat" -OutFile "geosite.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat" -OutFile "geoip_IR.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat" -OutFile "geosite_IR.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geoip.dat" -OutFile "geoip_IR.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geosite.dat" -OutFile "geosite_IR.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geoip.dat" -OutFile "geoip_RU.dat"
|
||||
Invoke-WebRequest @retry -Uri "https://github.com/runetfreedom/russia-v2ray-rules-dat/releases/latest/download/geosite.dat" -OutFile "geosite_RU.dat"
|
||||
Rename-Item xray.exe xray-windows-amd64.exe
|
||||
|
||||
+2
-2
@@ -66,8 +66,8 @@ rm -rf "${MTG_PKG}" "${MTG_PKG}.tar.gz"
|
||||
chmod +x "${MTG_BIN}"
|
||||
curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat
|
||||
curl -sfLRO https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat
|
||||
curl -sfLRo geoip_IR.dat https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat
|
||||
curl -sfLRo geosite_IR.dat https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat
|
||||
curl -sfLRo geoip_IR.dat https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geoip.dat
|
||||
curl -sfLRo geosite_IR.dat https://github.com/FDeghy/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 ../../
|
||||
|
||||
+1
-1
@@ -191,7 +191,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
|
||||
|
||||
## الاعتراف
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (الترخيص: **GPL-3.0**): _قواعد توجيه v2ray/xray و v2ray/xray-clients المحسنة مع النطاقات الإيرانية المدمجة وتركيز على الأمان وحظر الإعلانات._
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (الترخيص: **GPL-3.0**): _قواعد توجيه v2ray/xray و v2ray/xray-clients المحسنة مع النطاقات الإيرانية المدمجة وتركيز على الأمان وحظر الإعلانات._
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (الترخيص: **GPL-3.0**): _يحتوي هذا المستودع على قواعد توجيه V2Ray محدثة تلقائيًا بناءً على بيانات النطاقات والعناوين المحظورة في روسيا._
|
||||
|
||||
## أدوات المجتمع
|
||||
|
||||
+1
-1
@@ -191,7 +191,7 @@ Las contribuciones son bienvenidas. Por favor, lee la [Guía de contribución](/
|
||||
|
||||
## Reconocimientos
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (Licencia: **GPL-3.0**): _Reglas de enrutamiento mejoradas para v2ray/xray y v2ray/xray-clients con dominios iraníes incorporados y un enfoque en seguridad y bloqueo de anuncios._
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (Licencia: **GPL-3.0**): _Reglas de enrutamiento mejoradas para v2ray/xray y v2ray/xray-clients con dominios iraníes incorporados y un enfoque en seguridad y bloqueo de anuncios._
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (Licencia: **GPL-3.0**): _Este repositorio contiene reglas de enrutamiento V2Ray actualizadas automáticamente basadas en datos de dominios y direcciones bloqueadas en Rusia._
|
||||
|
||||
## Herramientas de la Comunidad
|
||||
|
||||
+1
-1
@@ -191,7 +191,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
|
||||
|
||||
## قدردانی
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (مجوز: **GPL-3.0**): _قوانین مسیریابی بهبود یافته v2ray/xray و v2ray/xray-clients با دامنههای ایرانی داخلی و تمرکز بر امنیت و مسدود کردن تبلیغات._
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (مجوز: **GPL-3.0**): _قوانین مسیریابی بهبود یافته v2ray/xray و v2ray/xray-clients با دامنههای ایرانی داخلی و تمرکز بر امنیت و مسدود کردن تبلیغات._
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (مجوز: **GPL-3.0**): _این مخزن شامل قوانین مسیریابی V2Ray بهروزرسانی شده خودکار بر اساس دادههای دامنهها و آدرسهای مسدود شده در روسیه است._
|
||||
|
||||
## ابزارهای جامعه
|
||||
|
||||
@@ -191,7 +191,7 @@ Contributions are welcome. Please read the [Contributing Guide](/CONTRIBUTING.md
|
||||
|
||||
## Acknowledgment
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (License: **GPL-3.0**): _Enhanced v2ray/xray and v2ray/xray-clients routing rules with built-in Iranian domains and a focus on security and adblocking._
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (License: **GPL-3.0**): _Enhanced v2ray/xray and v2ray/xray-clients routing rules with built-in Iranian domains and a focus on security and adblocking._
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (License: **GPL-3.0**): _This repository contains automatically updated V2Ray routing rules based on data on blocked domains and addresses in Russia._
|
||||
|
||||
## Community Tools
|
||||
|
||||
+1
-1
@@ -191,7 +191,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
|
||||
|
||||
## Благодарности
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (Лицензия: **GPL-3.0**): _Улучшенные правила маршрутизации для v2ray/xray и v2ray/xray-clients со встроенными иранскими доменами и фокусом на безопасность и блокировку рекламы._
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (Лицензия: **GPL-3.0**): _Улучшенные правила маршрутизации для v2ray/xray и v2ray/xray-clients со встроенными иранскими доменами и фокусом на безопасность и блокировку рекламы._
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (Лицензия: **GPL-3.0**): _Этот репозиторий содержит автоматически обновляемые правила маршрутизации V2Ray на основе данных о заблокированных доменах и адресах в России._
|
||||
|
||||
## Инструменты сообщества
|
||||
|
||||
+1
-1
@@ -191,7 +191,7 @@ Katkılarınızı her zaman bekliyoruz. Bir sorun (issue) açmadan veya pull req
|
||||
|
||||
## Teşekkür & Atıf
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (Lisans: **GPL-3.0**): _Geliştirilmiş v2ray/xray ve v2ray/xray-clients yönlendirme (routing) kuralları; yerleşik İran alan adları ile güvenlik ve reklam engelleme odaklıdır._
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (Lisans: **GPL-3.0**): _Geliştirilmiş v2ray/xray ve v2ray/xray-clients yönlendirme (routing) kuralları; yerleşik İran alan adları ile güvenlik ve reklam engelleme odaklıdır._
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (Lisans: **GPL-3.0**): _Bu depo, Rusya'daki engellenen alan adları ve adreslere dayalı otomatik olarak güncellenen V2Ray yönlendirme kurallarını içerir._
|
||||
|
||||
## Topluluk Araçları
|
||||
|
||||
+1
-1
@@ -191,7 +191,7 @@ English · فارسی · العربية · 中文(简体) · 中文(繁體
|
||||
|
||||
## 致谢
|
||||
|
||||
- [Iran v2ray rules](https://github.com/chocolate4u/Iran-v2ray-rules) (许可证: **GPL-3.0**): _增强的 v2ray/xray 和 v2ray/xray-clients 路由规则,内置伊朗域名,专注于安全性和广告拦截。_
|
||||
- [Iran v2ray rules](https://github.com/FDeghy/Iran-v2ray-rules) (许可证: **GPL-3.0**): _增强的 v2ray/xray 和 v2ray/xray-clients 路由规则,内置伊朗域名,专注于安全性和广告拦截。_
|
||||
- [Russia v2ray rules](https://github.com/runetfreedom/russia-v2ray-rules-dat) (许可证: **GPL-3.0**): _此仓库包含基于俄罗斯被阻止域名和地址数据自动更新的 V2Ray 路由规则。_
|
||||
|
||||
## 社区工具
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
)
|
||||
|
||||
func openPanelDatabase(finish func(*gorm.DB) error) (*database.MaintenanceLease, error) {
|
||||
lease, err := database.AcquireStartupMaintenance(context.Background())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := lease.InitDB(config.GetDBPath(), finish); err != nil {
|
||||
return nil, errors.Join(err, database.CloseDB(), lease.Close())
|
||||
}
|
||||
return lease, nil
|
||||
}
|
||||
|
||||
func recoverPendingPostgresRestore(db *gorm.DB) error {
|
||||
if db.Name() != database.DialectPostgres {
|
||||
return nil
|
||||
}
|
||||
pending, err := database.PendingPostgresRestoreForSchema(db)
|
||||
if err != nil || !pending {
|
||||
return err
|
||||
}
|
||||
if err := (&service.InboundService{}).MigrateDBOn(db); err != nil {
|
||||
return fmt.Errorf("retry pending PostgreSQL restore migration: %w", err)
|
||||
}
|
||||
return database.ClearPostgresRestorePending(db)
|
||||
}
|
||||
|
||||
func closePanelDatabase(lease *database.MaintenanceLease) {
|
||||
if err := errors.Join(database.CloseDB(), lease.Close()); err != nil {
|
||||
log.Printf("close database: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Routine CLI commands can use an already initialized database while a panel is running.
|
||||
func withCLIWorkingDatabase(work func() error) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), database.MaintenanceWait)
|
||||
lease, err := database.TryConfiguredMaintenance(ctx, true)
|
||||
cancel()
|
||||
if err == nil {
|
||||
err = lease.InitDB(config.GetDBPath(), recoverPendingPostgresRestore)
|
||||
} else if errors.Is(err, database.ErrMaintenanceBusy) {
|
||||
wait, cancel := context.WithTimeout(context.Background(), database.MaintenanceWait)
|
||||
defer cancel()
|
||||
lease, err = database.AcquireConfiguredMaintenance(wait, false)
|
||||
if err == nil {
|
||||
err = database.OpenInitializedDB(config.GetDBPath())
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
if lease != nil {
|
||||
err = errors.Join(err, database.CloseDB(), lease.Close())
|
||||
}
|
||||
return err
|
||||
}
|
||||
defer closePanelDatabase(lease)
|
||||
return lease.RunCLIWork(work)
|
||||
}
|
||||
|
||||
func watchPanelDatabaseLease(ctx context.Context, lease *database.MaintenanceLease) {
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
outage := false
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
ping, cancel := context.WithTimeout(ctx, database.MaintenanceWait)
|
||||
err := lease.CheckRuntimeConnection(ping)
|
||||
cancel()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
if !outage {
|
||||
log.Printf("PostgreSQL maintenance lease lost; database work paused: %v", err)
|
||||
outage = true
|
||||
}
|
||||
retry, cancelRetry := context.WithTimeout(ctx, database.MaintenanceWait)
|
||||
err = lease.RecoverRuntimeConnection(retry)
|
||||
cancelRetry()
|
||||
}
|
||||
if err == nil && outage {
|
||||
log.Print("PostgreSQL maintenance lease recovered")
|
||||
outage = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func withSQLiteMaintenance(path string, exclusive bool, work func() error) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), database.MaintenanceWait)
|
||||
defer cancel()
|
||||
lease, err := database.AcquireSQLiteMaintenance(ctx, path, exclusive)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lease.Close()
|
||||
return work()
|
||||
}
|
||||
|
||||
func migrateDatabaseFile(src, dsn string) error {
|
||||
// MigrateData reads each source table independently; keep the source
|
||||
// unchanged until the destination finishes importing the whole database.
|
||||
return withSQLiteMaintenance(src, true, func() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), database.MaintenanceWait)
|
||||
defer cancel()
|
||||
lease, err := database.AcquirePostgresMaintenance(ctx, dsn, true)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lock migration target: %w", err)
|
||||
}
|
||||
defer lease.Close()
|
||||
return lease.MigrateData(src, dsn)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/op/go-logging"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
||||
)
|
||||
|
||||
func TestPostgresPendingRestoreRetriesBeforeServing(t *testing.T) {
|
||||
if config.GetDBKind() != database.DialectPostgres {
|
||||
t.Skip("requires PostgreSQL migration locks")
|
||||
}
|
||||
cleanup, err := testpg.IsolatePackage("pending_restore")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
logger.InitLogger(logging.ERROR)
|
||||
t.Setenv("XUI_DB_FOLDER", t.TempDir())
|
||||
dbtest.InitDB(t, filepath.Join(config.GetDBFolderPath(), "x-ui.db"))
|
||||
db := database.GetDB()
|
||||
lease, err := database.AcquireConfiguredMaintenance(t.Context(), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Close()
|
||||
if err := lease.WithPostgresWork(db, database.MarkPostgresRestorePending); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lease.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("XUI_DB_FOLDER", t.TempDir())
|
||||
wait, cancel := context.WithTimeout(t.Context(), database.MaintenanceWait)
|
||||
defer cancel()
|
||||
if shared, err := database.AcquireConfiguredMaintenance(wait, false); !errors.Is(err, database.ErrPostgresRestorePending) {
|
||||
if shared != nil {
|
||||
_ = shared.Close()
|
||||
}
|
||||
t.Fatalf("another installation acquired shared access before repair: %v", err)
|
||||
}
|
||||
|
||||
reader := db.Begin()
|
||||
defer reader.Rollback()
|
||||
if err := reader.Exec("LOCK TABLE inbounds IN ROW EXCLUSIVE MODE").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lease, err = database.AcquireConfiguredMaintenance(wait, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Close()
|
||||
if err := lease.WithPostgresWork(db, recoverPendingPostgresRestore); err == nil {
|
||||
t.Fatal("startup recovery succeeded while another session blocked migration")
|
||||
}
|
||||
if pending, err := database.PostgresRestorePending(db); err != nil || !pending {
|
||||
t.Fatalf("pending state after failure = %t, %v", pending, err)
|
||||
}
|
||||
|
||||
if err := reader.Rollback().Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lease.InitDB(config.GetDBPath(), recoverPendingPostgresRestore); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if pending, err := database.PostgresRestorePending(database.GetDB()); err != nil || pending {
|
||||
t.Fatalf("pending state after successful recovery = %t, %v", pending, err)
|
||||
}
|
||||
if err := lease.SetExclusive(wait, false); err != nil {
|
||||
t.Fatalf("cannot resume runtime after repair: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ The overview page combines a current server snapshot with short time-series char
|
||||
|
||||
## Choose a chart window
|
||||
|
||||
Each overview chart has the same time-range selector in its upper-right corner. The default is **2m**. The choices are **2m**, **5m**, **30m**, **1h**, **6h**, and **12h**. Changing any selector changes the window on every overview chart.
|
||||
Use **Time range** beside **Xray Metrics** to change the window on every overview chart. The choices are **2m**, **5m**, **30m**, **1h**, **6h**, and **12h**. The default is **2m**. This browser remembers your selection for the panel across reloads and panel restarts.
|
||||
|
||||
The number of chart points stays capped at 60. Short windows use finer samples; longer windows use averages. At **2m** the charts are live: every status poll, once every 2 seconds, adds a point. A longer window is read from the server's stored history and refreshed once per point, at most once a minute.
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@ _openapi:
|
||||
the eligible IDs that match the given search and group for the chosen
|
||||
source and targets.
|
||||
url: '#list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets'
|
||||
- depth: 2
|
||||
title: Return up to 50 client emails for the routing rule user picker.
|
||||
url: '#return-up-to-50-client-emails-for-the-routing-rule-user-picker'
|
||||
- depth: 2
|
||||
title: 'Filter, sort, and paginate clients on the server. Each item is a slim
|
||||
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
|
||||
@@ -183,31 +186,23 @@ _openapi:
|
||||
changed count and per-email skip reasons.
|
||||
url: '#disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons'
|
||||
- depth: 2
|
||||
title: Delete many clients in one call. The server processes the list
|
||||
sequentially so each delete sees the committed state of the previous one
|
||||
— avoids the race the per-email fan-out had on the panel side. Pass
|
||||
keepTraffic=true to retain the xray_client_traffic rows after deletion.
|
||||
url: '#delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion'
|
||||
title: Delete clients identified by emails or by a server-resolved group. Set
|
||||
keepTraffic to retain client counters.
|
||||
url: '#delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters'
|
||||
- depth: 2
|
||||
title: Create many clients in one call. Body is a JSON array of {client,
|
||||
inboundIds} payloads — the same shape /add accepts. Items are processed
|
||||
sequentially; per-email skip reasons are returned for items that fail
|
||||
(e.g., duplicate email). Triggers a single Xray restart at the end if
|
||||
any inbound was running.
|
||||
url: '#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running'
|
||||
title: Create many clients in one call. Use subIdPrefix to generate a
|
||||
subscription ID with an independent cryptographically random suffix.
|
||||
Omit client.subId or leave it empty on that item. The result includes
|
||||
per-email skip reasons.
|
||||
url: '#create-many-clients-in-one-call-use-subidprefix-to-generate-a-subscription-id-with-an-independent-cryptographically-random-suffix-omit-clientsubid-or-leave-it-empty-on-that-item-the-result-includes-per-email-skip-reasons'
|
||||
- depth: 2
|
||||
title: Add many clients to a group in one call. Updates clients.group_name and
|
||||
patches the matching client entry inside every owning inbound's settings
|
||||
JSON in a single transaction. If the group name does not yet exist (in
|
||||
client_groups or as a derived label), it is auto-created as a persistent
|
||||
group. To clear the group label, use /groups/bulkRemove instead.
|
||||
url: '#add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead'
|
||||
title: Move clients into a group and update every owning inbound's settings in
|
||||
the same transaction.
|
||||
url: '#move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction'
|
||||
- depth: 2
|
||||
title: Clear the group label on many clients in one call. Inverse of
|
||||
/groups/bulkAdd. Clients themselves are kept — only the group label is
|
||||
cleared from clients.group_name and from each owning inbound's settings
|
||||
JSON. Groups become empty if all their members are removed.
|
||||
url: '#clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed'
|
||||
title: Clear group membership and preserve the clients. Use either emails or a
|
||||
selection scoped to the named group.
|
||||
url: '#clear-group-membership-and-preserve-the-clients-use-either-emails-or-a-selection-scoped-to-the-named-group'
|
||||
- depth: 2
|
||||
title: Attach many existing clients to many inbounds in one call. Each client
|
||||
keeps its identity (email/UUID/password/subId) and a shared traffic row;
|
||||
@@ -229,16 +224,31 @@ _openapi:
|
||||
process.
|
||||
url: '#poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process'
|
||||
- depth: 2
|
||||
title: "Mirror of bulkAttach: detach many existing clients from many inbounds in
|
||||
one call. For each email, intersects the client's current inbounds with
|
||||
the requested set and detaches from those only; (email, inbound) pairs
|
||||
where the client is not currently attached are silently no-ops. Emails
|
||||
not attached to any of the requested inbounds are reported under
|
||||
skipped. Client records are kept even if they become orphaned — use
|
||||
bulkDel for full removal. Returns per-email detached/skipped/errors
|
||||
lists and triggers a single Xray restart if any target inbound was
|
||||
running."
|
||||
url: '#mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
|
||||
title: Read up to 100 clients currently attached to one inbound. Search matches
|
||||
email or comment. The response includes filtered and attached totals,
|
||||
and marks candidates belonging to an optional frozen scope.
|
||||
url: '#read-up-to-100-clients-currently-attached-to-one-inbound-search-matches-email-or-comment-the-response-includes-filtered-and-attached-totals-and-marks-candidates-belonging-to-an-optional-frozen-scope'
|
||||
- depth: 2
|
||||
title: Freeze up to 100,000 current memberships of one inbound and return their
|
||||
count and an opaque token. Search does not narrow this selection. Tokens
|
||||
expire after 15 minutes and are held in a bounded in-memory history.
|
||||
url: '#freeze-up-to-100000-current-memberships-of-one-inbound-and-return-their-count-and-an-opaque-token-search-does-not-narrow-this-selection-tokens-expire-after-15-minutes-and-are-held-in-a-bounded-in-memory-history'
|
||||
- depth: 2
|
||||
title: Detach client memberships while keeping records and traffic. Legacy email
|
||||
requests accept multiple inbounds and return detached/skipped/errors
|
||||
lists. Scoped requests take exactly one inbound and either explicit
|
||||
clientIds or a frozen allMatching scopeToken with excludedClientIds.
|
||||
Supply a requestId UUID and reuse it with the same payload when
|
||||
retrying. The scoped response is {jobId}. Poll GET /bulkDetach/:id for
|
||||
progress and counts. Changed memberships are skipped and newly attached
|
||||
clients stay outside a frozen scope.
|
||||
url: '#detach-client-memberships-while-keeping-records-and-traffic-legacy-email-requests-accept-multiple-inbounds-and-return-detachedskippederrors-lists-scoped-requests-take-exactly-one-inbound-and-either-explicit-clientids-or-a-frozen-allmatching-scopetoken-with-excludedclientids-supply-a-requestid-uuid-and-reuse-it-with-the-same-payload-when-retrying-the-scoped-response-is-jobid-poll-get-bulkdetachid-for-progress-and-counts-changed-memberships-are-skipped-and-newly-attached-clients-stay-outside-a-frozen-scope'
|
||||
- depth: 2
|
||||
title: Poll a scoped detachment job. A completed result reports detached,
|
||||
skipped and failed client counts and whether node reconciliation is
|
||||
pending. Jobs are retained in a bounded in-memory history for up to 15
|
||||
minutes after completion.
|
||||
url: '#poll-a-scoped-detachment-job-a-completed-result-reports-detached-skipped-and-failed-client-counts-and-whether-node-reconciliation-is-pending-jobs-are-retained-in-a-bounded-in-memory-history-for-up-to-15-minutes-after-completion'
|
||||
- depth: 2
|
||||
title: Zero up/down counters for many clients in one call. Loops the
|
||||
single-reset path so each client its quota had disabled is re-enabled
|
||||
@@ -258,6 +268,14 @@ _openapi:
|
||||
other clients are unaffected. An empty array clears the bindings.
|
||||
Returns the saved host group IDs.
|
||||
url: '#replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids'
|
||||
- depth: 2
|
||||
title: Page through group candidates, members or subscription IDs. Pages are
|
||||
one-based with a fixed size of 100 and an exact total.
|
||||
url: '#page-through-group-candidates-members-or-subscription-ids-pages-are-one-based-with-a-fixed-size-of-100-and-an-exact-total'
|
||||
- depth: 2
|
||||
title: Stream all subscription links for a group as tab-separated text. Each row
|
||||
has an email and regular link, followed by a JSON link when enabled.
|
||||
url: '#stream-all-subscription-links-for-a-group-as-tab-separated-text-each-row-has-an-email-and-regular-link-followed-by-a-json-link-when-enabled'
|
||||
- depth: 2
|
||||
title: Return just the email list of clients that currently belong to the given
|
||||
group. Useful for fanning a single bulk action over an entire group
|
||||
@@ -336,10 +354,9 @@ _openapi:
|
||||
- depth: 2
|
||||
title: Online client emails grouped by the panelGuid of the node that physically
|
||||
hosts each client. The local panel uses its own GUID; each node (at any
|
||||
depth in a chain) uses its GUID. Lets the inbounds page attribute online
|
||||
status to the real node instead of the intermediate one it syncs
|
||||
through.
|
||||
url: '#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through'
|
||||
depth in a chain) uses its GUID. An empty list means the node reported
|
||||
no online clients. An absent GUID means there is no usable report.
|
||||
url: '#online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-an-empty-list-means-the-node-reported-no-online-clients-an-absent-guid-means-there-is-no-usable-report'
|
||||
- depth: 2
|
||||
title: Per-client source IPs grouped by the panelGuid of the node that observed
|
||||
them. Lets the central panel attribute and enforce per-client IP limits
|
||||
@@ -348,10 +365,12 @@ _openapi:
|
||||
url: '#per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through'
|
||||
- depth: 2
|
||||
title: Inbound tags that carried traffic within the heartbeat window, grouped by
|
||||
the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds
|
||||
page only marks a multi-inbound client online on the inbounds it
|
||||
actually used. Nodes that do not report per-inbound activity are absent.
|
||||
url: '#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent'
|
||||
the hosting node's panelGuid. Use with onlinesByGuid to scope online
|
||||
counts. An empty list means no active tags, an absent GUID means there
|
||||
is no usable report, and null means a confirmed legacy node lacks the
|
||||
activity endpoint. The reserved NUL tag (U+0000) marks a partial report.
|
||||
Inbounds whose tags are absent remain unknown.
|
||||
url: '#inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-use-with-onlinesbyguid-to-scope-online-counts-an-empty-list-means-no-active-tags-an-absent-guid-means-there-is-no-usable-report-and-null-means-a-confirmed-legacy-node-lacks-the-activity-endpoint-the-reserved-nul-tag-u0000-marks-a-partial-report-inbounds-whose-tags-are-absent-remain-unknown'
|
||||
- depth: 2
|
||||
title: Map of client email → last-seen unix timestamp.
|
||||
url: '#map-of-client-email--last-seen-unix-timestamp'
|
||||
@@ -411,6 +430,8 @@ _openapi:
|
||||
the eligible IDs that match the given search and group for the chosen
|
||||
source and targets.
|
||||
id: list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets
|
||||
- content: Return up to 50 client emails for the routing rule user picker.
|
||||
id: return-up-to-50-client-emails-for-the-routing-rule-user-picker
|
||||
- content: 'Filter, sort, and paginate clients on the server. Each item is a slim
|
||||
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
|
||||
page can ship 25-ish rows in a few KB instead of the full table. The
|
||||
@@ -548,30 +569,20 @@ _openapi:
|
||||
(local or remote node) is updated to remove each user. Returns the
|
||||
changed count and per-email skip reasons.
|
||||
id: disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons
|
||||
- content: Delete many clients in one call. The server processes the list
|
||||
sequentially so each delete sees the committed state of the previous
|
||||
one — avoids the race the per-email fan-out had on the panel side.
|
||||
Pass keepTraffic=true to retain the xray_client_traffic rows after
|
||||
deletion.
|
||||
id: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
|
||||
- content: Create many clients in one call. Body is a JSON array of {client,
|
||||
inboundIds} payloads — the same shape /add accepts. Items are
|
||||
processed sequentially; per-email skip reasons are returned for items
|
||||
that fail (e.g., duplicate email). Triggers a single Xray restart at
|
||||
the end if any inbound was running.
|
||||
id: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
|
||||
- content: Add many clients to a group in one call. Updates clients.group_name and
|
||||
patches the matching client entry inside every owning inbound's
|
||||
settings JSON in a single transaction. If the group name does not yet
|
||||
exist (in client_groups or as a derived label), it is auto-created as
|
||||
a persistent group. To clear the group label, use /groups/bulkRemove
|
||||
instead.
|
||||
id: add-many-clients-to-a-group-in-one-call-updates-clientsgroup_name-and-patches-the-matching-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-if-the-group-name-does-not-yet-exist-in-client_groups-or-as-a-derived-label-it-is-auto-created-as-a-persistent-group-to-clear-the-group-label-use-groupsbulkremove-instead
|
||||
- content: Clear the group label on many clients in one call. Inverse of
|
||||
/groups/bulkAdd. Clients themselves are kept — only the group label is
|
||||
cleared from clients.group_name and from each owning inbound's
|
||||
settings JSON. Groups become empty if all their members are removed.
|
||||
id: clear-the-group-label-on-many-clients-in-one-call-inverse-of-groupsbulkadd-clients-themselves-are-kept--only-the-group-label-is-cleared-from-clientsgroup_name-and-from-each-owning-inbounds-settings-json-groups-become-empty-if-all-their-members-are-removed
|
||||
- content: Delete clients identified by emails or by a server-resolved group. Set
|
||||
keepTraffic to retain client counters.
|
||||
id: delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters
|
||||
- content: Create many clients in one call. Use subIdPrefix to generate a
|
||||
subscription ID with an independent cryptographically random suffix.
|
||||
Omit client.subId or leave it empty on that item. The result includes
|
||||
per-email skip reasons.
|
||||
id: create-many-clients-in-one-call-use-subidprefix-to-generate-a-subscription-id-with-an-independent-cryptographically-random-suffix-omit-clientsubid-or-leave-it-empty-on-that-item-the-result-includes-per-email-skip-reasons
|
||||
- content: Move clients into a group and update every owning inbound's settings in
|
||||
the same transaction.
|
||||
id: move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction
|
||||
- content: Clear group membership and preserve the clients. Use either emails or a
|
||||
selection scoped to the named group.
|
||||
id: clear-group-membership-and-preserve-the-clients-use-either-emails-or-a-selection-scoped-to-the-named-group
|
||||
- content: Attach many existing clients to many inbounds in one call. Each client
|
||||
keeps its identity (email/UUID/password/subId) and a shared traffic
|
||||
row; all clients are added to a target inbound in a single
|
||||
@@ -590,16 +601,30 @@ _openapi:
|
||||
Completed results are retained for up to 15 minutes in the running
|
||||
panel process.
|
||||
id: poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process
|
||||
- content: "Mirror of bulkAttach: detach many existing clients from many inbounds
|
||||
in one call. For each email, intersects the client's current inbounds
|
||||
with the requested set and detaches from those only; (email, inbound)
|
||||
pairs where the client is not currently attached are silently no-ops.
|
||||
Emails not attached to any of the requested inbounds are reported
|
||||
under skipped. Client records are kept even if they become orphaned —
|
||||
use bulkDel for full removal. Returns per-email
|
||||
detached/skipped/errors lists and triggers a single Xray restart if
|
||||
any target inbound was running."
|
||||
id: mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
|
||||
- content: Read up to 100 clients currently attached to one inbound. Search
|
||||
matches email or comment. The response includes filtered and attached
|
||||
totals, and marks candidates belonging to an optional frozen scope.
|
||||
id: read-up-to-100-clients-currently-attached-to-one-inbound-search-matches-email-or-comment-the-response-includes-filtered-and-attached-totals-and-marks-candidates-belonging-to-an-optional-frozen-scope
|
||||
- content: Freeze up to 100,000 current memberships of one inbound and return
|
||||
their count and an opaque token. Search does not narrow this
|
||||
selection. Tokens expire after 15 minutes and are held in a bounded
|
||||
in-memory history.
|
||||
id: freeze-up-to-100000-current-memberships-of-one-inbound-and-return-their-count-and-an-opaque-token-search-does-not-narrow-this-selection-tokens-expire-after-15-minutes-and-are-held-in-a-bounded-in-memory-history
|
||||
- content: Detach client memberships while keeping records and traffic. Legacy
|
||||
email requests accept multiple inbounds and return
|
||||
detached/skipped/errors lists. Scoped requests take exactly one
|
||||
inbound and either explicit clientIds or a frozen allMatching
|
||||
scopeToken with excludedClientIds. Supply a requestId UUID and reuse
|
||||
it with the same payload when retrying. The scoped response is
|
||||
{jobId}. Poll GET /bulkDetach/:id for progress and counts. Changed
|
||||
memberships are skipped and newly attached clients stay outside a
|
||||
frozen scope.
|
||||
id: detach-client-memberships-while-keeping-records-and-traffic-legacy-email-requests-accept-multiple-inbounds-and-return-detachedskippederrors-lists-scoped-requests-take-exactly-one-inbound-and-either-explicit-clientids-or-a-frozen-allmatching-scopetoken-with-excludedclientids-supply-a-requestid-uuid-and-reuse-it-with-the-same-payload-when-retrying-the-scoped-response-is-jobid-poll-get-bulkdetachid-for-progress-and-counts-changed-memberships-are-skipped-and-newly-attached-clients-stay-outside-a-frozen-scope
|
||||
- content: Poll a scoped detachment job. A completed result reports detached,
|
||||
skipped and failed client counts and whether node reconciliation is
|
||||
pending. Jobs are retained in a bounded in-memory history for up to 15
|
||||
minutes after completion.
|
||||
id: poll-a-scoped-detachment-job-a-completed-result-reports-detached-skipped-and-failed-client-counts-and-whether-node-reconciliation-is-pending-jobs-are-retained-in-a-bounded-in-memory-history-for-up-to-15-minutes-after-completion
|
||||
- content: Zero up/down counters for many clients in one call. Loops the
|
||||
single-reset path so each client its quota had disabled is re-enabled
|
||||
across its attached inbounds and pushed to Xray/remote nodes; a client
|
||||
@@ -616,6 +641,13 @@ _openapi:
|
||||
host pool; other clients are unaffected. An empty array clears the
|
||||
bindings. Returns the saved host group IDs.
|
||||
id: replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids
|
||||
- content: Page through group candidates, members or subscription IDs. Pages are
|
||||
one-based with a fixed size of 100 and an exact total.
|
||||
id: page-through-group-candidates-members-or-subscription-ids-pages-are-one-based-with-a-fixed-size-of-100-and-an-exact-total
|
||||
- content: Stream all subscription links for a group as tab-separated text. Each
|
||||
row has an email and regular link, followed by a JSON link when
|
||||
enabled.
|
||||
id: stream-all-subscription-links-for-a-group-as-tab-separated-text-each-row-has-an-email-and-regular-link-followed-by-a-json-link-when-enabled
|
||||
- content: Return just the email list of clients that currently belong to the
|
||||
given group. Useful for fanning a single bulk action over an entire
|
||||
group without round-tripping the full client list.
|
||||
@@ -681,21 +713,22 @@ _openapi:
|
||||
id: list-the-emails-of-currently-connected-clients-last-seen-within-the-heartbeat-window-deduped-across-every-node
|
||||
- content: Online client emails grouped by the panelGuid of the node that
|
||||
physically hosts each client. The local panel uses its own GUID; each
|
||||
node (at any depth in a chain) uses its GUID. Lets the inbounds page
|
||||
attribute online status to the real node instead of the intermediate
|
||||
one it syncs through.
|
||||
id: online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-lets-the-inbounds-page-attribute-online-status-to-the-real-node-instead-of-the-intermediate-one-it-syncs-through
|
||||
node (at any depth in a chain) uses its GUID. An empty list means the
|
||||
node reported no online clients. An absent GUID means there is no
|
||||
usable report.
|
||||
id: online-client-emails-grouped-by-the-panelguid-of-the-node-that-physically-hosts-each-client-the-local-panel-uses-its-own-guid-each-node-at-any-depth-in-a-chain-uses-its-guid-an-empty-list-means-the-node-reported-no-online-clients-an-absent-guid-means-there-is-no-usable-report
|
||||
- content: Per-client source IPs grouped by the panelGuid of the node that
|
||||
observed them. Lets the central panel attribute and enforce per-client
|
||||
IP limits using the real visitor IPs each node sees, instead of the
|
||||
address of the intermediate panel it syncs through.
|
||||
id: per-client-source-ips-grouped-by-the-panelguid-of-the-node-that-observed-them-lets-the-central-panel-attribute-and-enforce-per-client-ip-limits-using-the-real-visitor-ips-each-node-sees-instead-of-the-address-of-the-intermediate-panel-it-syncs-through
|
||||
- content: Inbound tags that carried traffic within the heartbeat window, grouped
|
||||
by the hosting node's panelGuid. Pairs with onlinesByGuid so the
|
||||
inbounds page only marks a multi-inbound client online on the inbounds
|
||||
it actually used. Nodes that do not report per-inbound activity are
|
||||
absent.
|
||||
id: inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-pairs-with-onlinesbyguid-so-the-inbounds-page-only-marks-a-multi-inbound-client-online-on-the-inbounds-it-actually-used-nodes-that-do-not-report-per-inbound-activity-are-absent
|
||||
by the hosting node's panelGuid. Use with onlinesByGuid to scope
|
||||
online counts. An empty list means no active tags, an absent GUID
|
||||
means there is no usable report, and null means a confirmed legacy
|
||||
node lacks the activity endpoint. The reserved NUL tag (U+0000) marks
|
||||
a partial report. Inbounds whose tags are absent remain unknown.
|
||||
id: inbound-tags-that-carried-traffic-within-the-heartbeat-window-grouped-by-the-hosting-nodes-panelguid-use-with-onlinesbyguid-to-scope-online-counts-an-empty-list-means-no-active-tags-an-absent-guid-means-there-is-no-usable-report-and-null-means-a-confirmed-legacy-node-lacks-the-activity-endpoint-the-reserved-nul-tag-u0000-marks-a-partial-report-inbounds-whose-tags-are-absent-remain-unknown
|
||||
- content: Map of client email → last-seen unix timestamp.
|
||||
id: map-of-client-email--last-seen-unix-timestamp
|
||||
- content: Traffic counters for a client identified by email.
|
||||
@@ -988,7 +1021,13 @@ _openapi:
|
||||
- content: For node-backed changes, the result can include obj.nodeResults and
|
||||
obj.nodePending alongside the bulk counts and per-email results. A
|
||||
direct acknowledgment with downstream work pending still allows the
|
||||
batch to continue.
|
||||
batch to continue. Send emails for explicit clients or group for
|
||||
server-resolved members. Optionally send an unfiltered remove
|
||||
scopeToken from clientPage to reject stale membership while excluding
|
||||
clients created after the scope was frozen. Clients are checked before
|
||||
their first write. If a client changes groups after its first commit,
|
||||
the adjustment continues for the same client identity. Group responses
|
||||
include skippedCount and at most 20 representative skip records.
|
||||
heading: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-alternatively-send-externallinks-to-append-external-share-links-and-https-subscriptions-to-each-selected-client-in-one-transaction-this-mode-cannot-be-combined-with-other-adjustments-existing-entries-metadata-and-ordering-are-preserved-duplicates-match-kind-value-per-client-including-repeated-input-rows-the-first-entry-wins-missing-clients-are-not-written-and-appear-in-skipped-externallinksadded-counts-inserted-rows-externallinksskipped-counts-duplicate-rows-across-found-clients-externallinkserrors-counts-missing-clients-and-adjusted-counts-clients-receiving-at-least-one-new-row-validation-or-database-failure-aborts-the-whole-append-without-writes-repeating-an-append-is-idempotent-and-does-not-restart-xray
|
||||
- content: For node-backed changes, the result can include obj.nodeResults and
|
||||
obj.nodePending alongside the bulk counts and per-email results. A
|
||||
@@ -1003,13 +1042,26 @@ _openapi:
|
||||
- content: For node-backed changes, the result can include obj.nodeResults and
|
||||
obj.nodePending alongside the bulk counts and per-email results. A
|
||||
direct acknowledgment with downstream work pending still allows the
|
||||
batch to continue.
|
||||
heading: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion
|
||||
batch to continue. For group deletion, an unfiltered remove scopeToken
|
||||
from clientPage rejects stale membership before planning. Clients that
|
||||
leave the scope during the operation are skipped. Group responses
|
||||
include skippedCount and at most 20 representative skip records.
|
||||
heading: delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters
|
||||
- content: For node-backed changes, the result can include obj.nodeResults and
|
||||
obj.nodePending alongside the bulk counts and per-email results. A
|
||||
direct acknowledgment with downstream work pending still allows the
|
||||
batch to continue.
|
||||
heading: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running
|
||||
heading: create-many-clients-in-one-call-use-subidprefix-to-generate-a-subscription-id-with-an-independent-cryptographically-random-suffix-omit-clientsubid-or-leave-it-empty-on-that-item-the-result-includes-per-email-skip-reasons
|
||||
- content: Send one of emails, inboundId, or selection with the target group.
|
||||
Emails and inboundId can create the group. A picker selection targets
|
||||
an existing group and excludes current members. Explicit selections
|
||||
use clientIds. Frozen selections use scopeToken, the original search
|
||||
and up to 1,000 excludedClientIds. A stale selection makes no changes.
|
||||
heading: move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction
|
||||
- content: Explicit selections use clientIds. Frozen selections use scopeToken,
|
||||
the original search and up to 1,000 excludedClientIds. Only members of
|
||||
the selected group are eligible. A stale selection makes no changes.
|
||||
heading: clear-group-membership-and-preserve-the-clients-use-either-emails-or-a-selection-scoped-to-the-named-group
|
||||
- content: For node-backed changes, the result can include obj.nodeResults and
|
||||
obj.nodePending alongside the bulk counts and per-email results. A
|
||||
direct acknowledgment with downstream work pending still allows the
|
||||
@@ -1019,7 +1071,14 @@ _openapi:
|
||||
obj.nodePending alongside the bulk counts and per-email results. A
|
||||
direct acknowledgment with downstream work pending still allows the
|
||||
batch to continue.
|
||||
heading: mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
|
||||
heading: detach-client-memberships-while-keeping-records-and-traffic-legacy-email-requests-accept-multiple-inbounds-and-return-detachedskippederrors-lists-scoped-requests-take-exactly-one-inbound-and-either-explicit-clientids-or-a-frozen-allmatching-scopetoken-with-excludedclientids-supply-a-requestid-uuid-and-reuse-it-with-the-same-payload-when-retrying-the-scoped-response-is-jobid-poll-get-bulkdetachid-for-progress-and-counts-changed-memberships-are-skipped-and-newly-attached-clients-stay-outside-a-frozen-scope
|
||||
- content: Add mode excludes current members. Remove mode selects current members.
|
||||
Links mode selects members with a subscription ID. Search matches
|
||||
email, comment and group. freeze=true returns only the matching count,
|
||||
a scope token and the maximum ID for an add or remove selection. For
|
||||
subsequent pages, send maxId and scopeSearch to mark rows inside the
|
||||
frozen filter.
|
||||
heading: page-through-group-candidates-members-or-subscription-ids-pages-are-one-based-with-a-fixed-size-of-100-and-an-exact-total
|
||||
---
|
||||
|
||||
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
|
||||
@@ -1029,7 +1088,7 @@ export default function Layout(props) {
|
||||
return (
|
||||
<>
|
||||
{props.children}
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/attachCandidates","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkAttach/{id}","method":"get"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/attachCandidates","method":"get"},{"path":"/panel/api/clients/userSuggestions","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkAttach/{id}","method":"get"},{"path":"/panel/api/clients/detachCandidates","method":"get"},{"path":"/panel/api/clients/detachCandidates/freeze","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkDetach/{id}","method":"get"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/clientPage","method":"get"},{"path":"/panel/api/clients/groups/subLinks/export","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,11 @@ _openapi:
|
||||
for list pages; fetch /get/:id when you need the full per-client payload
|
||||
(uuid, password, flow, ...).
|
||||
url: '#same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-'
|
||||
- depth: 2
|
||||
title: List inbound metadata for the authenticated user. Returns id, tag,
|
||||
remark, listen, protocol, and port for remote ID lookup and
|
||||
reconciliation.
|
||||
url: '#list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation'
|
||||
- depth: 2
|
||||
title: Lightweight picker projection of the authenticated user’s inbounds.
|
||||
Returns id, remark, tag, protocol, port, a server-computed
|
||||
@@ -59,6 +64,13 @@ _openapi:
|
||||
- depth: 2
|
||||
title: Fetch a single inbound by numeric ID.
|
||||
url: '#fetch-a-single-inbound-by-numeric-id'
|
||||
- depth: 2
|
||||
title: Load inbound information and the first compatible client or a page of up
|
||||
to 50 tunnel peers.
|
||||
url: '#load-inbound-information-and-the-first-compatible-client-or-a-page-of-up-to-50-tunnel-peers'
|
||||
- depth: 2
|
||||
title: Stream the source pages for a WireGuard or AmneziaWG peer export.
|
||||
url: '#stream-the-source-pages-for-a-wireguard-or-amneziawg-peer-export'
|
||||
- depth: 2
|
||||
title: Create a new inbound. Send the full inbound payload (protocol, port,
|
||||
settings, streamSettings, sniffing, remark, expiryTime, total, enable).
|
||||
@@ -148,6 +160,10 @@ _openapi:
|
||||
Use this for list pages; fetch /get/:id when you need the full
|
||||
per-client payload (uuid, password, flow, ...).
|
||||
id: same-shape-as-list-but-with-settingsclients-stripped-down-to-email-enable-comment-and-clientstats-not-enriched-with-uuidsubid-use-this-for-list-pages-fetch-getid-when-you-need-the-full-per-client-payload-uuid-password-flow-
|
||||
- content: List inbound metadata for the authenticated user. Returns id, tag,
|
||||
remark, listen, protocol, and port for remote ID lookup and
|
||||
reconciliation.
|
||||
id: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation
|
||||
- content: Lightweight picker projection of the authenticated user’s inbounds.
|
||||
Returns id, remark, tag, protocol, port, a server-computed
|
||||
tlsFlowCapable flag (true for VLESS on TCP with tls or reality, or on
|
||||
@@ -174,6 +190,11 @@ _openapi:
|
||||
id: return-every-protocol-url-vless-vmess-trojan-ss-hysteria-mtproto-across-all-inbounds-and-all-of-their-clients-links-are-rendered-through-the-subscription-engine-so-the-configured-remark-template-name-only-display-part-is-applied-per-client--the-same-output-the-client-infoqr-pages-use-protocols-without-a-url-form-socks-http-mixed-wireguard-dokodemo-tunnel-contribute-nothing-used-by-the-panels-export-all-inbound-links-action
|
||||
- content: Fetch a single inbound by numeric ID.
|
||||
id: fetch-a-single-inbound-by-numeric-id
|
||||
- content: Load inbound information and the first compatible client or a page of
|
||||
up to 50 tunnel peers.
|
||||
id: load-inbound-information-and-the-first-compatible-client-or-a-page-of-up-to-50-tunnel-peers
|
||||
- content: Stream the source pages for a WireGuard or AmneziaWG peer export.
|
||||
id: stream-the-source-pages-for-a-wireguard-or-amneziawg-peer-export
|
||||
- content: Create a new inbound. Send the full inbound payload (protocol, port,
|
||||
settings, streamSettings, sniffing, remark, expiryTime, total,
|
||||
enable). settings, streamSettings, and sniffing may be sent as nested
|
||||
@@ -231,7 +252,20 @@ _openapi:
|
||||
decryption. An empty list can remove rules even from an incompatible
|
||||
inbound. Triggers an Xray restart.
|
||||
id: replace-the-entire-fallback-list-for-a-master-inbound-body-is-json-nonempty-lists-require-tcp-with-tlsreality-and-no-active-vless-server-decryption-an-empty-list-can-remove-rules-even-from-an-incompatible-inbound-triggers-an-xray-restart
|
||||
contents: []
|
||||
contents:
|
||||
- content: Available to panel sessions, admin, node-admin, and node-sync tokens.
|
||||
The catalog queries only metadata columns. An empty catalog is
|
||||
returned as an empty array.
|
||||
heading: list-inbound-metadata-for-the-authenticated-user-returns-id-tag-remark-listen-protocol-and-port-for-remote-id-lookup-and-reconciliation
|
||||
- content: Uses the authenticated panel user’s inbound. WireGuard reads the
|
||||
current clients array or the legacy peers array. AmneziaWG reads
|
||||
clients. Peer pages preserve stored order and return the total peer
|
||||
count and absolute offset.
|
||||
heading: load-inbound-information-and-the-first-compatible-client-or-a-page-of-up-to-50-tunnel-peers
|
||||
- content: Returns newline-delimited InboundInfoPage objects from one stored
|
||||
snapshot. Each contains at most 50 peers. Export consumers must check
|
||||
offsets and the total before publishing a completed download.
|
||||
heading: stream-the-source-pages-for-a-wireguard-or-amneziawg-peer-export
|
||||
---
|
||||
|
||||
{/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */}
|
||||
@@ -241,7 +275,7 @@ export default function Layout(props) {
|
||||
return (
|
||||
<>
|
||||
{props.children}
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/trafficSnapshot","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/amneziawgKernelReadiness","method":"get"},{"path":"/panel/api/inbounds/allLinks","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/subSortIndex","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/inbounds/list","method":"get"},{"path":"/panel/api/inbounds/trafficSnapshot","method":"get"},{"path":"/panel/api/inbounds/list/slim","method":"get"},{"path":"/panel/api/inbounds/catalog","method":"get"},{"path":"/panel/api/inbounds/options","method":"get"},{"path":"/panel/api/inbounds/amneziawgKernelReadiness","method":"get"},{"path":"/panel/api/inbounds/allLinks","method":"get"},{"path":"/panel/api/inbounds/get/{id}","method":"get"},{"path":"/panel/api/inbounds/{id}/info","method":"get"},{"path":"/panel/api/inbounds/{id}/peerExport","method":"get"},{"path":"/panel/api/inbounds/add","method":"post"},{"path":"/panel/api/inbounds/del/{id}","method":"post"},{"path":"/panel/api/inbounds/bulkDel","method":"post"},{"path":"/panel/api/inbounds/update/{id}","method":"post"},{"path":"/panel/api/inbounds/setEnable/{id}","method":"post"},{"path":"/panel/api/inbounds/{id}/subSortIndex","method":"post"},{"path":"/panel/api/inbounds/{id}/resetTraffic","method":"post"},{"path":"/panel/api/inbounds/{id}/delAllClients","method":"post"},{"path":"/panel/api/inbounds/resetAllTraffics","method":"post"},{"path":"/panel/api/inbounds/import","method":"post"},{"path":"/panel/api/inbounds/pushClientTraffics","method":"post"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"get"},{"path":"/panel/api/inbounds/{id}/fallbacks","method":"post"}]} showTitle />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,10 @@ _openapi:
|
||||
title: List every configured node with its connection details, health, and last
|
||||
heartbeat patch.
|
||||
url: '#list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch'
|
||||
- depth: 2
|
||||
title: Read the local panel, unique fleet client counts and sampled remote host
|
||||
telemetry.
|
||||
url: '#read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry'
|
||||
- depth: 2
|
||||
title: This panel's node-auth CA certificate (public, PEM) to paste into a
|
||||
node's mTLS trust setting. Lazily mints the CA and the master client
|
||||
@@ -99,6 +103,9 @@ _openapi:
|
||||
- content: List every configured node with its connection details, health, and
|
||||
last heartbeat patch.
|
||||
id: list-every-configured-node-with-its-connection-details-health-and-last-heartbeat-patch
|
||||
- content: Read the local panel, unique fleet client counts and sampled remote
|
||||
host telemetry.
|
||||
id: read-the-local-panel-unique-fleet-client-counts-and-sampled-remote-host-telemetry
|
||||
- content: This panel's node-auth CA certificate (public, PEM) to paste into a
|
||||
node's mTLS trust setting. Lazily mints the CA and the master client
|
||||
cert on first call. Pair with setting tlsVerifyMode=mtls on the node.
|
||||
@@ -175,7 +182,7 @@ export default function Layout(props) {
|
||||
return (
|
||||
<>
|
||||
{props.children}
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/restartXray/{id}","method":"post"},{"path":"/panel/api/nodes/restartPanel/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
|
||||
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/nodes/list","method":"get"},{"path":"/panel/api/nodes/overview","method":"get"},{"path":"/panel/api/nodes/mtls/ca","method":"post"},{"path":"/panel/api/nodes/mtls/trustCA","method":"post"},{"path":"/panel/api/nodes/mtls/reloadClient","method":"post"},{"path":"/panel/api/nodes/get/{id}","method":"get"},{"path":"/panel/api/nodes/webCert/{id}","method":"get"},{"path":"/panel/api/nodes/add","method":"post"},{"path":"/panel/api/nodes/update/{id}","method":"post"},{"path":"/panel/api/nodes/del/{id}","method":"post"},{"path":"/panel/api/nodes/setEnable/{id}","method":"post"},{"path":"/panel/api/nodes/test","method":"post"},{"path":"/panel/api/nodes/certFingerprint","method":"post"},{"path":"/panel/api/nodes/inbounds","method":"post"},{"path":"/panel/api/nodes/probe/{id}","method":"post"},{"path":"/panel/api/nodes/restartXray/{id}","method":"post"},{"path":"/panel/api/nodes/restartPanel/{id}","method":"post"},{"path":"/panel/api/nodes/updatePanel","method":"post"},{"path":"/panel/api/nodes/history/{id}/{metric}/{bucket}","method":"get"}]} showTitle />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -41,7 +41,8 @@ docker compose --profile postgres up -d
|
||||
|
||||
## Migrate SQLite → PostgreSQL
|
||||
|
||||
Move an existing SQLite install to PostgreSQL with the built-in command:
|
||||
Stop the panel, then move the existing SQLite install to PostgreSQL with the
|
||||
built-in command:
|
||||
|
||||
```bash
|
||||
x-ui migrate-db --dsn "postgres://xui:password@127.0.0.1:5432/xui?sslmode=disable"
|
||||
@@ -62,3 +63,35 @@ systemctl restart x-ui
|
||||
|
||||
Whichever backend you use, back it up regularly — see
|
||||
[Backup & restore](/docs/operations/backup-restore).
|
||||
|
||||
## Maintenance locks
|
||||
|
||||
Stop the panel before running `x-ui migrate`. The command waits up to five
|
||||
seconds for the database maintenance lock and reports an error if another panel
|
||||
or CLI process still holds it. In-panel restore drains admitted node polls and
|
||||
queued database writes before switching their database, then resumes work once
|
||||
the restored data is ready.
|
||||
|
||||
PostgreSQL uses advisory lock key `0x3378756964626d74` within the database. The
|
||||
panel uses a dedicated session named `3x-ui-maintenance`. A connection proxy
|
||||
must preserve PostgreSQL sessions for this DSN. After losing the shared runtime
|
||||
session, the panel keeps Xray running and pauses database work until it reacquires
|
||||
the advisory lock. An interrupted exclusive operation is canceled and must
|
||||
restart under a new lease. Its executing connection holds a separate advisory
|
||||
fence so another installation cannot enter while those writes could still commit.
|
||||
|
||||
If an interrupted PostgreSQL restore still needs data migration, startup retries
|
||||
that migration before serving requests. Cooperating installations share the
|
||||
recovery state in `xui_maintenance.restore_pending` in the target database.
|
||||
The first restore creates this schema, which needs database-level `CREATE`
|
||||
permission. Panel backups and restores exclude it. To recover after an
|
||||
interruption, restart the panel or run `x-ui migrate` while the panel is stopped,
|
||||
using the original application schema. Archive restore uses `pg_restore` and
|
||||
`psql` from a client package with the
|
||||
[restricted-mode security fix](https://www.postgresql.org/support/security/CVE-2026-18408/).
|
||||
It stages the decoded SQL in the system temporary directory before applying it
|
||||
in one transaction.
|
||||
|
||||
SQLite uses `.maintenance-lock` and `.maintenance-intent` beside the resolved
|
||||
database file. These paths stay the same while a restore replaces a symlink
|
||||
target. Leave the lock files in place while the panel or any CLI process is running.
|
||||
|
||||
@@ -8,7 +8,7 @@ icon: ChartNoAxesCombined
|
||||
|
||||
## انتخاب بازهٔ نمودار
|
||||
|
||||
هر نمودار نمای کلی یک سلکت بازهٔ زمانی در گوشهٔ بالای سمت راست دارد. مقدار پیشفرض **2m** است. گزینهها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. تغییر بازه در هر نمودار، بازهٔ همهٔ نمودارهای نمای کلی را تغییر میدهد.
|
||||
از گزینهٔ **بازهٔ زمانی** کنار **شاخصهای Xray** برای تغییر بازهٔ همهٔ نمودارهای نمای کلی استفاده کنید. گزینهها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. مقدار پیشفرض **2m** است. مرورگر انتخاب شما را برای این پنل پس از بارگیری مجدد صفحه و راهاندازی دوبارهٔ پنل حفظ میکند.
|
||||
|
||||
تعداد نقطههای نمودار حداکثر ۶۰ نقطه است. بازههای کوتاهتر از نمونههای دقیقتر و بازههای بلندتر از میانگین نمونهها استفاده میکنند. در بازهٔ **2m** نمودارها زندهاند: هر بار دریافت وضعیت، یعنی هر ۲ ثانیه، یک نقطه اضافه میکند. بازههای بلندتر از تاریخچهٔ ذخیرهشده در سرور خوانده میشوند و بهازای هر نقطه یک بار، و حداکثر دقیقهای یک بار، بهروزرسانی میشوند.
|
||||
|
||||
|
||||
+1340
-34
File diff suppressed because it is too large
Load Diff
Generated
+16
-4
@@ -11,10 +11,11 @@
|
||||
"@ant-design/icons": "^6.3.4",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@hookform/resolvers": "^7.0.9",
|
||||
"@hookform/resolvers": "^7.0.10",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@tanstack/react-query": "^5.108.4",
|
||||
"@tanstack/react-query-devtools": "^5.108.4",
|
||||
"@zip.js/zip.js": "2.25.1",
|
||||
"antd": "^6.7.2",
|
||||
"codemirror": "^6.0.2",
|
||||
"dayjs": "^1.11.23",
|
||||
@@ -1103,9 +1104,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@hookform/resolvers": {
|
||||
"version": "7.0.9",
|
||||
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.9.tgz",
|
||||
"integrity": "sha512-Ir3c/wEDz3+bryCwavOP4i930LIAqBugJalnipVZnAR5zC2yGieRMHVLs1D5PxzJBwCmQB4WVAvNlo5HJMa2WQ==",
|
||||
"version": "7.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.10.tgz",
|
||||
"integrity": "sha512-3SXIeYbLXTCSdYak7+YOxt7iu74fEkGH2IiDv+eJsFESghUzl07ntvGRV9AdFh+BGDPXfUaJYp7gnIVlYY9uag==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/utils": "^0.3.0"
|
||||
@@ -6307,6 +6308,17 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zip.js/zip.js": {
|
||||
"version": "2.25.1",
|
||||
"resolved": "https://registry.npmjs.org/@zip.js/zip.js/-/zip.js-2.25.1.tgz",
|
||||
"integrity": "sha512-/ZRBU5LNmnmj/4SGnvSmYe5UMavqeOg4MvfoMhAr0CRQGpRITwOJ8QD+9ppCIEkuzXJVDz0pIc8ZHCXoKCio1Q==",
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"bun": ">=0.7.0",
|
||||
"deno": ">=1.0.0",
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.19.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
|
||||
|
||||
@@ -38,10 +38,11 @@
|
||||
"@ant-design/icons": "^6.3.4",
|
||||
"@codemirror/lang-json": "^6.0.2",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@hookform/resolvers": "^7.0.9",
|
||||
"@hookform/resolvers": "^7.0.10",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@tanstack/react-query": "^5.108.4",
|
||||
"@tanstack/react-query-devtools": "^5.108.4",
|
||||
"@zip.js/zip.js": "2.25.1",
|
||||
"antd": "^6.7.2",
|
||||
"codemirror": "^6.0.2",
|
||||
"dayjs": "^1.11.23",
|
||||
|
||||
+1340
-34
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { withBasePath } from '@/api/http-init';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { GroupClientPageSchema, type GroupClientSelection } from '@/generated/zod';
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
|
||||
const PAGE_ENDPOINT = '/panel/api/clients/groups/clientPage';
|
||||
export const GROUP_CLIENT_PAGE_SIZE = 100;
|
||||
export const MAX_GROUP_EXCLUSIONS = 1000;
|
||||
|
||||
export type { GroupClientSelection };
|
||||
export type GroupClientMode = 'add' | 'remove' | 'links';
|
||||
export type GroupBulkScope = { group: string; scopeToken?: string };
|
||||
|
||||
type PageParams = {
|
||||
group: string;
|
||||
mode: GroupClientMode;
|
||||
page?: number;
|
||||
search?: string;
|
||||
freeze?: boolean;
|
||||
scopeSearch?: string;
|
||||
maxId?: number;
|
||||
};
|
||||
|
||||
export async function fetchGroupClients(params: PageParams, signal?: AbortSignal) {
|
||||
const response = await HttpUtil.get(PAGE_ENDPOINT, params, { signal, silent: true });
|
||||
const result = parseMsg(response, GroupClientPageSchema, 'clients/groups/clientPage');
|
||||
if (!result.success || !result.obj) throw new Error(result.msg);
|
||||
return result.obj;
|
||||
}
|
||||
|
||||
export function useGroupClientPage(params: PageParams, enabled: boolean) {
|
||||
return useQuery({
|
||||
queryKey: [...keys.clients.root(), 'groupClientPage', params],
|
||||
queryFn: ({ signal }) => fetchGroupClients(params, signal),
|
||||
enabled,
|
||||
gcTime: 0,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
export function groupSubscriptionExportPath(group: string) {
|
||||
return withBasePath(
|
||||
'/panel/api/clients/groups/subLinks/export?' + new URLSearchParams({ group }).toString(),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
import { withBasePath } from '@/api/http-init';
|
||||
import { InboundDetailSchema } from '@/schemas/inbound';
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
|
||||
export const INBOUND_PEER_PAGE_SIZE = 50;
|
||||
export const InboundInfoPageSchema = z.object({
|
||||
inbound: InboundDetailSchema,
|
||||
totalPeers: z.number().int().nonnegative(),
|
||||
peerOffset: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
export async function fetchInboundInfo(id: number, page: number, signal: AbortSignal) {
|
||||
const response = await HttpUtil.get(
|
||||
`/panel/api/inbounds/${id}/info`,
|
||||
{ page },
|
||||
{ signal, silent: true },
|
||||
);
|
||||
const result = parseMsg(response, InboundInfoPageSchema, 'inbounds/info');
|
||||
if (!result.success || !result.obj) throw new Error(result.msg);
|
||||
return result.obj;
|
||||
}
|
||||
|
||||
export function inboundPeerExportPath(id: number) {
|
||||
return withBasePath(`/panel/api/inbounds/${id}/peerExport`);
|
||||
}
|
||||
@@ -1,33 +1,49 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { z } from 'zod';
|
||||
import { skipToken, useQuery } from '@tanstack/react-query';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { ClientRecordSchema, type ClientRecord } from '@/schemas/client';
|
||||
import { ClientEmailSuggestionsSchema } from '@/generated/zod';
|
||||
|
||||
const ClientRecordListSchema = z
|
||||
.array(ClientRecordSchema)
|
||||
.nullable()
|
||||
.transform((value) => value ?? []);
|
||||
const suggestionsSchema = ClientEmailSuggestionsSchema.extend({
|
||||
emails: ClientEmailSuggestionsSchema.shape.emails.max(50),
|
||||
});
|
||||
|
||||
async function fetchClients(): Promise<ClientRecord[]> {
|
||||
const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true });
|
||||
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients');
|
||||
const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list');
|
||||
return validated.obj ?? [];
|
||||
}
|
||||
|
||||
export function useClientOptions(enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: keys.clients.all(),
|
||||
queryFn: fetchClients,
|
||||
enabled,
|
||||
staleTime: 30_000,
|
||||
select: (clients) =>
|
||||
clients
|
||||
.map((client) => client.email.trim())
|
||||
.filter(Boolean)
|
||||
.sort((a, b) => a.localeCompare(b)),
|
||||
function waitForTyping(signal: AbortSignal) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
signal.throwIfAborted();
|
||||
function cancel() {
|
||||
clearTimeout(timer);
|
||||
reject(signal.reason);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', cancel);
|
||||
resolve();
|
||||
}, 250);
|
||||
signal.addEventListener('abort', cancel, { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchClientOptions(search: string, signal: AbortSignal): Promise<string[]> {
|
||||
if (search) await waitForTyping(signal);
|
||||
const msg = await HttpUtil.get(
|
||||
'/panel/api/clients/userSuggestions',
|
||||
{ search },
|
||||
{ signal, silent: true },
|
||||
);
|
||||
if (!msg.success || msg.obj == null)
|
||||
throw new Error(msg.msg || 'Failed to load user suggestions');
|
||||
return (
|
||||
parseMsg(msg, suggestionsSchema, 'clients/userSuggestions', { strict: true }).obj?.emails ?? []
|
||||
);
|
||||
}
|
||||
|
||||
export function useClientOptions(search: string | null) {
|
||||
return useQuery({
|
||||
queryKey: keys.clients.userSuggestions(search),
|
||||
queryFn: search === null ? skipToken : ({ signal }) => fetchClientOptions(search, signal),
|
||||
staleTime: 30_000,
|
||||
gcTime: 60_000,
|
||||
retry: false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3,12 +3,39 @@ import { useMemo } from 'react';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
import { NodeListSchema } from '@/schemas/node';
|
||||
import { NodeListSchema, NodeOverviewSchema } from '@/schemas/node';
|
||||
import type { NodeRecord } from '@/schemas/node';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
|
||||
export type { NodeRecord };
|
||||
|
||||
async function fetchNodeOverview() {
|
||||
const msg = await HttpUtil.get('/panel/api/nodes/overview', undefined, { silent: true });
|
||||
if (!msg.success || msg.obj == null) throw new Error(msg.msg || 'Failed to fetch node overview');
|
||||
return NodeOverviewSchema.parse(msg.obj);
|
||||
}
|
||||
|
||||
const emptyNodes: NodeRecord[] = [];
|
||||
|
||||
export function useNodeOverviewQuery() {
|
||||
const query = useQuery({
|
||||
queryKey: keys.nodes.overview(),
|
||||
queryFn: fetchNodeOverview,
|
||||
refetchInterval: 5_000,
|
||||
});
|
||||
return {
|
||||
nodes: query.data?.nodes ?? emptyNodes,
|
||||
master: query.data?.master,
|
||||
fleet: query.data?.fleet,
|
||||
nodesUpdatedAt: query.dataUpdatedAt,
|
||||
loading: query.isFetching,
|
||||
fetched: query.data !== undefined || query.isError,
|
||||
fetchError: query.isLoadingError ? query.error.message : '',
|
||||
refreshError: query.isRefetchError ? query.error.message : '',
|
||||
refetch: query.refetch,
|
||||
};
|
||||
}
|
||||
|
||||
export interface NodeTotals {
|
||||
total: number;
|
||||
online: number;
|
||||
|
||||
@@ -8,6 +8,7 @@ export const keys = {
|
||||
nodes: {
|
||||
root: () => ['nodes'] as const,
|
||||
list: () => ['nodes', 'list'] as const,
|
||||
overview: () => ['nodes', 'overview'] as const,
|
||||
},
|
||||
hosts: {
|
||||
root: () => ['hosts'] as const,
|
||||
@@ -36,6 +37,7 @@ export const keys = {
|
||||
root: () => ['clients'] as const,
|
||||
list: (params: unknown) => ['clients', 'list', params] as const,
|
||||
all: () => ['clients', 'all'] as const,
|
||||
userSuggestions: (search: string | null) => ['clients', 'userSuggestions', search] as const,
|
||||
onlines: () => ['clients', 'onlines'] as const,
|
||||
onlinesByGuid: () => ['clients', 'onlinesByGuid'] as const,
|
||||
activeInbounds: () => ['clients', 'activeInbounds'] as const,
|
||||
|
||||
@@ -517,7 +517,8 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"status": "pending"
|
||||
}
|
||||
],
|
||||
"skipped": []
|
||||
"skipped": [],
|
||||
"skippedCount": 0
|
||||
},
|
||||
"BulkAttachResult": {
|
||||
"attached": [
|
||||
@@ -578,7 +579,8 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"email": "",
|
||||
"reason": ""
|
||||
}
|
||||
]
|
||||
],
|
||||
"skippedCount": 0
|
||||
},
|
||||
"BulkDetachResult": {
|
||||
"detached": [
|
||||
@@ -688,6 +690,12 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"oldValue": "10737418240",
|
||||
"source": "panel"
|
||||
},
|
||||
"ClientEmailSuggestions": {
|
||||
"emails": [
|
||||
"alice@example.com",
|
||||
"bob@example.com"
|
||||
]
|
||||
},
|
||||
"ClientInbound": {
|
||||
"clientId": 0,
|
||||
"createdAt": 0,
|
||||
@@ -941,6 +949,43 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"onlineCount": 1,
|
||||
"total": 2000
|
||||
},
|
||||
"DetachCandidate": {
|
||||
"comment": "",
|
||||
"email": "",
|
||||
"enable": false,
|
||||
"id": 0,
|
||||
"inScope": false
|
||||
},
|
||||
"DetachCandidatePage": {
|
||||
"attached": 0,
|
||||
"items": [
|
||||
{
|
||||
"comment": "",
|
||||
"email": "",
|
||||
"enable": false,
|
||||
"id": 0,
|
||||
"inScope": false
|
||||
}
|
||||
],
|
||||
"total": 0
|
||||
},
|
||||
"DetachJobStatus": {
|
||||
"error": "",
|
||||
"processed": 0,
|
||||
"result": null,
|
||||
"running": false,
|
||||
"total": 0
|
||||
},
|
||||
"DetachScopeSummary": {
|
||||
"scopeToken": "",
|
||||
"total": 0
|
||||
},
|
||||
"DetachSelectionResult": {
|
||||
"detached": 0,
|
||||
"errors": 0,
|
||||
"nodePending": false,
|
||||
"skipped": 0
|
||||
},
|
||||
"ExternalLinkInput": {
|
||||
"enable": true,
|
||||
"expiryTime": 0,
|
||||
@@ -1001,6 +1046,42 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"reason": "categoryMissing",
|
||||
"token": "geosite:blabla"
|
||||
},
|
||||
"GroupClientPage": {
|
||||
"items": [
|
||||
{
|
||||
"comment": "Example client",
|
||||
"email": "alice",
|
||||
"enable": true,
|
||||
"group": "staff",
|
||||
"id": 1,
|
||||
"inScope": true,
|
||||
"subId": "example-sub-id"
|
||||
}
|
||||
],
|
||||
"maxId": 0,
|
||||
"scopeToken": "",
|
||||
"total": 120
|
||||
},
|
||||
"GroupClientRow": {
|
||||
"comment": "Example client",
|
||||
"email": "alice",
|
||||
"enable": true,
|
||||
"group": "staff",
|
||||
"id": 1,
|
||||
"inScope": true,
|
||||
"subId": "example-sub-id"
|
||||
},
|
||||
"GroupClientSelection": {
|
||||
"clientIds": [
|
||||
0
|
||||
],
|
||||
"excludedClientIds": [
|
||||
0
|
||||
],
|
||||
"mode": "allMatching",
|
||||
"scopeToken": "",
|
||||
"search": ""
|
||||
},
|
||||
"HappLinkResult": {
|
||||
"encryptedLink": "happ://crypt5/example"
|
||||
},
|
||||
@@ -1185,6 +1266,11 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"sortOrder": 0,
|
||||
"xver": 0
|
||||
},
|
||||
"InboundInfoPage": {
|
||||
"inbound": null,
|
||||
"peerOffset": 50,
|
||||
"totalPeers": 120
|
||||
},
|
||||
"InboundOption": {
|
||||
"awgServer": null,
|
||||
"enable": true,
|
||||
@@ -1297,6 +1383,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"remark": "",
|
||||
"scheme": "https",
|
||||
"status": "online",
|
||||
"telemetry": null,
|
||||
"tlsVerifyMode": "verify",
|
||||
"transitive": false,
|
||||
"unavailableMetrics": [
|
||||
@@ -1324,11 +1411,34 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"total": 10737418240,
|
||||
"up": 1048576
|
||||
},
|
||||
"NodeFleetCounts": {
|
||||
"activeCount": 90,
|
||||
"clientCount": 100,
|
||||
"depletedCount": 2,
|
||||
"disabledCount": 8,
|
||||
"inboundCount": 8,
|
||||
"onlineCount": 20
|
||||
},
|
||||
"NodeInboundTraffic": {
|
||||
"down": 0,
|
||||
"id": 1,
|
||||
"up": 0
|
||||
},
|
||||
"NodeMasterView": {
|
||||
"counts": {
|
||||
"activeCount": 90,
|
||||
"clientCount": 100,
|
||||
"depletedCount": 2,
|
||||
"disabledCount": 8,
|
||||
"inboundCount": 8,
|
||||
"onlineCount": 20
|
||||
},
|
||||
"panelVersion": "v3.12.0",
|
||||
"telemetry": null,
|
||||
"xrayError": "",
|
||||
"xrayState": "running",
|
||||
"xrayVersion": "26.1.1"
|
||||
},
|
||||
"NodeMutationRequest": {
|
||||
"address": "",
|
||||
"allowPrivateAddress": false,
|
||||
@@ -1349,6 +1459,34 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"scheme": "http",
|
||||
"tlsVerifyMode": "verify"
|
||||
},
|
||||
"NodeOverview": {
|
||||
"fleet": {
|
||||
"activeCount": 90,
|
||||
"clientCount": 100,
|
||||
"depletedCount": 2,
|
||||
"disabledCount": 8,
|
||||
"inboundCount": 8,
|
||||
"onlineCount": 20
|
||||
},
|
||||
"master": {
|
||||
"counts": {
|
||||
"activeCount": 90,
|
||||
"clientCount": 100,
|
||||
"depletedCount": 2,
|
||||
"disabledCount": 8,
|
||||
"inboundCount": 8,
|
||||
"onlineCount": 20
|
||||
},
|
||||
"panelVersion": "v3.12.0",
|
||||
"telemetry": null,
|
||||
"xrayError": "",
|
||||
"xrayState": "running",
|
||||
"xrayVersion": "26.1.1"
|
||||
},
|
||||
"nodes": [
|
||||
null
|
||||
]
|
||||
},
|
||||
"NodeSnapshotAttachment": {
|
||||
"email": "user1",
|
||||
"inboundId": 1
|
||||
@@ -1364,6 +1502,25 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
null
|
||||
]
|
||||
},
|
||||
"NodeTelemetry": {
|
||||
"cpuPct": 12.5,
|
||||
"load1": 0.25,
|
||||
"load15": 0.12,
|
||||
"load5": 0.18,
|
||||
"logicalCores": 8,
|
||||
"memAvailableBytes": 1073741824,
|
||||
"memTotalBytes": 4294967296,
|
||||
"memUsedBytes": 2147483648,
|
||||
"netDown": 2048,
|
||||
"netUp": 1024,
|
||||
"physicalCores": 4,
|
||||
"resourceScope": "container",
|
||||
"sampleAgeMillis": 125,
|
||||
"sampledAt": 1700000000000,
|
||||
"tcpCount": 75,
|
||||
"udpCount": 12,
|
||||
"uptimeSecs": 3600
|
||||
},
|
||||
"NodeTrafficSnapshotV1": {
|
||||
"activeInboundTree": {},
|
||||
"clients": [
|
||||
@@ -1439,6 +1596,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"remark": "Primary edge",
|
||||
"scheme": "https",
|
||||
"status": "online",
|
||||
"telemetry": null,
|
||||
"tlsVerifyMode": "verify",
|
||||
"transitive": false,
|
||||
"unavailableMetrics": [
|
||||
@@ -1567,6 +1725,14 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
],
|
||||
"target": "old.example.com:443"
|
||||
},
|
||||
"RemoteInboundOption": {
|
||||
"id": 7,
|
||||
"listen": "127.0.0.1",
|
||||
"port": 443,
|
||||
"protocol": "vless",
|
||||
"remark": "VLESS-443",
|
||||
"tag": "in-443"
|
||||
},
|
||||
"ServerSettings": {
|
||||
"contentPaddingAddition": "",
|
||||
"disableCookies": false,
|
||||
@@ -1666,6 +1832,7 @@ export const EXAMPLES: Record<string, unknown> = {
|
||||
"panelVersion": "",
|
||||
"publicIP": null,
|
||||
"resourceScope": "",
|
||||
"sampleAgeMillis": 125,
|
||||
"swap": null,
|
||||
"tcpCount": 0,
|
||||
"udpCount": 0,
|
||||
|
||||
@@ -2104,6 +2104,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"$ref": "#/components/schemas/BulkAdjustReport"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"skippedCount": {
|
||||
"example": 0,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -2229,6 +2233,10 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"$ref": "#/components/schemas/BulkDeleteReport"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"skippedCount": {
|
||||
"example": 0,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -2585,6 +2593,24 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ClientEmailSuggestions": {
|
||||
"properties": {
|
||||
"emails": {
|
||||
"example": [
|
||||
"alice@example.com",
|
||||
"bob@example.com"
|
||||
],
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"emails"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ClientInbound": {
|
||||
"properties": {
|
||||
"clientId": {
|
||||
@@ -3380,6 +3406,124 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"DetachCandidate": {
|
||||
"properties": {
|
||||
"comment": {
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"type": "string"
|
||||
},
|
||||
"enable": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"inScope": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"comment",
|
||||
"email",
|
||||
"enable",
|
||||
"id",
|
||||
"inScope"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"DetachCandidatePage": {
|
||||
"properties": {
|
||||
"attached": {
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/DetachCandidate"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"total": {
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"attached",
|
||||
"items",
|
||||
"total"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"DetachJobStatus": {
|
||||
"properties": {
|
||||
"error": {
|
||||
"type": "string"
|
||||
},
|
||||
"processed": {
|
||||
"type": "integer"
|
||||
},
|
||||
"result": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/DetachSelectionResult"
|
||||
}
|
||||
],
|
||||
"nullable": true
|
||||
},
|
||||
"running": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"total": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"processed",
|
||||
"running",
|
||||
"total"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"DetachScopeSummary": {
|
||||
"properties": {
|
||||
"scopeToken": {
|
||||
"type": "string"
|
||||
},
|
||||
"total": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"scopeToken",
|
||||
"total"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"DetachSelectionResult": {
|
||||
"properties": {
|
||||
"detached": {
|
||||
"type": "integer"
|
||||
},
|
||||
"errors": {
|
||||
"type": "integer"
|
||||
},
|
||||
"nodePending": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"skipped": {
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"detached",
|
||||
"errors",
|
||||
"skipped"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ExternalLinkInput": {
|
||||
"description": "ExternalLinkInput is one row from the client form's Links tab.",
|
||||
"properties": {
|
||||
@@ -3580,6 +3724,104 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"GroupClientPage": {
|
||||
"properties": {
|
||||
"items": {
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/GroupClientRow"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"maxId": {
|
||||
"type": "integer"
|
||||
},
|
||||
"scopeToken": {
|
||||
"type": "string"
|
||||
},
|
||||
"total": {
|
||||
"example": 120,
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"items",
|
||||
"total"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"GroupClientRow": {
|
||||
"properties": {
|
||||
"comment": {
|
||||
"example": "Example client",
|
||||
"type": "string"
|
||||
},
|
||||
"email": {
|
||||
"example": "alice",
|
||||
"type": "string"
|
||||
},
|
||||
"enable": {
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"group": {
|
||||
"example": "staff",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"example": 1,
|
||||
"type": "integer"
|
||||
},
|
||||
"inScope": {
|
||||
"example": true,
|
||||
"type": "boolean"
|
||||
},
|
||||
"subId": {
|
||||
"example": "example-sub-id",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"comment",
|
||||
"email",
|
||||
"enable",
|
||||
"group",
|
||||
"id",
|
||||
"inScope",
|
||||
"subId"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"GroupClientSelection": {
|
||||
"properties": {
|
||||
"clientIds": {
|
||||
"items": {
|
||||
"type": "integer"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"excludedClientIds": {
|
||||
"items": {
|
||||
"type": "integer"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
"mode": {
|
||||
"example": "allMatching",
|
||||
"type": "string"
|
||||
},
|
||||
"scopeToken": {
|
||||
"type": "string"
|
||||
},
|
||||
"search": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mode"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"HappLinkResult": {
|
||||
"properties": {
|
||||
"encryptedLink": {
|
||||
@@ -4272,6 +4514,31 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"InboundInfoPage": {
|
||||
"properties": {
|
||||
"inbound": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/Inbound"
|
||||
}
|
||||
],
|
||||
"nullable": true
|
||||
},
|
||||
"peerOffset": {
|
||||
"example": 50,
|
||||
"type": "integer"
|
||||
},
|
||||
"totalPeers": {
|
||||
"example": 120,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"peerOffset",
|
||||
"totalPeers"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"InboundOption": {
|
||||
"properties": {
|
||||
"awgServer": {
|
||||
@@ -4729,6 +4996,14 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"example": "online",
|
||||
"type": "string"
|
||||
},
|
||||
"telemetry": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/NodeTelemetry"
|
||||
}
|
||||
],
|
||||
"nullable": true
|
||||
},
|
||||
"tlsVerifyMode": {
|
||||
"enum": [
|
||||
"verify",
|
||||
@@ -4890,6 +5165,43 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeFleetCounts": {
|
||||
"properties": {
|
||||
"activeCount": {
|
||||
"example": 90,
|
||||
"type": "integer"
|
||||
},
|
||||
"clientCount": {
|
||||
"example": 100,
|
||||
"type": "integer"
|
||||
},
|
||||
"depletedCount": {
|
||||
"example": 2,
|
||||
"type": "integer"
|
||||
},
|
||||
"disabledCount": {
|
||||
"example": 8,
|
||||
"type": "integer"
|
||||
},
|
||||
"inboundCount": {
|
||||
"example": 8,
|
||||
"type": "integer"
|
||||
},
|
||||
"onlineCount": {
|
||||
"example": 20,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"activeCount",
|
||||
"clientCount",
|
||||
"depletedCount",
|
||||
"disabledCount",
|
||||
"inboundCount",
|
||||
"onlineCount"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeInboundTraffic": {
|
||||
"properties": {
|
||||
"down": {
|
||||
@@ -4912,6 +5224,40 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeMasterView": {
|
||||
"properties": {
|
||||
"counts": {
|
||||
"$ref": "#/components/schemas/NodeFleetCounts"
|
||||
},
|
||||
"panelVersion": {
|
||||
"example": "v3.12.0",
|
||||
"type": "string"
|
||||
},
|
||||
"telemetry": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/NodeTelemetry"
|
||||
}
|
||||
],
|
||||
"nullable": true
|
||||
},
|
||||
"xrayError": {
|
||||
"type": "string"
|
||||
},
|
||||
"xrayState": {
|
||||
"example": "running",
|
||||
"type": "string"
|
||||
},
|
||||
"xrayVersion": {
|
||||
"example": "26.1.1",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"counts"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeMutationRequest": {
|
||||
"description": "NodeMutationRequest is the node write/probe contract. ApiToken is accepted\nonly as input. On update, nil means keep the stored token; replacement and\nclearing are explicit and mutually exclusive.",
|
||||
"properties": {
|
||||
@@ -5002,6 +5348,33 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeOverview": {
|
||||
"properties": {
|
||||
"fleet": {
|
||||
"$ref": "#/components/schemas/NodeFleetCounts"
|
||||
},
|
||||
"master": {
|
||||
"$ref": "#/components/schemas/NodeMasterView"
|
||||
},
|
||||
"nodes": {
|
||||
"items": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/NodeView"
|
||||
}
|
||||
],
|
||||
"nullable": true
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"fleet",
|
||||
"master",
|
||||
"nodes"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeSnapshotAttachment": {
|
||||
"properties": {
|
||||
"email": {
|
||||
@@ -5045,6 +5418,106 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeTelemetry": {
|
||||
"description": "NodeTelemetry describes one host sample. Nil metrics were not measured.",
|
||||
"properties": {
|
||||
"cpuPct": {
|
||||
"example": 12.5,
|
||||
"nullable": true,
|
||||
"type": "number"
|
||||
},
|
||||
"load1": {
|
||||
"example": 0.25,
|
||||
"nullable": true,
|
||||
"type": "number"
|
||||
},
|
||||
"load15": {
|
||||
"example": 0.12,
|
||||
"nullable": true,
|
||||
"type": "number"
|
||||
},
|
||||
"load5": {
|
||||
"example": 0.18,
|
||||
"nullable": true,
|
||||
"type": "number"
|
||||
},
|
||||
"logicalCores": {
|
||||
"example": 8,
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"memAvailableBytes": {
|
||||
"example": 1073741824,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"memTotalBytes": {
|
||||
"example": 4294967296,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"memUsedBytes": {
|
||||
"example": 2147483648,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"netDown": {
|
||||
"example": 2048,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"netUp": {
|
||||
"example": 1024,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"physicalCores": {
|
||||
"example": 4,
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"resourceScope": {
|
||||
"example": "container",
|
||||
"type": "string"
|
||||
},
|
||||
"sampleAgeMillis": {
|
||||
"example": 125,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"sampledAt": {
|
||||
"example": 1700000000000,
|
||||
"format": "int64",
|
||||
"type": "integer"
|
||||
},
|
||||
"tcpCount": {
|
||||
"example": 75,
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"udpCount": {
|
||||
"example": 12,
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"uptimeSecs": {
|
||||
"example": 3600,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"sampledAt"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"NodeTrafficSnapshotV1": {
|
||||
"description": "NodeTrafficSnapshotV1 carries complete counters every tick; only unchanged structure is omitted.",
|
||||
"properties": {
|
||||
@@ -5276,6 +5749,14 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"example": "online",
|
||||
"type": "string"
|
||||
},
|
||||
"telemetry": {
|
||||
"allOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/NodeTelemetry"
|
||||
}
|
||||
],
|
||||
"nullable": true
|
||||
},
|
||||
"tlsVerifyMode": {
|
||||
"example": "verify",
|
||||
"type": "string"
|
||||
@@ -5841,6 +6322,43 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"RemoteInboundOption": {
|
||||
"properties": {
|
||||
"id": {
|
||||
"example": 7,
|
||||
"type": "integer"
|
||||
},
|
||||
"listen": {
|
||||
"example": "127.0.0.1",
|
||||
"type": "string"
|
||||
},
|
||||
"port": {
|
||||
"example": 443,
|
||||
"type": "integer"
|
||||
},
|
||||
"protocol": {
|
||||
"example": "vless",
|
||||
"type": "string"
|
||||
},
|
||||
"remark": {
|
||||
"example": "VLESS-443",
|
||||
"type": "string"
|
||||
},
|
||||
"tag": {
|
||||
"example": "in-443",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"listen",
|
||||
"port",
|
||||
"protocol",
|
||||
"remark",
|
||||
"tag"
|
||||
],
|
||||
"type": "object"
|
||||
},
|
||||
"ServerSettings": {
|
||||
"description": "ServerSettings is the \"server\" block of an AmneziaWG inbound's Settings\nJSON: the interface-level configuration shared by every client/peer. The\nlisten port is deliberately not duplicated here — it lives on the inbound\nrow itself (Inbound.Port), like every other protocol.",
|
||||
"properties": {
|
||||
@@ -6142,6 +6660,12 @@ export const SCHEMAS: Record<string, unknown> = {
|
||||
"resourceScope": {
|
||||
"type": "string"
|
||||
},
|
||||
"sampleAgeMillis": {
|
||||
"example": 125,
|
||||
"format": "int64",
|
||||
"nullable": true,
|
||||
"type": "integer"
|
||||
},
|
||||
"swap": {},
|
||||
"tcpCount": {
|
||||
"type": "integer"
|
||||
|
||||
@@ -502,6 +502,7 @@ export interface BulkAdjustResult {
|
||||
nodePending?: boolean;
|
||||
nodeResults?: ClientNodeApplyOutcome[];
|
||||
skipped?: BulkAdjustReport[];
|
||||
skippedCount?: number;
|
||||
}
|
||||
|
||||
export interface BulkAttachResult {
|
||||
@@ -534,6 +535,7 @@ export interface BulkDeleteResult {
|
||||
nodePending?: boolean;
|
||||
nodeResults?: ClientNodeApplyOutcome[];
|
||||
skipped?: BulkDeleteReport[];
|
||||
skippedCount?: number;
|
||||
}
|
||||
|
||||
export interface BulkDetachResult {
|
||||
@@ -610,6 +612,10 @@ export interface ClientChangeLog {
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface ClientEmailSuggestions {
|
||||
emails: string[];
|
||||
}
|
||||
|
||||
export interface ClientInbound {
|
||||
clientId: number;
|
||||
createdAt: number;
|
||||
@@ -782,6 +788,40 @@ export interface ClientsSummary {
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DetachCandidate {
|
||||
comment: string;
|
||||
email: string;
|
||||
enable: boolean;
|
||||
id: number;
|
||||
inScope: boolean;
|
||||
}
|
||||
|
||||
export interface DetachCandidatePage {
|
||||
attached: number;
|
||||
items: DetachCandidate[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DetachJobStatus {
|
||||
error?: string;
|
||||
processed: number;
|
||||
result?: DetachSelectionResult | null;
|
||||
running: boolean;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DetachScopeSummary {
|
||||
scopeToken: string;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface DetachSelectionResult {
|
||||
detached: number;
|
||||
errors: number;
|
||||
nodePending?: boolean;
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
export interface ExternalLinkInput {
|
||||
enable?: boolean | null;
|
||||
expiryTime?: number;
|
||||
@@ -833,6 +873,31 @@ export interface GeodataTokenIssue {
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface GroupClientPage {
|
||||
items: GroupClientRow[];
|
||||
maxId?: number;
|
||||
scopeToken?: string;
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface GroupClientRow {
|
||||
comment: string;
|
||||
email: string;
|
||||
enable: boolean;
|
||||
group: string;
|
||||
id: number;
|
||||
inScope: boolean;
|
||||
subId: string;
|
||||
}
|
||||
|
||||
export interface GroupClientSelection {
|
||||
clientIds?: number[];
|
||||
excludedClientIds?: number[];
|
||||
mode: string;
|
||||
scopeToken?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
export interface HappLinkResult {
|
||||
encryptedLink: string;
|
||||
}
|
||||
@@ -977,6 +1042,12 @@ export interface InboundFallback {
|
||||
xver: number;
|
||||
}
|
||||
|
||||
export interface InboundInfoPage {
|
||||
inbound?: Inbound | null;
|
||||
peerOffset: number;
|
||||
totalPeers: number;
|
||||
}
|
||||
|
||||
export interface InboundOption {
|
||||
awgServer?: ServerSettings | null;
|
||||
enable: boolean;
|
||||
@@ -1092,6 +1163,7 @@ export interface Node {
|
||||
remark: string;
|
||||
scheme: string;
|
||||
status: string;
|
||||
telemetry?: NodeTelemetry | null;
|
||||
tlsVerifyMode: string;
|
||||
transitive?: boolean;
|
||||
unavailableMetrics?: string[];
|
||||
@@ -1119,12 +1191,30 @@ export interface NodeClientTraffic {
|
||||
up: number;
|
||||
}
|
||||
|
||||
export interface NodeFleetCounts {
|
||||
activeCount: number;
|
||||
clientCount: number;
|
||||
depletedCount: number;
|
||||
disabledCount: number;
|
||||
inboundCount: number;
|
||||
onlineCount: number;
|
||||
}
|
||||
|
||||
export interface NodeInboundTraffic {
|
||||
down: number;
|
||||
id: number;
|
||||
up: number;
|
||||
}
|
||||
|
||||
export interface NodeMasterView {
|
||||
counts: NodeFleetCounts;
|
||||
panelVersion?: string;
|
||||
telemetry?: NodeTelemetry | null;
|
||||
xrayError?: string;
|
||||
xrayState?: string;
|
||||
xrayVersion?: string;
|
||||
}
|
||||
|
||||
export interface NodeMutationRequest {
|
||||
address: string;
|
||||
allowPrivateAddress: boolean;
|
||||
@@ -1144,6 +1234,12 @@ export interface NodeMutationRequest {
|
||||
tlsVerifyMode: string;
|
||||
}
|
||||
|
||||
export interface NodeOverview {
|
||||
fleet: NodeFleetCounts;
|
||||
master: NodeMasterView;
|
||||
nodes: NodeView | null[];
|
||||
}
|
||||
|
||||
export interface NodeSnapshotAttachment {
|
||||
email: string;
|
||||
inboundId: number;
|
||||
@@ -1154,6 +1250,26 @@ export interface NodeSnapshotStructure {
|
||||
inbounds: Inbound | null[];
|
||||
}
|
||||
|
||||
export interface NodeTelemetry {
|
||||
cpuPct?: number | null;
|
||||
load1?: number | null;
|
||||
load15?: number | null;
|
||||
load5?: number | null;
|
||||
logicalCores?: number | null;
|
||||
memAvailableBytes?: number | null;
|
||||
memTotalBytes?: number | null;
|
||||
memUsedBytes?: number | null;
|
||||
netDown?: number | null;
|
||||
netUp?: number | null;
|
||||
physicalCores?: number | null;
|
||||
resourceScope?: string;
|
||||
sampleAgeMillis?: number | null;
|
||||
sampledAt: number;
|
||||
tcpCount?: number | null;
|
||||
udpCount?: number | null;
|
||||
uptimeSecs?: number | null;
|
||||
}
|
||||
|
||||
export interface NodeTrafficSnapshotV1 {
|
||||
activeInboundTree: Record<string, string[]>;
|
||||
clients: NodeClientTraffic[];
|
||||
@@ -1203,6 +1319,7 @@ export interface NodeView {
|
||||
remark: string;
|
||||
scheme: string;
|
||||
status: string;
|
||||
telemetry?: NodeTelemetry | null;
|
||||
tlsVerifyMode: string;
|
||||
transitive?: boolean;
|
||||
unavailableMetrics?: string[];
|
||||
@@ -1318,6 +1435,15 @@ export interface RealityWatchStatus {
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface RemoteInboundOption {
|
||||
id: number;
|
||||
listen: string;
|
||||
port: number;
|
||||
protocol: Protocol;
|
||||
remark: string;
|
||||
tag: string;
|
||||
}
|
||||
|
||||
export interface ServerSettings {
|
||||
contentPaddingAddition?: string;
|
||||
disableCookies: boolean;
|
||||
@@ -1402,6 +1528,7 @@ export interface Status {
|
||||
panelVersion: string;
|
||||
publicIP: unknown;
|
||||
resourceScope?: string;
|
||||
sampleAgeMillis?: number | null;
|
||||
swap: unknown;
|
||||
tcpCount: number;
|
||||
udpCount: number;
|
||||
|
||||
@@ -525,6 +525,7 @@ export const BulkAdjustResultSchema = z.object({
|
||||
nodePending: z.boolean().optional(),
|
||||
nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(),
|
||||
skipped: z.array(z.lazy(() => BulkAdjustReportSchema)).optional(),
|
||||
skippedCount: z.number().int().optional(),
|
||||
});
|
||||
export type BulkAdjustResult = z.infer<typeof BulkAdjustResultSchema>;
|
||||
|
||||
@@ -562,6 +563,7 @@ export const BulkDeleteResultSchema = z.object({
|
||||
nodePending: z.boolean().optional(),
|
||||
nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(),
|
||||
skipped: z.array(z.lazy(() => BulkDeleteReportSchema)).optional(),
|
||||
skippedCount: z.number().int().optional(),
|
||||
});
|
||||
export type BulkDeleteResult = z.infer<typeof BulkDeleteResultSchema>;
|
||||
|
||||
@@ -645,6 +647,11 @@ export const ClientChangeLogSchema = z.object({
|
||||
});
|
||||
export type ClientChangeLog = z.infer<typeof ClientChangeLogSchema>;
|
||||
|
||||
export const ClientEmailSuggestionsSchema = z.object({
|
||||
emails: z.array(z.string()),
|
||||
});
|
||||
export type ClientEmailSuggestions = z.infer<typeof ClientEmailSuggestionsSchema>;
|
||||
|
||||
export const ClientInboundSchema = z.object({
|
||||
clientId: z.number().int(),
|
||||
createdAt: z.number().int(),
|
||||
@@ -831,6 +838,45 @@ export const ClientsSummarySchema = z.object({
|
||||
});
|
||||
export type ClientsSummary = z.infer<typeof ClientsSummarySchema>;
|
||||
|
||||
export const DetachCandidateSchema = z.object({
|
||||
comment: z.string(),
|
||||
email: z.string(),
|
||||
enable: z.boolean(),
|
||||
id: z.number().int(),
|
||||
inScope: z.boolean(),
|
||||
});
|
||||
export type DetachCandidate = z.infer<typeof DetachCandidateSchema>;
|
||||
|
||||
export const DetachCandidatePageSchema = z.object({
|
||||
attached: z.number().int(),
|
||||
items: z.array(z.lazy(() => DetachCandidateSchema)),
|
||||
total: z.number().int(),
|
||||
});
|
||||
export type DetachCandidatePage = z.infer<typeof DetachCandidatePageSchema>;
|
||||
|
||||
export const DetachJobStatusSchema = z.object({
|
||||
error: z.string().optional(),
|
||||
processed: z.number().int(),
|
||||
result: z.lazy(() => DetachSelectionResultSchema).nullable().optional(),
|
||||
running: z.boolean(),
|
||||
total: z.number().int(),
|
||||
});
|
||||
export type DetachJobStatus = z.infer<typeof DetachJobStatusSchema>;
|
||||
|
||||
export const DetachScopeSummarySchema = z.object({
|
||||
scopeToken: z.string(),
|
||||
total: z.number().int(),
|
||||
});
|
||||
export type DetachScopeSummary = z.infer<typeof DetachScopeSummarySchema>;
|
||||
|
||||
export const DetachSelectionResultSchema = z.object({
|
||||
detached: z.number().int(),
|
||||
errors: z.number().int(),
|
||||
nodePending: z.boolean().optional(),
|
||||
skipped: z.number().int(),
|
||||
});
|
||||
export type DetachSelectionResult = z.infer<typeof DetachSelectionResultSchema>;
|
||||
|
||||
export const ExternalLinkInputSchema = z.object({
|
||||
enable: z.boolean().nullable().optional(),
|
||||
expiryTime: z.number().int().optional(),
|
||||
@@ -890,6 +936,34 @@ export const GeodataTokenIssueSchema = z.object({
|
||||
});
|
||||
export type GeodataTokenIssue = z.infer<typeof GeodataTokenIssueSchema>;
|
||||
|
||||
export const GroupClientPageSchema = z.object({
|
||||
items: z.array(z.lazy(() => GroupClientRowSchema)),
|
||||
maxId: z.number().int().optional(),
|
||||
scopeToken: z.string().optional(),
|
||||
total: z.number().int(),
|
||||
});
|
||||
export type GroupClientPage = z.infer<typeof GroupClientPageSchema>;
|
||||
|
||||
export const GroupClientRowSchema = z.object({
|
||||
comment: z.string(),
|
||||
email: z.string(),
|
||||
enable: z.boolean(),
|
||||
group: z.string(),
|
||||
id: z.number().int(),
|
||||
inScope: z.boolean(),
|
||||
subId: z.string(),
|
||||
});
|
||||
export type GroupClientRow = z.infer<typeof GroupClientRowSchema>;
|
||||
|
||||
export const GroupClientSelectionSchema = z.object({
|
||||
clientIds: z.array(z.number().int()).optional(),
|
||||
excludedClientIds: z.array(z.number().int()).optional(),
|
||||
mode: z.string(),
|
||||
scopeToken: z.string().optional(),
|
||||
search: z.string().optional(),
|
||||
});
|
||||
export type GroupClientSelection = z.infer<typeof GroupClientSelectionSchema>;
|
||||
|
||||
export const HappLinkResultSchema = z.object({
|
||||
encryptedLink: z.string(),
|
||||
});
|
||||
@@ -1042,6 +1116,13 @@ export const InboundFallbackSchema = z.object({
|
||||
});
|
||||
export type InboundFallback = z.infer<typeof InboundFallbackSchema>;
|
||||
|
||||
export const InboundInfoPageSchema = z.object({
|
||||
inbound: z.lazy(() => InboundSchema).nullable().optional(),
|
||||
peerOffset: z.number().int(),
|
||||
totalPeers: z.number().int(),
|
||||
});
|
||||
export type InboundInfoPage = z.infer<typeof InboundInfoPageSchema>;
|
||||
|
||||
export const InboundOptionSchema = z.object({
|
||||
awgServer: z.lazy(() => ServerSettingsSchema).nullable().optional(),
|
||||
enable: z.boolean(),
|
||||
@@ -1167,6 +1248,7 @@ export const NodeSchema = z.object({
|
||||
remark: z.string(),
|
||||
scheme: z.enum(['http', 'https']),
|
||||
status: z.string(),
|
||||
telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(),
|
||||
tlsVerifyMode: z.enum(['verify', 'skip', 'pin', 'mtls']),
|
||||
transitive: z.boolean().optional(),
|
||||
unavailableMetrics: z.array(z.string()).optional(),
|
||||
@@ -1196,6 +1278,16 @@ export const NodeClientTrafficSchema = z.object({
|
||||
});
|
||||
export type NodeClientTraffic = z.infer<typeof NodeClientTrafficSchema>;
|
||||
|
||||
export const NodeFleetCountsSchema = z.object({
|
||||
activeCount: z.number().int(),
|
||||
clientCount: z.number().int(),
|
||||
depletedCount: z.number().int(),
|
||||
disabledCount: z.number().int(),
|
||||
inboundCount: z.number().int(),
|
||||
onlineCount: z.number().int(),
|
||||
});
|
||||
export type NodeFleetCounts = z.infer<typeof NodeFleetCountsSchema>;
|
||||
|
||||
export const NodeInboundTrafficSchema = z.object({
|
||||
down: z.number().int(),
|
||||
id: z.number().int(),
|
||||
@@ -1203,6 +1295,16 @@ export const NodeInboundTrafficSchema = z.object({
|
||||
});
|
||||
export type NodeInboundTraffic = z.infer<typeof NodeInboundTrafficSchema>;
|
||||
|
||||
export const NodeMasterViewSchema = z.object({
|
||||
counts: z.lazy(() => NodeFleetCountsSchema),
|
||||
panelVersion: z.string().optional(),
|
||||
telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(),
|
||||
xrayError: z.string().optional(),
|
||||
xrayState: z.string().optional(),
|
||||
xrayVersion: z.string().optional(),
|
||||
});
|
||||
export type NodeMasterView = z.infer<typeof NodeMasterViewSchema>;
|
||||
|
||||
export const NodeMutationRequestSchema = z.object({
|
||||
address: z.string(),
|
||||
allowPrivateAddress: z.boolean(),
|
||||
@@ -1223,6 +1325,13 @@ export const NodeMutationRequestSchema = z.object({
|
||||
});
|
||||
export type NodeMutationRequest = z.infer<typeof NodeMutationRequestSchema>;
|
||||
|
||||
export const NodeOverviewSchema = z.object({
|
||||
fleet: z.lazy(() => NodeFleetCountsSchema),
|
||||
master: z.lazy(() => NodeMasterViewSchema),
|
||||
nodes: z.array(z.lazy(() => NodeViewSchema).nullable()),
|
||||
});
|
||||
export type NodeOverview = z.infer<typeof NodeOverviewSchema>;
|
||||
|
||||
export const NodeSnapshotAttachmentSchema = z.object({
|
||||
email: z.string(),
|
||||
inboundId: z.number().int(),
|
||||
@@ -1235,6 +1344,27 @@ export const NodeSnapshotStructureSchema = z.object({
|
||||
});
|
||||
export type NodeSnapshotStructure = z.infer<typeof NodeSnapshotStructureSchema>;
|
||||
|
||||
export const NodeTelemetrySchema = z.object({
|
||||
cpuPct: z.number().nullable().optional(),
|
||||
load1: z.number().nullable().optional(),
|
||||
load15: z.number().nullable().optional(),
|
||||
load5: z.number().nullable().optional(),
|
||||
logicalCores: z.number().int().nullable().optional(),
|
||||
memAvailableBytes: z.number().int().nullable().optional(),
|
||||
memTotalBytes: z.number().int().nullable().optional(),
|
||||
memUsedBytes: z.number().int().nullable().optional(),
|
||||
netDown: z.number().int().nullable().optional(),
|
||||
netUp: z.number().int().nullable().optional(),
|
||||
physicalCores: z.number().int().nullable().optional(),
|
||||
resourceScope: z.string().optional(),
|
||||
sampleAgeMillis: z.number().int().nullable().optional(),
|
||||
sampledAt: z.number().int(),
|
||||
tcpCount: z.number().int().nullable().optional(),
|
||||
udpCount: z.number().int().nullable().optional(),
|
||||
uptimeSecs: z.number().int().nullable().optional(),
|
||||
});
|
||||
export type NodeTelemetry = z.infer<typeof NodeTelemetrySchema>;
|
||||
|
||||
export const NodeTrafficSnapshotV1Schema = z.object({
|
||||
activeInboundTree: z.record(z.string(), z.array(z.string())),
|
||||
clients: z.array(z.lazy(() => NodeClientTrafficSchema)),
|
||||
@@ -1285,6 +1415,7 @@ export const NodeViewSchema = z.object({
|
||||
remark: z.string(),
|
||||
scheme: z.string(),
|
||||
status: z.string(),
|
||||
telemetry: z.lazy(() => NodeTelemetrySchema).nullable().optional(),
|
||||
tlsVerifyMode: z.string(),
|
||||
transitive: z.boolean().optional(),
|
||||
unavailableMetrics: z.array(z.string()).optional(),
|
||||
@@ -1411,6 +1542,16 @@ export const RealityWatchStatusSchema = z.object({
|
||||
});
|
||||
export type RealityWatchStatus = z.infer<typeof RealityWatchStatusSchema>;
|
||||
|
||||
export const RemoteInboundOptionSchema = z.object({
|
||||
id: z.number().int(),
|
||||
listen: z.string(),
|
||||
port: z.number().int(),
|
||||
protocol: z.lazy(() => ProtocolSchema),
|
||||
remark: z.string(),
|
||||
tag: z.string(),
|
||||
});
|
||||
export type RemoteInboundOption = z.infer<typeof RemoteInboundOptionSchema>;
|
||||
|
||||
export const ServerSettingsSchema = z.object({
|
||||
contentPaddingAddition: z.string().optional(),
|
||||
disableCookies: z.boolean(),
|
||||
@@ -1499,6 +1640,7 @@ export const StatusSchema = z.object({
|
||||
panelVersion: z.string(),
|
||||
publicIP: z.unknown(),
|
||||
resourceScope: z.string().optional(),
|
||||
sampleAgeMillis: z.number().int().nullable().optional(),
|
||||
swap: z.unknown(),
|
||||
tcpCount: z.number().int(),
|
||||
udpCount: z.number().int(),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tansta
|
||||
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
import type { GroupBulkScope, GroupClientSelection } from '@/api/groupClients';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { clientManagementPath } from '@/api/client-management';
|
||||
import { markLocalInvalidate } from '@/api/invalidationTracker';
|
||||
@@ -357,15 +358,16 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
});
|
||||
|
||||
const bulkAddToGroupMut = useMutation({
|
||||
mutationFn: (body: { emails: string[]; group: string }) =>
|
||||
HttpUtil.post('/panel/api/clients/groups/bulkAdd', body, JSON_HEADERS),
|
||||
mutationFn: (
|
||||
body: ({ emails: string[] } | { selection: GroupClientSelection }) & { group: string },
|
||||
) => HttpUtil.post('/panel/api/clients/groups/bulkAdd', body, JSON_HEADERS),
|
||||
onSuccess: (msg) => {
|
||||
if (msg?.success) invalidateAll();
|
||||
},
|
||||
});
|
||||
|
||||
const bulkRemoveFromGroupMut = useMutation({
|
||||
mutationFn: (body: { emails: string[] }) =>
|
||||
mutationFn: (body: { emails: string[] } | { group: string; selection: GroupClientSelection }) =>
|
||||
HttpUtil.post('/panel/api/clients/groups/bulkRemove', body, JSON_HEADERS),
|
||||
onSuccess: (msg) => {
|
||||
if (msg?.success) invalidateAll();
|
||||
@@ -392,10 +394,9 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
});
|
||||
|
||||
const bulkDeleteMut = useMutation({
|
||||
mutationFn: async (payload: {
|
||||
emails: string[];
|
||||
keepTraffic?: boolean;
|
||||
}): Promise<Msg<BulkDeleteResult>> => {
|
||||
mutationFn: async (
|
||||
payload: ({ emails: string[] } | GroupBulkScope) & { keepTraffic?: boolean },
|
||||
): Promise<Msg<BulkDeleteResult>> => {
|
||||
const raw = await HttpUtil.post('/panel/api/clients/bulkDel', payload, JSON_HEADERS);
|
||||
return parseMsg(raw, BulkDeleteResultSchema, 'clients/bulkDel');
|
||||
},
|
||||
@@ -415,15 +416,16 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
});
|
||||
|
||||
const bulkAdjustMut = useMutation({
|
||||
mutationFn: async (payload: {
|
||||
emails: string[];
|
||||
addDays: number;
|
||||
addBytes: number;
|
||||
flow?: string;
|
||||
limitHwid?: number | null;
|
||||
adTag?: string;
|
||||
externalLinks?: ExternalLinkInput[];
|
||||
}): Promise<Msg<BulkAdjustResult>> => {
|
||||
mutationFn: async (
|
||||
payload: ({ emails: string[] } | GroupBulkScope) & {
|
||||
addDays: number;
|
||||
addBytes: number;
|
||||
flow?: string;
|
||||
limitHwid?: number | null;
|
||||
adTag?: string;
|
||||
externalLinks?: ExternalLinkInput[];
|
||||
},
|
||||
): Promise<Msg<BulkAdjustResult>> => {
|
||||
if (payload.externalLinks !== undefined) await ExternalLinksAppendSchema.parseAsync(payload);
|
||||
const raw = await HttpUtil.post('/panel/api/clients/bulkAdjust', payload, JSON_HEADERS);
|
||||
return parseMsg(raw, BulkAdjustResultSchema, 'clients/bulkAdjust');
|
||||
@@ -576,10 +578,13 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
[removeMut],
|
||||
);
|
||||
const bulkDelete = useCallback(
|
||||
(emails: string[], keepTraffic = false) => {
|
||||
if (!Array.isArray(emails) || emails.length === 0)
|
||||
(scope: string[] | GroupBulkScope, keepTraffic = false) => {
|
||||
if (Array.isArray(scope) && scope.length === 0)
|
||||
return Promise.resolve(null as unknown as Msg<BulkDeleteResult>);
|
||||
return bulkDeleteMut.mutateAsync({ emails, keepTraffic });
|
||||
return bulkDeleteMut.mutateAsync({
|
||||
...(Array.isArray(scope) ? { emails: scope } : scope),
|
||||
keepTraffic,
|
||||
});
|
||||
},
|
||||
[bulkDeleteMut],
|
||||
);
|
||||
@@ -593,7 +598,7 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
);
|
||||
const bulkAdjust = useCallback(
|
||||
(
|
||||
emails: string[],
|
||||
scope: string[] | GroupBulkScope,
|
||||
addDays: number,
|
||||
addBytes: number,
|
||||
flow = '',
|
||||
@@ -601,9 +606,9 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
adTag?: string,
|
||||
externalLinks?: ExternalLinkInput[],
|
||||
) => {
|
||||
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
||||
if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null);
|
||||
return bulkAdjustMut.mutateAsync({
|
||||
emails,
|
||||
...(Array.isArray(scope) ? { emails: scope } : scope),
|
||||
addDays,
|
||||
addBytes,
|
||||
flow,
|
||||
@@ -631,16 +636,19 @@ export function useClients(options: UseClientsOptions = {}) {
|
||||
[bulkSetEnableMut],
|
||||
);
|
||||
const bulkAddToGroup = useCallback(
|
||||
(emails: string[], group: string) => {
|
||||
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
||||
return bulkAddToGroupMut.mutateAsync({ emails, group });
|
||||
(scope: string[] | GroupClientSelection, group: string) => {
|
||||
if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null);
|
||||
return bulkAddToGroupMut.mutateAsync({
|
||||
...(Array.isArray(scope) ? { emails: scope } : { selection: scope }),
|
||||
group,
|
||||
});
|
||||
},
|
||||
[bulkAddToGroupMut],
|
||||
);
|
||||
const bulkRemoveFromGroup = useCallback(
|
||||
(emails: string[]) => {
|
||||
if (!Array.isArray(emails) || emails.length === 0) return Promise.resolve(null);
|
||||
return bulkRemoveFromGroupMut.mutateAsync({ emails });
|
||||
(scope: string[] | { group: string; selection: GroupClientSelection }) => {
|
||||
if (Array.isArray(scope) && scope.length === 0) return Promise.resolve(null);
|
||||
return bulkRemoveFromGroupMut.mutateAsync(Array.isArray(scope) ? { emails: scope } : scope);
|
||||
},
|
||||
[bulkRemoveFromGroupMut],
|
||||
);
|
||||
|
||||
@@ -1019,9 +1019,19 @@ export interface GenWireguardLinkInput {
|
||||
port: number;
|
||||
remark?: string;
|
||||
peerIndex: number;
|
||||
serverPublicKey?: string;
|
||||
finalmask?: FinalMaskStreamSettings;
|
||||
}
|
||||
|
||||
export function wireguardServerPublicKey(secretKey: unknown): string {
|
||||
if (typeof secretKey !== 'string' || !secretKey) return '';
|
||||
try {
|
||||
return Wireguard.generateKeypair(secretKey).publicKey;
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// Wireguard share link: wireguard://<peerPrivKey>@<host>:<port>
|
||||
// ?publickey=<serverPub>&address=<peerAllowedIP>&mtu=<mtu>#<remark>
|
||||
// pubKey is derived from the server's secretKey via Wireguard.generateKeypair
|
||||
@@ -1035,10 +1045,9 @@ export function genWireguardLink(input: GenWireguardLinkInput): string {
|
||||
const url = new URL(`wireguard://${formatUrlHost(address)}:${port}`);
|
||||
url.username = peer.privateKey ?? '';
|
||||
|
||||
const pubKey =
|
||||
settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
|
||||
const pubKey = input.serverPublicKey ?? wireguardServerPublicKey(settings.secretKey);
|
||||
if (pubKey.length > 0) url.searchParams.set('publickey', pubKey);
|
||||
if (peer.allowedIPs.length > 0) {
|
||||
if (Array.isArray(peer.allowedIPs) && peer.allowedIPs.length > 0) {
|
||||
url.searchParams.set('address', peer.allowedIPs.join(','));
|
||||
}
|
||||
if (typeof settings.mtu === 'number' && settings.mtu > 0) {
|
||||
@@ -1061,13 +1070,12 @@ export function genWireguardConfig(input: GenWireguardLinkInput): string {
|
||||
const peer = settings.peers[peerIndex];
|
||||
if (!peer) return '';
|
||||
|
||||
const pubKey =
|
||||
settings.secretKey.length > 0 ? Wireguard.generateKeypair(settings.secretKey).publicKey : '';
|
||||
const pubKey = input.serverPublicKey ?? wireguardServerPublicKey(settings.secretKey);
|
||||
|
||||
const lines = [
|
||||
'[Interface]',
|
||||
`PrivateKey = ${peer.privateKey ?? ''}`,
|
||||
`Address = ${peer.allowedIPs.join(', ')}`,
|
||||
`Address = ${Array.isArray(peer.allowedIPs) ? peer.allowedIPs.join(', ') : ''}`,
|
||||
`DNS = ${settings.dns || '1.1.1.1, 1.0.0.1'}`,
|
||||
];
|
||||
if (typeof settings.mtu === 'number' && settings.mtu > 0) {
|
||||
@@ -1096,7 +1104,7 @@ export interface GenAmneziaWGLinkInput {
|
||||
}
|
||||
|
||||
function amneziaWGHLine(key: string, value: string | undefined, fallback: string): string {
|
||||
return `${key} = ${value && value.trim() !== '' ? value : fallback}`;
|
||||
return `${key} = ${typeof value === 'string' && value.trim() !== '' ? value : fallback}`;
|
||||
}
|
||||
|
||||
// Base64url (RFC 4648 §5), no padding — matches the real AmneziaVPN app's
|
||||
@@ -1132,13 +1140,16 @@ export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
|
||||
const client = settings.clients[peerIndex];
|
||||
if (!client) return '';
|
||||
const server = settings.server;
|
||||
if (!server || typeof server !== 'object') return '';
|
||||
|
||||
const lines = [
|
||||
'[Interface]',
|
||||
`PrivateKey = ${client.privateKey ?? ''}`,
|
||||
`Address = ${(client.allowedIPs ?? []).join(', ')}`,
|
||||
`Address = ${Array.isArray(client.allowedIPs) ? client.allowedIPs.join(', ') : ''}`,
|
||||
];
|
||||
const dns = [server.primaryDns, server.secondaryDns].filter((v) => !!v && v.trim() !== '');
|
||||
const dns = [server.primaryDns, server.secondaryDns].filter(
|
||||
(v) => typeof v === 'string' && v.trim() !== '',
|
||||
);
|
||||
if (dns.length > 0) lines.push(`DNS = ${dns.join(', ')}`);
|
||||
lines.push(`MTU = ${effectiveMtu(server.mtu, server.s4)}`);
|
||||
lines.push(`Jc = ${server.jc}`, `Jmin = ${server.jmin}`, `Jmax = ${server.jmax}`);
|
||||
@@ -1162,7 +1173,7 @@ export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
|
||||
['MaxHandshakeAttempts', server.maxHandshakeAttempts],
|
||||
];
|
||||
for (const [key, value] of optional31) {
|
||||
if (value && value.trim() !== '') lines.push(`${key} = ${value}`);
|
||||
if (typeof value === 'string' && value.trim() !== '') lines.push(`${key} = ${value}`);
|
||||
}
|
||||
if (server.randomTrailers) lines.push('RandomTrailers = on');
|
||||
if (server.disableCookies) lines.push('DisableCookies = on');
|
||||
@@ -1186,6 +1197,7 @@ export function genAmneziaWGConfig(input: GenAmneziaWGLinkInput): string {
|
||||
export interface GenAmneziaWGFanoutInput {
|
||||
inbound: Inbound;
|
||||
remark?: string;
|
||||
peerOffset?: number;
|
||||
hostOverride?: string;
|
||||
fallbackHostname: string;
|
||||
}
|
||||
@@ -1194,7 +1206,7 @@ function amneziaWGFanout(
|
||||
input: GenAmneziaWGFanoutInput,
|
||||
render: (input: GenAmneziaWGLinkInput) => string,
|
||||
): string[][] {
|
||||
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
|
||||
const { inbound, remark = '', peerOffset = 0, hostOverride = '', fallbackHostname } = input;
|
||||
if (inbound.protocol !== 'amneziawg') return [];
|
||||
const endpoints = tunnelEndpoints(inbound, resolveAddr(inbound, hostOverride, fallbackHostname));
|
||||
const settings = inbound.settings as AmneziawgInboundSettings;
|
||||
@@ -1205,7 +1217,7 @@ function amneziaWGFanout(
|
||||
settings,
|
||||
address: e.address,
|
||||
port: e.port,
|
||||
remark: tunnelPeerRemark(remark, e.remark, i, c),
|
||||
remark: tunnelPeerRemark(remark, e.remark, peerOffset + i, c),
|
||||
peerIndex: i,
|
||||
}),
|
||||
),
|
||||
@@ -1680,6 +1692,7 @@ export function genInboundLinks(input: GenInboundLinksInput): string {
|
||||
export interface GenWireguardFanoutInput {
|
||||
inbound: Inbound;
|
||||
remark?: string;
|
||||
peerOffset?: number;
|
||||
hostOverride?: string;
|
||||
fallbackHostname: string;
|
||||
}
|
||||
@@ -1694,7 +1707,7 @@ function wgRenderPeers(settings: WireguardInboundSettings): WireguardInboundPeer
|
||||
if (clients.length > 0) {
|
||||
return clients.map((c) => ({ ...c, publicKey: c.publicKey ?? '' }));
|
||||
}
|
||||
return settings.peers;
|
||||
return settings.peers ?? [];
|
||||
}
|
||||
|
||||
// Hosts reach wireguard/amneziawg as externalProxy entries (withHostEndpoints);
|
||||
@@ -1724,21 +1737,23 @@ function wireguardFanout(
|
||||
input: GenWireguardFanoutInput,
|
||||
render: (input: GenWireguardLinkInput) => string,
|
||||
): string[][] {
|
||||
const { inbound, remark = '', hostOverride = '', fallbackHostname } = input;
|
||||
const { inbound, remark = '', peerOffset = 0, hostOverride = '', fallbackHostname } = input;
|
||||
if (inbound.protocol !== 'wireguard') return [];
|
||||
const endpoints = tunnelEndpoints(inbound, resolveAddr(inbound, hostOverride, fallbackHostname));
|
||||
const baseSettings = inbound.settings as WireguardInboundSettings;
|
||||
const peers = wgRenderPeers(baseSettings);
|
||||
const settings: WireguardInboundSettings = { ...baseSettings, peers };
|
||||
const serverPublicKey = wireguardServerPublicKey(settings.secretKey);
|
||||
return peers.map((p, i) =>
|
||||
endpoints.map((e) =>
|
||||
render({
|
||||
settings,
|
||||
address: e.address,
|
||||
port: e.port,
|
||||
remark: tunnelPeerRemark(remark, e.remark, i, p),
|
||||
remark: tunnelPeerRemark(remark, e.remark, peerOffset + i, p),
|
||||
peerIndex: i,
|
||||
finalmask: inbound.streamSettings?.finalmask,
|
||||
serverPublicKey,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -303,6 +303,16 @@ export const sections: readonly Section[] = [
|
||||
response:
|
||||
'{\n "success": true,\n "obj": [\n {\n "id": 1,\n "remark": "VLESS-443",\n "settings": {\n "clients": [\n { "email": "alice", "enable": true }\n ],\n "decryption": "none"\n },\n "clientStats": []\n }\n ]\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/inbounds/catalog',
|
||||
summary:
|
||||
'List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.',
|
||||
description:
|
||||
'Available to panel sessions, admin, node-admin, and node-sync tokens. The catalog queries only metadata columns. An empty catalog is returned as an empty array.',
|
||||
responseSchema: 'RemoteInboundOption',
|
||||
responseSchemaArray: true,
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/inbounds/options',
|
||||
@@ -333,6 +343,34 @@ export const sections: readonly Section[] = [
|
||||
summary: 'Fetch a single inbound by numeric ID.',
|
||||
params: [{ name: 'id', in: 'path', type: 'number', desc: 'Inbound ID.' }],
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/inbounds/:id/info',
|
||||
summary:
|
||||
'Load inbound information and the first compatible client or a page of up to 50 tunnel peers.',
|
||||
description:
|
||||
'Uses the authenticated panel user’s inbound. WireGuard reads the current clients array or the legacy peers array. AmneziaWG reads clients. Peer pages preserve stored order and return the total peer count and absolute offset.',
|
||||
params: [
|
||||
{ name: 'id', in: 'path', type: 'integer', desc: 'Inbound ID.' },
|
||||
{ name: 'page', in: 'query', type: 'integer', optional: true, defaultValue: 1 },
|
||||
],
|
||||
responseSchema: 'InboundInfoPage',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/inbounds/:id/peerExport',
|
||||
summary: 'Stream the source pages for a WireGuard or AmneziaWG peer export.',
|
||||
description:
|
||||
'Returns newline-delimited InboundInfoPage objects from one stored snapshot. Each contains at most 50 peers. Export consumers must check offsets and the total before publishing a completed download.',
|
||||
params: [{ name: 'id', in: 'path', type: 'integer', desc: 'Inbound ID.' }],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Ordered peer pages from one inbound snapshot.',
|
||||
content: { 'application/x-ndjson': { schema: { type: 'string' } } },
|
||||
},
|
||||
'400': { description: 'Invalid inbound or no tunnel peers available for export.' },
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/inbounds/add',
|
||||
@@ -1113,6 +1151,21 @@ export const sections: readonly Section[] = [
|
||||
],
|
||||
responseSchema: 'AttachCandidatePage',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/userSuggestions',
|
||||
summary: 'Return up to 50 client emails for the routing rule user picker.',
|
||||
params: [
|
||||
{
|
||||
name: 'search',
|
||||
in: 'query',
|
||||
type: 'string',
|
||||
desc: 'Optional case-insensitive substring. Percent and underscore are literal.',
|
||||
optional: true,
|
||||
},
|
||||
],
|
||||
responseSchema: 'ClientEmailSuggestions',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/list/paged',
|
||||
@@ -1650,14 +1703,18 @@ export const sections: readonly Section[] = [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/bulkAdjust',
|
||||
description: bulkClientNodeApplyDescription,
|
||||
summary:
|
||||
'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: "none" clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound supports it (omit or "" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel ("none" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.',
|
||||
description:
|
||||
bulkClientNodeApplyDescription +
|
||||
' Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients are checked before their first write. If a client changes groups after its first commit, the adjustment continues for the same client identity. Group responses include skippedCount and at most 20 representative skip records.',
|
||||
requestSchema: {
|
||||
type: 'object',
|
||||
required: ['emails'],
|
||||
oneOf: [{ required: ['emails'] }, { required: ['group'] }],
|
||||
properties: {
|
||||
emails: { type: 'array', items: { type: 'string' }, minItems: 1 },
|
||||
group: { type: 'string', minLength: 1 },
|
||||
scopeToken: { type: 'string' },
|
||||
addDays: { type: 'integer' },
|
||||
addBytes: { type: 'integer' },
|
||||
flow: { type: 'string' },
|
||||
@@ -1716,10 +1773,22 @@ export const sections: readonly Section[] = [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/bulkDel',
|
||||
description: bulkClientNodeApplyDescription,
|
||||
summary:
|
||||
'Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.',
|
||||
body: '{\n "emails": ["alice", "bob"],\n "keepTraffic": false\n}',
|
||||
'Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters.',
|
||||
description:
|
||||
bulkClientNodeApplyDescription +
|
||||
' For group deletion, an unfiltered remove scopeToken from clientPage rejects stale membership before planning. Clients that leave the scope during the operation are skipped. Group responses include skippedCount and at most 20 representative skip records.',
|
||||
requestSchema: {
|
||||
type: 'object',
|
||||
oneOf: [{ required: ['emails'] }, { required: ['group'] }],
|
||||
properties: {
|
||||
emails: { type: 'array', items: { type: 'string' } },
|
||||
group: { type: 'string', minLength: 1 },
|
||||
scopeToken: { type: 'string' },
|
||||
keepTraffic: { type: 'boolean' },
|
||||
},
|
||||
},
|
||||
body: JSON.stringify({ emails: ['alice', 'bob'], keepTraffic: false }, null, 2),
|
||||
responseSchema: 'BulkDeleteResult',
|
||||
},
|
||||
{
|
||||
@@ -1727,23 +1796,92 @@ export const sections: readonly Section[] = [
|
||||
path: '/panel/api/clients/bulkCreate',
|
||||
description: bulkClientNodeApplyDescription,
|
||||
summary:
|
||||
'Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.',
|
||||
body: '[\n {\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 2,\n "enable": true\n },\n "inboundIds": [7]\n },\n {\n "client": {\n "email": "bob@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [7, 9]\n }\n]',
|
||||
'Create many clients in one call. Use subIdPrefix to generate a subscription ID with an independent cryptographically random suffix. Omit client.subId or leave it empty on that item. The result includes per-email skip reasons.',
|
||||
requestSchema: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
required: ['client', 'inboundIds'],
|
||||
properties: {
|
||||
client: {
|
||||
type: 'object',
|
||||
required: ['email'],
|
||||
properties: {
|
||||
email: { type: 'string' },
|
||||
subId: { type: 'string' },
|
||||
totalGB: { type: 'integer' },
|
||||
expiryTime: { type: 'integer' },
|
||||
limitHwid: { type: 'integer' },
|
||||
enable: { type: 'boolean' },
|
||||
},
|
||||
},
|
||||
inboundIds: { type: 'array', items: { type: 'integer' } },
|
||||
subIdPrefix: {
|
||||
type: 'string',
|
||||
description: 'Optional readable prefix. The panel adds a random suffix.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
body: JSON.stringify(
|
||||
[
|
||||
{
|
||||
client: { email: 'alice@example.com', totalGB: 53687091200, limitHwid: 2 },
|
||||
inboundIds: [7],
|
||||
subIdPrefix: 'team',
|
||||
},
|
||||
{
|
||||
client: { email: 'bob@example.com', totalGB: 53687091200, limitHwid: 0 },
|
||||
inboundIds: [7, 9],
|
||||
subIdPrefix: 'team',
|
||||
},
|
||||
],
|
||||
null,
|
||||
2,
|
||||
),
|
||||
responseSchema: 'BulkCreateResult',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/groups/bulkAdd',
|
||||
summary:
|
||||
"Add many clients to a group in one call. Updates clients.group_name and patches the matching client entry inside every owning inbound's settings JSON in a single transaction. If the group name does not yet exist (in client_groups or as a derived label), it is auto-created as a persistent group. To clear the group label, use /groups/bulkRemove instead.",
|
||||
body: '{\n "emails": ["alice", "bob"],\n "group": "customer-a"\n}',
|
||||
"Move clients into a group and update every owning inbound's settings in the same transaction.",
|
||||
description:
|
||||
'Send one of emails, inboundId, or selection with the target group. Emails and inboundId can create the group. A picker selection targets an existing group and excludes current members. Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. A stale selection makes no changes.',
|
||||
requestSchema: {
|
||||
type: 'object',
|
||||
required: ['group'],
|
||||
oneOf: [
|
||||
{ required: ['emails'] },
|
||||
{ required: ['inboundId'] },
|
||||
{ required: ['selection'] },
|
||||
],
|
||||
properties: {
|
||||
group: { type: 'string', minLength: 1 },
|
||||
emails: { type: 'array', items: { type: 'string' } },
|
||||
inboundId: { type: 'integer', minimum: 1 },
|
||||
selection: { $ref: '#/components/schemas/GroupClientSelection' },
|
||||
},
|
||||
},
|
||||
body: JSON.stringify({ group: 'customer-a', inboundId: 7 }, null, 2),
|
||||
response: '{\n "success": true,\n "obj": {\n "affected": 2\n }\n}',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/groups/bulkRemove',
|
||||
summary:
|
||||
"Clear the group label on many clients in one call. Inverse of /groups/bulkAdd. Clients themselves are kept — only the group label is cleared from clients.group_name and from each owning inbound's settings JSON. Groups become empty if all their members are removed.",
|
||||
'Clear group membership and preserve the clients. Use either emails or a selection scoped to the named group.',
|
||||
description:
|
||||
'Explicit selections use clientIds. Frozen selections use scopeToken, the original search and up to 1,000 excludedClientIds. Only members of the selected group are eligible. A stale selection makes no changes.',
|
||||
requestSchema: {
|
||||
type: 'object',
|
||||
oneOf: [{ required: ['emails'] }, { required: ['group', 'selection'] }],
|
||||
properties: {
|
||||
group: { type: 'string', minLength: 1 },
|
||||
emails: { type: 'array', items: { type: 'string' } },
|
||||
selection: { $ref: '#/components/schemas/GroupClientSelection' },
|
||||
},
|
||||
},
|
||||
body: '{\n "emails": ["alice", "bob"]\n}',
|
||||
response: '{\n "success": true,\n "obj": {\n "affected": 2\n }\n}',
|
||||
},
|
||||
@@ -1793,18 +1931,72 @@ export const sections: readonly Section[] = [
|
||||
],
|
||||
responseSchema: 'AttachJobStatus',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/detachCandidates',
|
||||
summary:
|
||||
'Read up to 100 clients currently attached to one inbound. Search matches email or comment. The response includes filtered and attached totals, and marks candidates belonging to an optional frozen scope.',
|
||||
params: [
|
||||
{ name: 'inboundId', in: 'query', type: 'integer', desc: 'Source inbound ID.' },
|
||||
{
|
||||
name: 'page',
|
||||
in: 'query',
|
||||
type: 'integer',
|
||||
desc: '1-indexed page, defaults to 1.',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
name: 'search',
|
||||
in: 'query',
|
||||
type: 'string',
|
||||
desc: 'Email or comment substring.',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
name: 'scopeToken',
|
||||
in: 'query',
|
||||
type: 'string',
|
||||
desc: 'Token from the freeze endpoint.',
|
||||
optional: true,
|
||||
},
|
||||
],
|
||||
responseSchema: 'DetachCandidatePage',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/detachCandidates/freeze',
|
||||
summary:
|
||||
'Freeze up to 100,000 current memberships of one inbound and return their count and an opaque token. Search does not narrow this selection. Tokens expire after 15 minutes and are held in a bounded in-memory history.',
|
||||
body: '{\n "inboundId": 7\n}',
|
||||
responseSchema: 'DetachScopeSummary',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/bulkDetach',
|
||||
description: bulkClientNodeApplyDescription,
|
||||
summary:
|
||||
"Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.",
|
||||
'Detach client memberships while keeping records and traffic. Legacy email requests accept multiple inbounds and return detached/skipped/errors lists. Scoped requests take exactly one inbound and either explicit clientIds or a frozen allMatching scopeToken with excludedClientIds. Supply a requestId UUID and reuse it with the same payload when retrying. The scoped response is {jobId}. Poll GET /bulkDetach/:id for progress and counts. Changed memberships are skipped and newly attached clients stay outside a frozen scope.',
|
||||
params: [
|
||||
{
|
||||
name: 'emails',
|
||||
in: 'body (json)',
|
||||
type: 'string[]',
|
||||
desc: 'Emails of existing clients to detach.',
|
||||
desc: 'Emails of existing clients to detach. Use either emails or selection.',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
name: 'selection',
|
||||
in: 'body (json)',
|
||||
type: 'object',
|
||||
desc: 'Explicit IDs or a frozen scope with exclusions.',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
name: 'requestId',
|
||||
in: 'body (json)',
|
||||
type: 'string',
|
||||
desc: 'UUID required for scoped requests. Retries are idempotent while job history is retained.',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
name: 'inboundIds',
|
||||
@@ -1816,6 +2008,16 @@ export const sections: readonly Section[] = [
|
||||
body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}',
|
||||
responseSchema: 'BulkDetachResult',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/bulkDetach/:id',
|
||||
summary:
|
||||
'Poll a scoped detachment job. A completed result reports detached, skipped and failed client counts and whether node reconciliation is pending. Jobs are retained in a bounded in-memory history for up to 15 minutes after completion.',
|
||||
params: [
|
||||
{ name: 'id', in: 'path', type: 'string', desc: 'Job ID returned by bulkDetach.' },
|
||||
],
|
||||
responseSchema: 'DetachJobStatus',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/bulkResetTraffic',
|
||||
@@ -1841,6 +2043,38 @@ export const sections: readonly Section[] = [
|
||||
body: '{\n "hostGroupIds": ["cdn-front"]\n}',
|
||||
response: '{\n "success": true,\n "obj": {\n "hostGroupIds": ["cdn-front"]\n }\n}',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/groups/clientPage',
|
||||
summary:
|
||||
'Page through group candidates, members or subscription IDs. Pages are one-based with a fixed size of 100 and an exact total.',
|
||||
description:
|
||||
'Add mode excludes current members. Remove mode selects current members. Links mode selects members with a subscription ID. Search matches email, comment and group. freeze=true returns only the matching count, a scope token and the maximum ID for an add or remove selection. For subsequent pages, send maxId and scopeSearch to mark rows inside the frozen filter.',
|
||||
params: [
|
||||
{ name: 'group', in: 'query', type: 'string', desc: 'Group name.' },
|
||||
{ name: 'mode', in: 'query', type: 'string', enum: ['add', 'remove', 'links'] },
|
||||
{ name: 'page', in: 'query', type: 'integer', optional: true, defaultValue: 1 },
|
||||
{ name: 'search', in: 'query', type: 'string', optional: true },
|
||||
{ name: 'freeze', in: 'query', type: 'boolean', optional: true },
|
||||
{ name: 'scopeSearch', in: 'query', type: 'string', optional: true },
|
||||
{ name: 'maxId', in: 'query', type: 'integer', optional: true },
|
||||
],
|
||||
responseSchema: 'GroupClientPage',
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/groups/subLinks/export',
|
||||
summary:
|
||||
'Stream all subscription links for a group as tab-separated text. Each row has an email and regular link, followed by a JSON link when enabled.',
|
||||
params: [{ name: 'group', in: 'query', type: 'string', desc: 'Group name.' }],
|
||||
responses: {
|
||||
'200': {
|
||||
description: 'Complete subscription link export.',
|
||||
content: { 'text/plain': { schema: { type: 'string' } } },
|
||||
},
|
||||
'400': { description: 'Missing group or subscriptions disabled.' },
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/clients/groups/:name/emails',
|
||||
@@ -1964,7 +2198,7 @@ export const sections: readonly Section[] = [
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/onlinesByGuid',
|
||||
summary:
|
||||
'Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. Lets the inbounds page attribute online status to the real node instead of the intermediate one it syncs through.',
|
||||
'Online client emails grouped by the panelGuid of the node that physically hosts each client. The local panel uses its own GUID; each node (at any depth in a chain) uses its GUID. An empty list means the node reported no online clients. An absent GUID means there is no usable report.',
|
||||
response:
|
||||
'{\n "success": true,\n "obj": {\n "a1b2-...": ["user1"],\n "c3d4-...": ["user1", "user2"]\n }\n}',
|
||||
},
|
||||
@@ -1980,7 +2214,7 @@ export const sections: readonly Section[] = [
|
||||
method: 'POST',
|
||||
path: '/panel/api/clients/activeInbounds',
|
||||
summary:
|
||||
"Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Pairs with onlinesByGuid so the inbounds page only marks a multi-inbound client online on the inbounds it actually used. Nodes that do not report per-inbound activity are absent.",
|
||||
"Inbound tags that carried traffic within the heartbeat window, grouped by the hosting node's panelGuid. Use with onlinesByGuid to scope online counts. An empty list means no active tags, an absent GUID means there is no usable report, and null means a confirmed legacy node lacks the activity endpoint. The reserved NUL tag (U+0000) marks a partial report. Inbounds whose tags are absent remain unknown.",
|
||||
response:
|
||||
'{\n "success": true,\n "obj": {\n "a1b2-...": ["in-443-tcp", "in-8443-tcp"]\n }\n}',
|
||||
},
|
||||
@@ -2072,6 +2306,13 @@ export const sections: readonly Section[] = [
|
||||
responseSchema: 'NodeView',
|
||||
responseSchemaArray: true,
|
||||
},
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/panel/api/nodes/overview',
|
||||
summary:
|
||||
'Read the local panel, unique fleet client counts and sampled remote host telemetry.',
|
||||
responseSchema: 'NodeOverview',
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/panel/api/nodes/mtls/ca',
|
||||
|
||||
@@ -140,7 +140,12 @@ const trafficPayloadSchema = {
|
||||
},
|
||||
onlineClients: stringArray,
|
||||
onlineByGuid: stringArrayMap,
|
||||
activeInbounds: stringArrayMap,
|
||||
activeInbounds: {
|
||||
type: 'object',
|
||||
additionalProperties: { ...stringArray, nullable: true },
|
||||
description:
|
||||
'Empty lists mean no active tags, absent GUIDs mean no usable report, and null denotes legacy nodes without per-inbound activity. The reserved NUL tag (U+0000) marks a partial report. Unlisted inbounds stay unknown.',
|
||||
},
|
||||
lastOnlineMap: timestampMap,
|
||||
},
|
||||
oneOf: [
|
||||
|
||||
@@ -192,10 +192,12 @@ export default function ClientBulkAddModal({
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const subIdPrefix = emails.length > 1 ? current.subId : '';
|
||||
const payloads = emails.map((email) => ({
|
||||
subIdPrefix: subIdPrefix || undefined,
|
||||
client: {
|
||||
email,
|
||||
subId: current.subId || RandomUtil.randomLowerAndNum(16),
|
||||
subId: subIdPrefix ? '' : current.subId || RandomUtil.randomLowerAndNum(16),
|
||||
id: RandomUtil.randomUUID(),
|
||||
password: ss2022Method
|
||||
? RandomUtil.randomShadowsocksPassword(ss2022Method)
|
||||
@@ -219,11 +221,15 @@ export default function ClientBulkAddModal({
|
||||
inboundIds: current.inboundIds,
|
||||
}));
|
||||
const msg = await bulkCreate(payloads);
|
||||
if (!msg?.success) {
|
||||
messageApi.error(msg?.msg || t('somethingWentWrong'));
|
||||
return;
|
||||
}
|
||||
const ok = msg?.obj?.created ?? 0;
|
||||
const skipped = msg?.obj?.skipped ?? [];
|
||||
const failed = skipped.length;
|
||||
const firstError = skipped[0]?.reason ?? msg?.msg ?? '';
|
||||
if (failed === 0 && msg?.success) {
|
||||
const firstError = skipped[0]?.reason ?? '';
|
||||
if (failed === 0) {
|
||||
messageApi.success(t('pages.clients.toasts.bulkCreated', { count: ok }));
|
||||
} else {
|
||||
messageApi.warning(
|
||||
|
||||
@@ -101,7 +101,7 @@ export default function ClientBulkAdjustModal({
|
||||
const result = await onSubmit(days, bytes, flowValue, limitHwid, adTag, externalLinks);
|
||||
if (!result) return;
|
||||
const ok = result.adjusted ?? 0;
|
||||
const skipped = result.skipped?.length ?? 0;
|
||||
const skipped = result.skippedCount ?? result.skipped?.length ?? 0;
|
||||
if (result.externalLinks) {
|
||||
const summary = t('pages.clients.toasts.bulkLinksAppended', {
|
||||
clients: ok,
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Button, Modal, Table, Tooltip, Typography, message } from 'antd';
|
||||
import type { TableColumnType } from 'antd';
|
||||
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';
|
||||
|
||||
import {
|
||||
GROUP_CLIENT_PAGE_SIZE,
|
||||
groupSubscriptionExportPath,
|
||||
useGroupClientPage,
|
||||
} from '@/api/groupClients';
|
||||
|
||||
import type { ClientRecord } from '@/hooks/useClients';
|
||||
|
||||
interface SubSettings {
|
||||
@@ -13,13 +19,14 @@ interface SubSettings {
|
||||
subJsonEnable: boolean;
|
||||
}
|
||||
|
||||
interface SubLinksModalProps {
|
||||
type SubLinksModalProps = {
|
||||
open: boolean;
|
||||
emails: string[];
|
||||
clients: ClientRecord[];
|
||||
subSettings?: SubSettings;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
} & (
|
||||
| { emails: string[]; clients: ClientRecord[]; group?: never }
|
||||
| { group: string; emails?: never; clients?: never }
|
||||
);
|
||||
|
||||
interface Row {
|
||||
key: string;
|
||||
@@ -33,6 +40,7 @@ export default function SubLinksModal({
|
||||
open,
|
||||
emails,
|
||||
clients,
|
||||
group,
|
||||
subSettings,
|
||||
onOpenChange,
|
||||
}: SubLinksModalProps) {
|
||||
@@ -42,33 +50,73 @@ export default function SubLinksModal({
|
||||
const enabled = !!subSettings?.enable && !!subSettings?.subURI;
|
||||
const jsonEnabled = !!subSettings?.subJsonEnable && !!subSettings?.subJsonURI;
|
||||
|
||||
const [page, setPage] = useState(1);
|
||||
const [copying, setCopying] = useState(false);
|
||||
const groupPage = useGroupClientPage(
|
||||
{ group: group ?? '', mode: 'links', page },
|
||||
!!group && open && enabled,
|
||||
);
|
||||
const exportPath = group ? groupSubscriptionExportPath(group) : undefined;
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
if (!enabled) return [];
|
||||
const byEmail = new Map(clients.map((c) => [c.email, c]));
|
||||
const out: Row[] = [];
|
||||
for (const email of emails) {
|
||||
const c = byEmail.get(email);
|
||||
if (!c?.subId) continue;
|
||||
out.push({
|
||||
function row(email: string, subId: string): Row {
|
||||
return {
|
||||
key: email,
|
||||
email,
|
||||
subId: c.subId,
|
||||
link: subSettings!.subURI + c.subId,
|
||||
jsonLink: jsonEnabled ? subSettings!.subJsonURI + c.subId : '',
|
||||
});
|
||||
subId,
|
||||
link: subSettings!.subURI + subId,
|
||||
jsonLink: jsonEnabled ? subSettings!.subJsonURI + subId : '',
|
||||
};
|
||||
}
|
||||
if (group) return (groupPage.data?.items ?? []).map(({ email, subId }) => row(email, subId));
|
||||
const byEmail = new Map((clients ?? []).map((client) => [client.email, client.subId]));
|
||||
const out: Row[] = [];
|
||||
for (const email of emails ?? []) {
|
||||
const subId = byEmail.get(email);
|
||||
if (subId) out.push(row(email, subId));
|
||||
}
|
||||
return out;
|
||||
}, [emails, clients, enabled, jsonEnabled, subSettings]);
|
||||
}, [emails, clients, enabled, group, groupPage.data?.items, jsonEnabled, subSettings]);
|
||||
const total = group ? (groupPage.data?.total ?? 0) : rows.length;
|
||||
|
||||
const allText = useMemo(
|
||||
() =>
|
||||
rows
|
||||
.map((r) =>
|
||||
jsonEnabled ? `${r.email}\t${r.link}\t${r.jsonLink}` : `${r.email}\t${r.link}`,
|
||||
)
|
||||
.join('\n'),
|
||||
[rows, jsonEnabled],
|
||||
);
|
||||
function allText() {
|
||||
return rows
|
||||
.map(({ email, link, jsonLink }) =>
|
||||
jsonEnabled ? `${email}\t${link}\t${jsonLink}` : `${email}\t${link}`,
|
||||
)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
async function copyAll() {
|
||||
if (!exportPath) {
|
||||
await copy(allText(), t('pages.clients.subLinksCopiedAll', { count: total }));
|
||||
return;
|
||||
}
|
||||
setCopying(true);
|
||||
try {
|
||||
const content = async () => {
|
||||
const response = await fetch(exportPath, { credentials: 'same-origin' });
|
||||
if (!response.ok || !response.headers.get('Content-Type')?.startsWith('text/plain')) {
|
||||
throw new Error(t('somethingWentWrong'));
|
||||
}
|
||||
return response.blob();
|
||||
};
|
||||
if (typeof ClipboardItem !== 'undefined' && navigator.clipboard?.write) {
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'text/plain': content().then((blob) => new Blob([blob], { type: 'text/plain' })),
|
||||
}),
|
||||
]);
|
||||
} else {
|
||||
await navigator.clipboard.writeText(await (await content()).text());
|
||||
}
|
||||
messageApi.success(t('copied'));
|
||||
} catch {
|
||||
messageApi.error(t('somethingWentWrong'));
|
||||
} finally {
|
||||
setCopying(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function copy(text: string, label?: string) {
|
||||
try {
|
||||
@@ -80,7 +128,7 @@ export default function SubLinksModal({
|
||||
}
|
||||
|
||||
function download() {
|
||||
const blob = new Blob([allText], { type: 'text/plain;charset=utf-8' });
|
||||
const blob = new Blob([allText()], { type: 'text/plain;charset=utf-8' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
||||
@@ -150,7 +198,7 @@ export default function SubLinksModal({
|
||||
{messageContextHolder}
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('pages.clients.subLinksTitle', { count: rows.length })}
|
||||
title={t('pages.clients.subLinksTitle', { count: total })}
|
||||
width={780}
|
||||
footer={
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||
@@ -158,18 +206,19 @@ export default function SubLinksModal({
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<Button
|
||||
icon={<CopyOutlined aria-hidden />}
|
||||
disabled={rows.length === 0}
|
||||
onClick={() =>
|
||||
copy(allText, t('pages.clients.subLinksCopiedAll', { count: rows.length }))
|
||||
}
|
||||
disabled={!total}
|
||||
loading={copying}
|
||||
onClick={copyAll}
|
||||
>
|
||||
{t('pages.clients.subLinksCopyAll')}
|
||||
</Button>
|
||||
<Button
|
||||
type="primary"
|
||||
icon={<DownloadOutlined aria-hidden />}
|
||||
disabled={rows.length === 0}
|
||||
onClick={download}
|
||||
disabled={!total}
|
||||
href={exportPath}
|
||||
download={exportPath ? 'sub-links.txt' : undefined}
|
||||
onClick={exportPath ? undefined : download}
|
||||
>
|
||||
{t('download')}
|
||||
</Button>
|
||||
@@ -187,7 +236,7 @@ export default function SubLinksModal({
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
)}
|
||||
{enabled && rows.length === 0 && (
|
||||
{enabled && !total && !groupPage.isFetching && !groupPage.isError && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
@@ -195,12 +244,26 @@ export default function SubLinksModal({
|
||||
style={{ marginBottom: 12 }}
|
||||
/>
|
||||
)}
|
||||
{rows.length > 0 && (
|
||||
{groupPage.isError && (
|
||||
<Alert showIcon type="error" title={groupPage.error.message || t('somethingWentWrong')} />
|
||||
)}
|
||||
{enabled && (total > 0 || groupPage.isFetching) && (
|
||||
<Table<Row>
|
||||
dataSource={rows}
|
||||
columns={columns}
|
||||
size="small"
|
||||
pagination={false}
|
||||
loading={groupPage.isFetching}
|
||||
pagination={
|
||||
group
|
||||
? {
|
||||
current: page,
|
||||
pageSize: GROUP_CLIENT_PAGE_SIZE,
|
||||
total,
|
||||
showSizeChanger: false,
|
||||
onChange: setPage,
|
||||
}
|
||||
: false
|
||||
}
|
||||
scroll={{ y: 360 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
|
||||
import type { ClientRecord } from '@/hooks/useClients';
|
||||
|
||||
interface GroupAddClientsModalProps {
|
||||
open: boolean;
|
||||
groupName: string | null;
|
||||
candidates: ClientRecord[];
|
||||
onClose: () => void;
|
||||
onSubmit: (emails: string[]) => Promise<{ affected?: number } | null>;
|
||||
}
|
||||
|
||||
interface ClientRow {
|
||||
email: string;
|
||||
comment: string;
|
||||
enable: boolean;
|
||||
currentGroup: string;
|
||||
}
|
||||
|
||||
export default function GroupAddClientsModal({
|
||||
open,
|
||||
groupName,
|
||||
candidates,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: GroupAddClientsModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const rows = useMemo<ClientRow[]>(
|
||||
() =>
|
||||
(candidates || [])
|
||||
.map((c) => ({
|
||||
email: (c.email || '').trim(),
|
||||
comment: (c.comment || '').trim(),
|
||||
enable: c.enable !== false,
|
||||
currentGroup: (c.group || '').trim(),
|
||||
}))
|
||||
.filter((r) => r.email),
|
||||
[candidates],
|
||||
);
|
||||
|
||||
// React resets this during render rather than in an effect so the modal's
|
||||
// first open frame already shows cleared fields.
|
||||
const [wasOpen, setWasOpen] = useState(false);
|
||||
if (open !== wasOpen) {
|
||||
setWasOpen(open);
|
||||
if (open) {
|
||||
setSelectedEmails([]);
|
||||
setSearch('');
|
||||
}
|
||||
}
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
if (!q) return rows;
|
||||
return rows.filter(
|
||||
(r) =>
|
||||
r.email.toLowerCase().includes(q) ||
|
||||
r.comment.toLowerCase().includes(q) ||
|
||||
r.currentGroup.toLowerCase().includes(q),
|
||||
);
|
||||
}, [rows, search]);
|
||||
|
||||
const columns: ColumnsType<ClientRow> = useMemo(
|
||||
() => [
|
||||
{ title: t('pages.inbounds.email'), dataIndex: 'email', key: 'email', ellipsis: true },
|
||||
{ title: t('comment'), dataIndex: 'comment', key: 'comment', ellipsis: true },
|
||||
{
|
||||
title: t('pages.clients.group'),
|
||||
dataIndex: 'currentGroup',
|
||||
key: 'currentGroup',
|
||||
width: 140,
|
||||
ellipsis: true,
|
||||
render: (g: string) =>
|
||||
g ? (
|
||||
<Tag color="geekblue">{g}</Tag>
|
||||
) : (
|
||||
<Typography.Text type="secondary">—</Typography.Text>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
key: 'enable',
|
||||
width: 90,
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? (
|
||||
<Tag color="success">{t('enable')}</Tag>
|
||||
) : (
|
||||
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
async function submit() {
|
||||
if (!groupName || selectedEmails.length === 0) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await onSubmit(selectedEmails);
|
||||
if (!result) return;
|
||||
const affected = result.affected ?? selectedEmails.length;
|
||||
messageApi.success(t('pages.groups.addToGroupResult', { count: affected, name: groupName }));
|
||||
onClose();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
onOk={submit}
|
||||
okButtonProps={{ disabled: selectedEmails.length === 0, loading: saving }}
|
||||
okText={t('add')}
|
||||
cancelText={t('cancel')}
|
||||
title={t('pages.groups.addToGroupTitle', { name: groupName ?? '' })}
|
||||
width={720}
|
||||
>
|
||||
{messageContextHolder}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t('pages.groups.addToGroupDesc')}
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
|
||||
<Input.Search
|
||||
allowClear
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected: selectedEmails.length,
|
||||
total: rows.length,
|
||||
})}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{rows.length === 0 ? (
|
||||
<Alert type="info" showIcon title={t('pages.groups.addToGroupEmpty')} />
|
||||
) : (
|
||||
<Table<ClientRow>
|
||||
size="small"
|
||||
rowKey="email"
|
||||
columns={columns}
|
||||
dataSource={filteredRows}
|
||||
pagination={false}
|
||||
scroll={{ y: 320 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedEmails,
|
||||
onChange: (keys) => setSelectedEmails(keys as string[]),
|
||||
preserveSelectedRowKeys: true,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Alert, Button, Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
|
||||
import {
|
||||
GROUP_CLIENT_PAGE_SIZE,
|
||||
MAX_GROUP_EXCLUSIONS,
|
||||
fetchGroupClients,
|
||||
useGroupClientPage,
|
||||
type GroupClientSelection,
|
||||
} from '@/api/groupClients';
|
||||
import type { GroupClientRow } from '@/generated/zod';
|
||||
|
||||
interface GroupClientsModalProps {
|
||||
group: string;
|
||||
mode: 'add' | 'remove';
|
||||
onClose: () => void;
|
||||
onSubmit: (selection: GroupClientSelection) => Promise<{ affected?: number } | null>;
|
||||
}
|
||||
|
||||
export default function GroupClientsModal({
|
||||
group,
|
||||
mode,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: GroupClientsModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [messages, holder] = message.useMessage();
|
||||
const [page, setPage] = useState(1);
|
||||
const [search, setSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [choices, setChoices] = useState(new Set<number>());
|
||||
const [frozen, setFrozen] = useState<{
|
||||
token: string;
|
||||
count: number;
|
||||
maxId: number;
|
||||
search: string;
|
||||
}>();
|
||||
const [busy, setBusy] = useState<'freeze' | 'submit'>();
|
||||
const action = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => setDebouncedSearch(search), 220);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [search]);
|
||||
|
||||
const query = useGroupClientPage(
|
||||
{
|
||||
group,
|
||||
mode,
|
||||
page,
|
||||
search: debouncedSearch,
|
||||
maxId: frozen?.maxId,
|
||||
scopeSearch: frozen?.search,
|
||||
},
|
||||
search === debouncedSearch,
|
||||
);
|
||||
const loading = search !== debouncedSearch || query.isFetching;
|
||||
const rows = loading ? [] : (query.data?.items ?? []);
|
||||
const selected = frozen ? frozen.count - choices.size : choices.size;
|
||||
const visible = rows.filter((row) => !frozen || row.inScope);
|
||||
const add = mode === 'add';
|
||||
|
||||
function clearSelection() {
|
||||
setFrozen(undefined);
|
||||
setChoices(new Set());
|
||||
}
|
||||
|
||||
function selectVisible(keys: React.Key[]) {
|
||||
const checked = new Set(keys);
|
||||
const next = new Set(choices);
|
||||
for (const row of visible) {
|
||||
if (frozen ? !checked.has(row.id) : checked.has(row.id)) next.add(row.id);
|
||||
else next.delete(row.id);
|
||||
}
|
||||
if (next.size > (frozen ? MAX_GROUP_EXCLUSIONS : 50_000)) {
|
||||
messages.warning(
|
||||
t('pages.groups.selectionLimit', { count: frozen ? MAX_GROUP_EXCLUSIONS : 50_000 }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
setChoices(next);
|
||||
}
|
||||
|
||||
async function selectAll() {
|
||||
if (action.current || loading) return;
|
||||
action.current = true;
|
||||
setBusy('freeze');
|
||||
try {
|
||||
const result = await fetchGroupClients({
|
||||
group,
|
||||
mode,
|
||||
search: debouncedSearch,
|
||||
freeze: true,
|
||||
});
|
||||
if (!result.scopeToken || !result.maxId || !result.total) {
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
setChoices(new Set());
|
||||
setFrozen({
|
||||
token: result.scopeToken,
|
||||
maxId: result.maxId,
|
||||
count: result.total,
|
||||
search: debouncedSearch,
|
||||
});
|
||||
} catch (error) {
|
||||
messages.error((error instanceof Error && error.message) || t('somethingWentWrong'));
|
||||
} finally {
|
||||
action.current = false;
|
||||
setBusy(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (action.current || selected <= 0) return;
|
||||
action.current = true;
|
||||
setBusy('submit');
|
||||
try {
|
||||
const selection: GroupClientSelection = frozen
|
||||
? {
|
||||
mode: 'allMatching',
|
||||
scopeToken: frozen.token,
|
||||
search: frozen.search,
|
||||
excludedClientIds: [...choices],
|
||||
}
|
||||
: { mode: 'explicit', clientIds: [...choices] };
|
||||
const result = await onSubmit(selection);
|
||||
if (result) {
|
||||
messages.success(
|
||||
t(add ? 'pages.groups.addToGroupResult' : 'pages.groups.removeFromGroupResult', {
|
||||
count: result.affected ?? 0,
|
||||
name: group,
|
||||
}),
|
||||
);
|
||||
onClose();
|
||||
}
|
||||
} finally {
|
||||
action.current = false;
|
||||
setBusy(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnsType<GroupClientRow> = [
|
||||
{ title: t('pages.inbounds.email'), dataIndex: 'email', width: 220, ellipsis: true },
|
||||
{ title: t('comment'), dataIndex: 'comment', ellipsis: true },
|
||||
...(add
|
||||
? [
|
||||
{
|
||||
title: t('pages.clients.group'),
|
||||
dataIndex: 'group',
|
||||
width: 140,
|
||||
ellipsis: true,
|
||||
render: (label: string) => (label ? <Tag color="geekblue">{label}</Tag> : '—'),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
width: 100,
|
||||
render: (enabled: boolean) => (
|
||||
<Tag color={enabled ? 'success' : undefined}>
|
||||
{t(enabled ? 'enable' : 'pages.inbounds.attachClientsStatusDisabled')}
|
||||
</Tag>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onCancel={() => {
|
||||
if (!action.current) onClose();
|
||||
}}
|
||||
onOk={submit}
|
||||
okButtonProps={{ disabled: selected <= 0 || !!busy, danger: !add }}
|
||||
confirmLoading={busy === 'submit'}
|
||||
okText={t(add ? 'add' : 'remove')}
|
||||
cancelText={t('cancel')}
|
||||
cancelButtonProps={{ disabled: !!busy }}
|
||||
title={t(add ? 'pages.groups.addToGroupTitle' : 'pages.groups.removeFromGroupTitle', {
|
||||
name: group,
|
||||
})}
|
||||
width={720}
|
||||
>
|
||||
{holder}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t(add ? 'pages.groups.addToGroupDesc' : 'pages.groups.removeFromGroupDesc')}
|
||||
</Typography.Paragraph>
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Input.Search
|
||||
allowClear
|
||||
disabled={!!busy}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
setSearch(event.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
maxLength={256}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
<Space wrap>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!!busy || loading || !visible.length}
|
||||
onClick={() => selectVisible(visible.map((row) => row.id))}
|
||||
>
|
||||
{t('pages.inbounds.attachSelectPage')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!!busy || loading || !query.data?.total}
|
||||
loading={busy === 'freeze'}
|
||||
aria-pressed={!!frozen}
|
||||
onClick={selectAll}
|
||||
>
|
||||
{t('pages.groups.selectAllMatching')}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
disabled={!!busy || (!choices.size && !frozen)}
|
||||
onClick={clearSelection}
|
||||
>
|
||||
{t('pages.inbounds.attachClearSelection')}
|
||||
</Button>
|
||||
{frozen && choices.size > 0 && (
|
||||
<Button size="small" disabled={!!busy} onClick={() => setChoices(new Set())}>
|
||||
{t('pages.inbounds.attachClearExclusions')}
|
||||
</Button>
|
||||
)}
|
||||
<Typography.Text role="status" type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected,
|
||||
total: frozen?.count ?? query.data?.total ?? 0,
|
||||
})}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{query.isError && (
|
||||
<Alert showIcon type="error" title={query.error.message || t('somethingWentWrong')} />
|
||||
)}
|
||||
{!loading && !query.isError && !search && query.data?.total === 0 && (
|
||||
<Alert
|
||||
type="info"
|
||||
showIcon
|
||||
title={t(add ? 'pages.groups.addToGroupEmpty' : 'pages.groups.removeFromGroupEmpty')}
|
||||
/>
|
||||
)}
|
||||
<Table<GroupClientRow>
|
||||
size="small"
|
||||
rowKey="id"
|
||||
virtual
|
||||
columns={columns}
|
||||
dataSource={rows}
|
||||
loading={loading}
|
||||
scroll={{ x: 620, y: 320 }}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize: GROUP_CLIENT_PAGE_SIZE,
|
||||
total: query.data?.total ?? 0,
|
||||
showSizeChanger: false,
|
||||
disabled: !!busy,
|
||||
onChange: setPage,
|
||||
}}
|
||||
rowSelection={{
|
||||
selectedRowKeys: visible
|
||||
.filter((row) => choices.has(row.id) !== !!frozen)
|
||||
.map((row) => row.id),
|
||||
onChange: selectVisible,
|
||||
getTitleCheckboxProps: () => ({ 'aria-label': t('pages.inbounds.attachSelectPage') }),
|
||||
getCheckboxProps: (row) => ({
|
||||
'aria-label': row.email,
|
||||
disabled: !!busy || (!!frozen && !row.inScope),
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
|
||||
import type { ClientRecord } from '@/hooks/useClients';
|
||||
|
||||
interface GroupRemoveClientsModalProps {
|
||||
open: boolean;
|
||||
groupName: string | null;
|
||||
members: ClientRecord[];
|
||||
onClose: () => void;
|
||||
onSubmit: (emails: string[]) => Promise<{ affected?: number } | null>;
|
||||
}
|
||||
|
||||
interface ClientRow {
|
||||
email: string;
|
||||
comment: string;
|
||||
enable: boolean;
|
||||
}
|
||||
|
||||
export default function GroupRemoveClientsModal({
|
||||
open,
|
||||
groupName,
|
||||
members,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: GroupRemoveClientsModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
|
||||
const [search, setSearch] = useState('');
|
||||
|
||||
const rows = useMemo<ClientRow[]>(
|
||||
() =>
|
||||
(members || [])
|
||||
.map((c) => ({
|
||||
email: (c.email || '').trim(),
|
||||
comment: (c.comment || '').trim(),
|
||||
enable: c.enable !== false,
|
||||
}))
|
||||
.filter((r) => r.email),
|
||||
[members],
|
||||
);
|
||||
|
||||
// React resets this during render rather than in an effect so the modal's
|
||||
// first open frame already shows cleared fields.
|
||||
const [wasOpen, setWasOpen] = useState(false);
|
||||
if (open !== wasOpen) {
|
||||
setWasOpen(open);
|
||||
if (open) {
|
||||
setSelectedEmails([]);
|
||||
setSearch('');
|
||||
}
|
||||
}
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
if (!q) return rows;
|
||||
return rows.filter(
|
||||
(r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q),
|
||||
);
|
||||
}, [rows, search]);
|
||||
|
||||
const columns: ColumnsType<ClientRow> = useMemo(
|
||||
() => [
|
||||
{ title: t('pages.inbounds.email'), dataIndex: 'email', key: 'email', ellipsis: true },
|
||||
{ title: t('comment'), dataIndex: 'comment', key: 'comment', ellipsis: true },
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
key: 'enable',
|
||||
width: 90,
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? (
|
||||
<Tag color="success">{t('enable')}</Tag>
|
||||
) : (
|
||||
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
|
||||
async function submit() {
|
||||
if (!groupName || selectedEmails.length === 0) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const result = await onSubmit(selectedEmails);
|
||||
if (!result) return;
|
||||
const affected = result.affected ?? selectedEmails.length;
|
||||
messageApi.success(
|
||||
t('pages.groups.removeFromGroupResult', { count: affected, name: groupName }),
|
||||
);
|
||||
onClose();
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
onOk={submit}
|
||||
okButtonProps={{ danger: true, disabled: selectedEmails.length === 0, loading: saving }}
|
||||
okText={t('remove')}
|
||||
cancelText={t('cancel')}
|
||||
title={t('pages.groups.removeFromGroupTitle', { name: groupName ?? '' })}
|
||||
width={680}
|
||||
>
|
||||
{messageContextHolder}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t('pages.groups.removeFromGroupDesc')}
|
||||
</Typography.Paragraph>
|
||||
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
|
||||
<Input.Search
|
||||
allowClear
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected: selectedEmails.length,
|
||||
total: rows.length,
|
||||
})}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
<Table<ClientRow>
|
||||
size="small"
|
||||
rowKey="email"
|
||||
columns={columns}
|
||||
dataSource={filteredRows}
|
||||
pagination={false}
|
||||
scroll={{ y: 280 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedEmails,
|
||||
onChange: (keys) => setSelectedEmails(keys as string[]),
|
||||
preserveSelectedRowKeys: true,
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { useState } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, waitFor, within } from 'storybook/test';
|
||||
import { Button } from 'antd';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
|
||||
import { ThemeProvider } from '@/hooks/useTheme';
|
||||
import AddClientsToGroupModal from '@/pages/inbounds/clients/AddClientsToGroupModal';
|
||||
import GroupsPage from './GroupsPage';
|
||||
|
||||
const api = '/panel/api/clients';
|
||||
const group = 'staff';
|
||||
const groupCount = 10_000;
|
||||
const requests: { path: string; query: URLSearchParams; body?: Record<string, unknown> }[] = [];
|
||||
const exportedLinks = Array.from({ length: groupCount }, (_, index) => {
|
||||
const id = index + 1;
|
||||
return `client-${id}@example.test\thttps://sub.example.test/plain/s${id}`;
|
||||
}).join('\n');
|
||||
let copiedLinks = '';
|
||||
|
||||
function GroupFixture() {
|
||||
const [queryClient] = useState(() => new QueryClient());
|
||||
const [inboundOpen, setInboundOpen] = useState(false);
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/panel/groups']}>
|
||||
<ThemeProvider>
|
||||
<Button onClick={() => setInboundOpen(true)}>Group the source inbound</Button>
|
||||
<GroupsPage />
|
||||
<AddClientsToGroupModal
|
||||
open={inboundOpen}
|
||||
inboundId={7}
|
||||
count={groupCount}
|
||||
onClose={() => setInboundOpen(false)}
|
||||
/>
|
||||
</ThemeProvider>
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function response(obj: unknown) {
|
||||
return Promise.resolve(Response.json({ success: true, msg: '', obj }));
|
||||
}
|
||||
|
||||
const meta = {
|
||||
title: 'Pages/Groups/Client management',
|
||||
component: GroupsPage,
|
||||
render: () => <GroupFixture />,
|
||||
} satisfies Meta<typeof GroupsPage>;
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const LargeGroup: Story = {
|
||||
parameters: { a11y: { context: '.ant-modal' } },
|
||||
beforeEach: () => {
|
||||
requests.length = 0;
|
||||
copiedLinks = '';
|
||||
const original = window.fetch;
|
||||
const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: {
|
||||
writeText: async (value: string) => {
|
||||
copiedLinks = value;
|
||||
},
|
||||
write: async (items: ClipboardItem[]) => {
|
||||
copiedLinks = await (await items[0]!.getType('text/plain')).text();
|
||||
},
|
||||
},
|
||||
});
|
||||
window.fetch = (input, init) => {
|
||||
const url = new URL(input instanceof Request ? input.url : input, window.location.href);
|
||||
const path = url.pathname;
|
||||
const query = url.searchParams;
|
||||
const body =
|
||||
typeof init?.body === 'string' && init.body.startsWith('{')
|
||||
? (JSON.parse(init.body) as Record<string, unknown>)
|
||||
: undefined;
|
||||
requests.push({ path, query, body });
|
||||
if (path === api + '/groups') {
|
||||
return response([
|
||||
{
|
||||
id: 1,
|
||||
name: group,
|
||||
clientCount: groupCount,
|
||||
hostGroupIds: [],
|
||||
trafficUsed: 0,
|
||||
up: 0,
|
||||
down: 0,
|
||||
},
|
||||
]);
|
||||
}
|
||||
if (path === '/panel/api/setting/defaultSettings') {
|
||||
return response({ subEnable: true, subURI: 'https://sub.example.test/plain/' });
|
||||
}
|
||||
if (path === '/panel/api/setting/all') return response({});
|
||||
if (path === '/csrf-token') return response('story-token');
|
||||
if (path === api + '/groups/clientPage') {
|
||||
const mode = query.get('mode');
|
||||
const search = query.get('search');
|
||||
const total = search ? 1 : mode === 'add' ? 40_000 : groupCount;
|
||||
const maxId = mode === 'add' ? 50_000 : 10_000;
|
||||
if (query.get('freeze') === 'true') {
|
||||
return response({ items: [], total, scopeToken: `scope-${mode}-${search ?? ''}`, maxId });
|
||||
}
|
||||
const offset = (Number(query.get('page') ?? '1') - 1) * 100;
|
||||
const items = Array.from({ length: Math.min(100, total) }, (_, index) => {
|
||||
const id = search ? 10101 : (mode === 'add' ? groupCount : 0) + offset + index + 1;
|
||||
return {
|
||||
id,
|
||||
email: `client-${id}@example.test`,
|
||||
comment: '',
|
||||
group: mode === 'add' ? '' : group,
|
||||
enable: true,
|
||||
subId: `s${id}`,
|
||||
inScope: !query.get('scopeSearch') || id === 10101,
|
||||
};
|
||||
});
|
||||
return response({ items, total });
|
||||
}
|
||||
if (path === api + '/groups/subLinks/export') {
|
||||
return Promise.resolve(
|
||||
new Response(exportedLinks, { headers: { 'Content-Type': 'text/plain' } }),
|
||||
);
|
||||
}
|
||||
if (path === api + '/bulkAdjust') return response({ adjusted: groupCount });
|
||||
if (path === api + '/bulkDel') return response({ deleted: groupCount });
|
||||
if (path.endsWith('/bulkAdd') || path.endsWith('/bulkRemove'))
|
||||
return response({ affected: 1 });
|
||||
if (path.startsWith('/panel/api/')) return response([]);
|
||||
return original(input, init);
|
||||
};
|
||||
return () => {
|
||||
window.fetch = original;
|
||||
if (clipboard) Object.defineProperty(navigator, 'clipboard', clipboard);
|
||||
else Reflect.deleteProperty(navigator, 'clipboard');
|
||||
};
|
||||
},
|
||||
play: async ({ userEvent }) => {
|
||||
const screen = within(document.body);
|
||||
const open = async (label: RegExp) => {
|
||||
await userEvent.click((await screen.findAllByRole('button', { name: 'more' }))[0]!);
|
||||
await userEvent.click(await screen.findByRole('menuitem', { name: label }));
|
||||
return within(await screen.findByRole('dialog'));
|
||||
};
|
||||
const close = async (dialog: ReturnType<typeof within>, name = 'Cancel') => {
|
||||
await userEvent.click(dialog.getAllByRole('button', { name }).at(-1)!);
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
};
|
||||
const add = await open(/add clients…/i);
|
||||
await add.findByText('client-10001@example.test');
|
||||
await expect(add.getAllByRole('checkbox').length).toBeLessThan(101);
|
||||
await userEvent.click(add.getByRole('button', { name: 'Select this page' }));
|
||||
const nextPage = screen.getByRole('dialog').querySelector('.ant-pagination-next button');
|
||||
if (!(nextPage instanceof HTMLButtonElement)) {
|
||||
throw new Error(
|
||||
'Next page control missing: ' +
|
||||
screen.getByRole('dialog').querySelector('.ant-pagination')?.outerHTML,
|
||||
);
|
||||
}
|
||||
await userEvent.click(nextPage);
|
||||
await waitFor(() => {
|
||||
const loaded = requests
|
||||
.filter((request) => request.path.endsWith('/clientPage'))
|
||||
.map((request) => request.query.toString());
|
||||
expect(loaded).toContain('group=staff&mode=add&page=2&search=');
|
||||
});
|
||||
await add.findByText('client-10101@example.test');
|
||||
await expect(add.getByRole('status')).toHaveTextContent('100 of 40000 selected');
|
||||
const selectAll = add.getByRole('button', { name: /Select all matching clients/i });
|
||||
await userEvent.click(selectAll);
|
||||
await waitFor(() => expect(selectAll).toHaveAttribute('aria-pressed', 'true'));
|
||||
const checkbox = await add.findByRole('checkbox', { name: 'client-10101@example.test' });
|
||||
await waitFor(() => expect(checkbox).toBeChecked());
|
||||
await userEvent.click(checkbox);
|
||||
await userEvent.type(add.getByRole('searchbox'), '10101');
|
||||
await waitFor(() => expect(requests.some((r) => r.query.get('search') === '10101')).toBe(true));
|
||||
await userEvent.click(add.getByRole('button', { name: /^Add$/ }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
await expect(requests.find((r) => r.path === api + '/groups/bulkAdd')?.body).toEqual({
|
||||
group,
|
||||
selection: {
|
||||
mode: 'allMatching',
|
||||
scopeToken: 'scope-add-',
|
||||
search: '',
|
||||
excludedClientIds: [10101],
|
||||
},
|
||||
});
|
||||
|
||||
const remove = await open(/remove clients…/i);
|
||||
await remove.findByText('client-1@example.test');
|
||||
await expect(remove.getAllByRole('checkbox').length).toBeLessThan(101);
|
||||
await close(remove);
|
||||
|
||||
const links = await open(/sub links/i);
|
||||
await links.findByText('https://sub.example.test/plain/s1');
|
||||
await expect(links.getAllByRole('row').length).toBeLessThanOrEqual(101);
|
||||
await expect(links.getByRole('link', { name: 'Download' })).toHaveAttribute(
|
||||
'href',
|
||||
api + '/groups/subLinks/export?group=staff',
|
||||
);
|
||||
await userEvent.click(links.getByRole('button', { name: /copy all/i }));
|
||||
await waitFor(() => expect(copiedLinks).toBe(exportedLinks));
|
||||
await close(links, 'Close');
|
||||
|
||||
const adjust = await open(/adjust/i);
|
||||
await userEvent.type(adjust.getByLabelText('Add days'), '1');
|
||||
await userEvent.click(adjust.getByRole('button', { name: 'Confirm' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
await expect(requests.find((r) => r.path === api + '/bulkAdjust')?.body).toMatchObject({
|
||||
group,
|
||||
scopeToken: 'scope-remove-',
|
||||
addDays: 1,
|
||||
});
|
||||
const del = await open(/delete clients in group/i);
|
||||
await userEvent.click(del.getByRole('button', { name: /^Delete$/ }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
await expect(requests.find((r) => r.path === api + '/bulkDel')?.body).toEqual({
|
||||
group,
|
||||
scopeToken: 'scope-remove-',
|
||||
keepTraffic: false,
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Group the source inbound' }));
|
||||
const inbound = within(await screen.findByRole('dialog'));
|
||||
await userEvent.type(inbound.getByRole('combobox'), group);
|
||||
await userEvent.click(inbound.getByRole('button', { name: /^Add$/ }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
await expect(requests.filter((r) => r.path === api + '/groups/bulkAdd').at(-1)?.body).toEqual({
|
||||
inboundId: 7,
|
||||
group,
|
||||
});
|
||||
await expect(
|
||||
requests.some(
|
||||
(r) =>
|
||||
r.path === api + '/list' || r.path.endsWith('/emails') || Array.isArray(r.body?.emails),
|
||||
),
|
||||
).toBe(false);
|
||||
const picker = await open(/add clients…/i);
|
||||
await picker.findByRole('checkbox', { name: 'client-10001@example.test' });
|
||||
},
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { lazy, useCallback, useEffect, useId, useMemo, useState } from 'react';
|
||||
import { lazy, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Button,
|
||||
@@ -39,7 +39,6 @@ import {
|
||||
UsergroupDeleteOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
@@ -50,24 +49,14 @@ import { setMessageInstance } from '@/utils/messageBus';
|
||||
import AppSidebar from '@/layouts/AppSidebar';
|
||||
import { LazyMount } from '@/components/utility';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import {
|
||||
ClientRecordSchema,
|
||||
GroupSummaryListSchema,
|
||||
type ClientRecord,
|
||||
type GroupSummary,
|
||||
} from '@/schemas/client';
|
||||
import { fetchGroupClients, type GroupBulkScope } from '@/api/groupClients';
|
||||
import { GroupSummaryListSchema, type GroupSummary } from '@/schemas/client';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
import HostGroupSelect from './HostGroupSelect';
|
||||
|
||||
const ClientRecordListSchema = z
|
||||
.array(ClientRecordSchema)
|
||||
.nullable()
|
||||
.transform((v) => v ?? []);
|
||||
|
||||
const SubLinksModal = lazy(() => import('../clients/SubLinksModal'));
|
||||
const ClientBulkAdjustModal = lazy(() => import('../clients/ClientBulkAdjustModal'));
|
||||
const GroupAddClientsModal = lazy(() => import('./GroupAddClientsModal'));
|
||||
const GroupRemoveClientsModal = lazy(() => import('./GroupRemoveClientsModal'));
|
||||
const GroupClientsModal = lazy(() => import('./GroupClientsModal'));
|
||||
const GroupHostRulesModal = lazy(() => import('./GroupHostRulesModal'));
|
||||
|
||||
const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } } as const;
|
||||
@@ -85,16 +74,6 @@ async function fetchGroups(): Promise<GroupSummary[]> {
|
||||
return validated.obj ?? [];
|
||||
}
|
||||
|
||||
async function fetchEmailsForGroup(name: string): Promise<string[]> {
|
||||
const msg = await HttpUtil.get<string[]>(
|
||||
`/panel/api/clients/groups/${encodeURIComponent(name)}/emails`,
|
||||
undefined,
|
||||
{ silent: true },
|
||||
);
|
||||
if (!msg?.success || !Array.isArray(msg.obj)) return [];
|
||||
return msg.obj;
|
||||
}
|
||||
|
||||
export default function GroupsPage() {
|
||||
usePageTitle();
|
||||
const { t } = useTranslation();
|
||||
@@ -184,22 +163,10 @@ export default function GroupsPage() {
|
||||
const [adjustOpen, setAdjustOpen] = useState(false);
|
||||
const [addClientsOpen, setAddClientsOpen] = useState(false);
|
||||
const [removeClientsOpen, setRemoveClientsOpen] = useState(false);
|
||||
const [groupEmails, setGroupEmails] = useState<string[]>([]);
|
||||
const [adjustScope, setAdjustScope] = useState<(GroupBulkScope & { count: number }) | null>(null);
|
||||
const scopeRequest = useRef(0);
|
||||
const [groupForAction, setGroupForAction] = useState<GroupSummary | null>(null);
|
||||
|
||||
const allClientsQuery = useQuery<ClientRecord[]>({
|
||||
queryKey: keys.clients.all(),
|
||||
queryFn: async () => {
|
||||
const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true });
|
||||
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients');
|
||||
const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list');
|
||||
return validated.obj ?? [];
|
||||
},
|
||||
enabled: addClientsOpen || removeClientsOpen || subLinksOpen,
|
||||
staleTime: 30_000,
|
||||
});
|
||||
const allClients = allClientsQuery.data ?? [];
|
||||
|
||||
const totalGroups = groups.length;
|
||||
const totalClients = useMemo(
|
||||
() => groups.reduce((acc, g) => acc + (g.clientCount || 0), 0),
|
||||
@@ -289,37 +256,47 @@ export default function GroupsPage() {
|
||||
});
|
||||
}
|
||||
|
||||
async function openSubLinksFor(g: GroupSummary) {
|
||||
function openSubLinksFor(g: GroupSummary) {
|
||||
if (!g.clientCount) {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return;
|
||||
}
|
||||
const emails = await fetchEmailsForGroup(g.name);
|
||||
if (emails.length === 0) {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return;
|
||||
}
|
||||
scopeRequest.current++;
|
||||
setGroupForAction(g);
|
||||
setGroupEmails(emails);
|
||||
setSubLinksOpen(true);
|
||||
}
|
||||
|
||||
async function openAdjustFor(g: GroupSummary) {
|
||||
async function freezeGroup(g: GroupSummary) {
|
||||
if (!g.clientCount) {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
const emails = await fetchEmailsForGroup(g.name);
|
||||
if (emails.length === 0) {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return;
|
||||
const request = ++scopeRequest.current;
|
||||
try {
|
||||
const result = await fetchGroupClients({ group: g.name, mode: 'remove', freeze: true });
|
||||
if (scopeRequest.current !== request) return null;
|
||||
if (!result.total || !result.scopeToken) {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return null;
|
||||
}
|
||||
return { group: g.name, count: result.total, scopeToken: result.scopeToken };
|
||||
} catch (error) {
|
||||
if (scopeRequest.current === request) {
|
||||
messageApi.error((error instanceof Error && error.message) || t('somethingWentWrong'));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
setGroupForAction(g);
|
||||
setGroupEmails(emails);
|
||||
}
|
||||
|
||||
async function openAdjustFor(g: GroupSummary) {
|
||||
const scope = await freezeGroup(g);
|
||||
if (!scope) return;
|
||||
setAdjustScope(scope);
|
||||
setAdjustOpen(true);
|
||||
}
|
||||
|
||||
function openAddClientsFor(g: GroupSummary) {
|
||||
scopeRequest.current++;
|
||||
setGroupForAction(g);
|
||||
setAddClientsOpen(true);
|
||||
}
|
||||
@@ -344,29 +321,26 @@ export default function GroupsPage() {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return;
|
||||
}
|
||||
scopeRequest.current++;
|
||||
setGroupForAction(g);
|
||||
setRemoveClientsOpen(true);
|
||||
}
|
||||
|
||||
function onDeleteClients(g: GroupSummary) {
|
||||
if (!g.clientCount) {
|
||||
messageApi.info(t('pages.groups.emptyForAction'));
|
||||
return;
|
||||
}
|
||||
async function onDeleteClients(g: GroupSummary) {
|
||||
const scope = await freezeGroup(g);
|
||||
if (!scope) return;
|
||||
modal.confirm({
|
||||
title: t('pages.groups.deleteClientsConfirmTitle', { name: g.name }),
|
||||
content: t('pages.groups.deleteClientsConfirmContent', { count: g.clientCount }),
|
||||
content: t('pages.groups.deleteClientsConfirmContent', { count: scope.count }),
|
||||
okText: t('delete'),
|
||||
okType: 'danger',
|
||||
cancelText: t('cancel'),
|
||||
onOk: async () => {
|
||||
const emails = await fetchEmailsForGroup(g.name);
|
||||
if (emails.length === 0) return;
|
||||
const msg = await bulkDelete(emails);
|
||||
const msg = await bulkDelete({ group: scope.group, scopeToken: scope.scopeToken });
|
||||
if (msg?.success) {
|
||||
const ok = msg.obj?.deleted ?? 0;
|
||||
const skipped = msg.obj?.skipped ?? [];
|
||||
const failed = skipped.length;
|
||||
const failed = msg.obj?.skippedCount ?? skipped.length;
|
||||
if (failed === 0) {
|
||||
messageApi.success(t('pages.groups.deleteClientsSuccess', { count: ok }));
|
||||
} else {
|
||||
@@ -750,69 +724,67 @@ export default function GroupsPage() {
|
||||
/>
|
||||
</LazyMount>
|
||||
|
||||
<LazyMount when={subLinksOpen}>
|
||||
<SubLinksModal
|
||||
open={subLinksOpen}
|
||||
emails={groupEmails}
|
||||
clients={allClients}
|
||||
subSettings={subSettings}
|
||||
onOpenChange={setSubLinksOpen}
|
||||
/>
|
||||
</LazyMount>
|
||||
{subLinksOpen && groupForAction && (
|
||||
<LazyMount when={subLinksOpen}>
|
||||
<SubLinksModal
|
||||
key={groupForAction.name}
|
||||
open
|
||||
group={groupForAction.name}
|
||||
subSettings={subSettings}
|
||||
onOpenChange={setSubLinksOpen}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
|
||||
<LazyMount when={adjustOpen}>
|
||||
<ClientBulkAdjustModal
|
||||
open={adjustOpen}
|
||||
count={groupEmails.length}
|
||||
onOpenChange={setAdjustOpen}
|
||||
onSubmit={async (addDays, addBytes, flow, limitHwid, adTag) => {
|
||||
const msg = await bulkAdjust(groupEmails, addDays, addBytes, flow, limitHwid, adTag);
|
||||
if (msg?.success) {
|
||||
const obj = msg.obj ?? { adjusted: 0 };
|
||||
messageApi.success(
|
||||
t('pages.groups.adjustSuccess', {
|
||||
count: obj.adjusted ?? 0,
|
||||
name: groupForAction?.name ?? '',
|
||||
}),
|
||||
{adjustOpen && adjustScope && (
|
||||
<LazyMount when={adjustOpen}>
|
||||
<ClientBulkAdjustModal
|
||||
open
|
||||
count={adjustScope.count}
|
||||
onOpenChange={setAdjustOpen}
|
||||
onSubmit={async (addDays, addBytes, flow, limitHwid, adTag, externalLinks) => {
|
||||
const { group, scopeToken } = adjustScope;
|
||||
const msg = await bulkAdjust(
|
||||
{ group, scopeToken },
|
||||
addDays,
|
||||
addBytes,
|
||||
flow,
|
||||
limitHwid,
|
||||
adTag,
|
||||
externalLinks,
|
||||
);
|
||||
return obj;
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
if (!msg?.success || !msg.obj) return null;
|
||||
messageApi.success(
|
||||
t('pages.groups.adjustSuccess', { count: msg.obj.adjusted, name: group }),
|
||||
);
|
||||
return msg.obj;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
|
||||
<LazyMount when={addClientsOpen}>
|
||||
<GroupAddClientsModal
|
||||
open={addClientsOpen}
|
||||
groupName={groupForAction?.name ?? null}
|
||||
candidates={allClients.filter((c) => c.group !== groupForAction?.name)}
|
||||
onClose={() => setAddClientsOpen(false)}
|
||||
onSubmit={async (emails) => {
|
||||
const msg = await bulkAddToGroup(emails, groupForAction?.name ?? '');
|
||||
if (msg?.success) {
|
||||
return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
|
||||
<LazyMount when={removeClientsOpen}>
|
||||
<GroupRemoveClientsModal
|
||||
open={removeClientsOpen}
|
||||
groupName={groupForAction?.name ?? null}
|
||||
members={allClients.filter((c) => c.group === groupForAction?.name)}
|
||||
onClose={() => setRemoveClientsOpen(false)}
|
||||
onSubmit={async (emails) => {
|
||||
const msg = await bulkRemoveFromGroup(emails);
|
||||
if (msg?.success) {
|
||||
return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
{(addClientsOpen || removeClientsOpen) && groupForAction && (
|
||||
<LazyMount when={addClientsOpen || removeClientsOpen}>
|
||||
<GroupClientsModal
|
||||
key={(addClientsOpen ? 'add:' : 'remove:') + groupForAction.name}
|
||||
mode={addClientsOpen ? 'add' : 'remove'}
|
||||
group={groupForAction.name}
|
||||
onClose={() => {
|
||||
setAddClientsOpen(false);
|
||||
setRemoveClientsOpen(false);
|
||||
}}
|
||||
onSubmit={async (selection) => {
|
||||
const group = groupForAction.name;
|
||||
const msg = addClientsOpen
|
||||
? await bulkAddToGroup(selection, group)
|
||||
: await bulkRemoveFromGroup({ group, selection });
|
||||
return msg?.success
|
||||
? ((msg.obj as { affected?: number } | undefined) ?? { affected: 0 })
|
||||
: null;
|
||||
}}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
</Layout>
|
||||
</ConfigProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
.host-address-tag-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.host-address-tag-button,
|
||||
.host-address-tag-editor {
|
||||
padding: 0 2px;
|
||||
border: 0;
|
||||
border-radius: 2px;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.host-address-tag-button {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.host-address-tag-button:first-child {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.host-address-tag-button:last-child {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.host-address-tag-button:focus-visible,
|
||||
.host-address-tag-editor:focus {
|
||||
outline: 2px solid var(--ant-color-primary);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.host-address-tag-editor {
|
||||
width: 24ch;
|
||||
max-width: 100%;
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { useCallback, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
||||
import type { ClipboardEvent, ComponentPropsWithRef, KeyboardEvent, MouseEvent, Ref } from 'react';
|
||||
import { CopyOutlined } from '@ant-design/icons';
|
||||
import { Select, message } from 'antd';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { selectTagRender } from '@/components/form';
|
||||
import { ClipboardManager } from '@/utils';
|
||||
import './HostAddressSelect.css';
|
||||
|
||||
type Props = Pick<
|
||||
ComponentPropsWithRef<typeof Select<string[]>>,
|
||||
'aria-describedby' | 'aria-invalid' | 'id' | 'onBlur' | 'options' | 'ref' | 'value'
|
||||
> & {
|
||||
onChange?: (value: string[]) => void;
|
||||
commitEditRef: Ref<() => boolean>;
|
||||
validateEdit: () => void;
|
||||
};
|
||||
|
||||
const separators = /[\s,;]+/u;
|
||||
|
||||
function keepFromSelect(event: MouseEvent) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
function keepKeyFromSelect(event: KeyboardEvent) {
|
||||
if (event.key !== 'Tab') event.stopPropagation();
|
||||
}
|
||||
|
||||
export default function HostAddressSelect({
|
||||
value,
|
||||
onChange,
|
||||
commitEditRef,
|
||||
validateEdit,
|
||||
...props
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const addresses = value ?? [];
|
||||
const [messageApi, messageContext] = message.useMessage();
|
||||
const [editing, setEditing] = useState<{ address: string; draft: string } | null>(null);
|
||||
const [search, setSearch] = useState('');
|
||||
const [open, setOpen] = useState(false);
|
||||
const editButtons = useRef(new Map<string, HTMLButtonElement>());
|
||||
const focusAfterEdit = useRef<string | null>(null);
|
||||
|
||||
const focusEditor = useCallback((input: HTMLInputElement | null) => {
|
||||
input?.focus();
|
||||
input?.select();
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (editing !== null || focusAfterEdit.current === null) return;
|
||||
editButtons.current.get(focusAfterEdit.current)?.focus();
|
||||
focusAfterEdit.current = null;
|
||||
}, [editing]);
|
||||
|
||||
function startEdit(address: string) {
|
||||
setOpen(false);
|
||||
setSearch('');
|
||||
setEditing({ address, draft: address });
|
||||
}
|
||||
|
||||
function finishEdit(address: string, restoreFocus: boolean) {
|
||||
if (restoreFocus) focusAfterEdit.current = address;
|
||||
setEditing(null);
|
||||
}
|
||||
|
||||
function commitEdit(restoreFocus: boolean): boolean {
|
||||
if (!editing) return true;
|
||||
const index = addresses.indexOf(editing.address);
|
||||
if (index < 0) {
|
||||
setEditing(null);
|
||||
return true;
|
||||
}
|
||||
const next = editing.draft.trim();
|
||||
if (!next || separators.test(next)) {
|
||||
messageApi.warning({
|
||||
key: 'host-address-edit',
|
||||
content: t('pages.hosts.addressActions.single'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if (next !== editing.address) {
|
||||
if (addresses.includes(next)) {
|
||||
messageApi.warning({
|
||||
key: 'host-address-edit',
|
||||
content: t('pages.hosts.addressActions.duplicate'),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
onChange?.(addresses.map((address, i) => (i === index ? next : address)));
|
||||
validateEdit();
|
||||
}
|
||||
finishEdit(next, restoreFocus);
|
||||
return true;
|
||||
}
|
||||
|
||||
useImperativeHandle(commitEditRef, () => () => commitEdit(false));
|
||||
|
||||
function editKeyDown(event: KeyboardEvent<HTMLInputElement>) {
|
||||
keepKeyFromSelect(event);
|
||||
if (!editing || event.nativeEvent.isComposing) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
finishEdit(editing.address, true);
|
||||
} else if (event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
commitEdit(true);
|
||||
}
|
||||
}
|
||||
|
||||
function pasteAddresses(event: ClipboardEvent<HTMLDivElement>) {
|
||||
const input = event.target;
|
||||
if (!(input instanceof HTMLInputElement) || input.getAttribute('role') !== 'combobox') return;
|
||||
const pasted = event.clipboardData.getData('text/plain');
|
||||
if (!pasted.trim()) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const start = input.selectionStart ?? input.value.length;
|
||||
const end = input.selectionEnd ?? start;
|
||||
const text = input.value.slice(0, start) + pasted + input.value.slice(end);
|
||||
const existing = new Set(addresses);
|
||||
const additions = [...new Set(text.split(separators))].filter(
|
||||
(address) => address && !existing.has(address),
|
||||
);
|
||||
if (additions.length > 0) onChange?.([...addresses, ...additions]);
|
||||
setSearch('');
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
async function copyAddress(address: string) {
|
||||
if (await ClipboardManager.copyText(address)) messageApi.success(t('copied'));
|
||||
else messageApi.error(t('somethingWentWrong'));
|
||||
}
|
||||
|
||||
return (
|
||||
<div onPasteCapture={pasteAddresses}>
|
||||
{messageContext}
|
||||
<Select<string[]>
|
||||
{...props}
|
||||
mode="tags"
|
||||
value={addresses}
|
||||
onChange={onChange}
|
||||
showSearch={{ searchValue: search, onSearch: setSearch }}
|
||||
open={editing ? false : open}
|
||||
onOpenChange={setOpen}
|
||||
tokenSeparators={[',', ';', ' ', '\t', '\r', '\n']}
|
||||
placeholder="cdn.example.com, cdn2.example.com:443"
|
||||
tagRender={(tag) => {
|
||||
if (tag.isMaxTag || tag.disabled) return selectTagRender(tag);
|
||||
const address = String(tag.value);
|
||||
const editLabel = t('pages.hosts.addressActions.edit', { address });
|
||||
return selectTagRender({
|
||||
...tag,
|
||||
label:
|
||||
editing?.address === address ? (
|
||||
<input
|
||||
className="host-address-tag-editor"
|
||||
type="text"
|
||||
dir="ltr"
|
||||
aria-label={editLabel}
|
||||
ref={focusEditor}
|
||||
value={editing.draft}
|
||||
onChange={(event) => setEditing({ address, draft: event.target.value })}
|
||||
onKeyDown={editKeyDown}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onBlur={() => commitEdit(false)}
|
||||
/>
|
||||
) : (
|
||||
<span className="host-address-tag-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="host-address-tag-button"
|
||||
aria-label={editLabel}
|
||||
title={editLabel}
|
||||
ref={(button) => {
|
||||
if (button) editButtons.current.set(address, button);
|
||||
else editButtons.current.delete(address);
|
||||
}}
|
||||
onMouseDown={keepFromSelect}
|
||||
onKeyDown={keepKeyFromSelect}
|
||||
onClick={(event) => {
|
||||
if (event.detail === 0) startEdit(address);
|
||||
}}
|
||||
onDoubleClick={() => startEdit(address)}
|
||||
>
|
||||
<bdi>{address}</bdi>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="host-address-tag-button"
|
||||
aria-label={t('pages.hosts.addressActions.copy', { address })}
|
||||
title={t('copy')}
|
||||
onMouseDown={keepFromSelect}
|
||||
onKeyDown={keepKeyFromSelect}
|
||||
onClick={() => void copyAddress(address)}
|
||||
>
|
||||
<CopyOutlined aria-hidden />
|
||||
</button>
|
||||
</span>
|
||||
),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
@@ -35,6 +35,7 @@ import { useNodesQuery } from '@/api/queries/useNodesQuery';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
import { catTabLabel } from '@/pages/settings/catTabLabel';
|
||||
import { withHostPort } from '@/lib/hosts/host-port';
|
||||
import HostAddressSelect from './HostAddressSelect';
|
||||
import { HostFinalMaskForm, HostMuxForm, HostSockoptForm } from './json-forms';
|
||||
|
||||
type FormShape = Omit<BulkAddHostValues, 'isDisabled'> & {
|
||||
@@ -100,7 +101,16 @@ function defaultsFor(host: HostRecord | null): FormShape {
|
||||
};
|
||||
}
|
||||
|
||||
export default function HostFormModal({
|
||||
export default function HostFormModal(props: HostFormModalProps) {
|
||||
const key = props.open ? (props.mode === 'add' ? 'add' : `edit:${props.host?.groupId}`) : null;
|
||||
const [session, setSession] = useState({ key, generation: 0 });
|
||||
if (key !== session.key) {
|
||||
setSession({ key, generation: session.generation + (key === null ? 0 : 1) });
|
||||
}
|
||||
return <HostFormSession key={session.generation} {...props} />;
|
||||
}
|
||||
|
||||
function HostFormSession({
|
||||
open,
|
||||
mode,
|
||||
host,
|
||||
@@ -111,9 +121,18 @@ export default function HostFormModal({
|
||||
}: HostFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const { isMobile } = useMediaQuery();
|
||||
const methods = useForm<FormShape>({ defaultValues: defaultsFor(host) });
|
||||
const methods = useForm<FormShape>({ defaultValues: defaultsFor(mode === 'edit' ? host : null) });
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const active = useRef(false);
|
||||
const commitAddressEdit = useRef<(() => boolean) | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
active.current = open;
|
||||
return () => {
|
||||
active.current = false;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const security = (useWatch({ control: methods.control, name: 'security' }) ?? 'same') as string;
|
||||
const fingerprint = (useWatch({ control: methods.control, name: 'fingerprint' }) ?? '') as string;
|
||||
@@ -130,18 +149,6 @@ export default function HostFormModal({
|
||||
const watchedHosts = useWatch({ control: methods.control, name: 'hosts' });
|
||||
const hasCidr = Boolean(watchedHosts?.some((h) => typeof h === 'string' && h.includes('/')));
|
||||
|
||||
// React resets this during render rather than in an effect so the modal's
|
||||
// first open frame already shows cleared fields.
|
||||
const openHost = open ? host : null;
|
||||
const [syncedHost, setSyncedHost] = useState(openHost);
|
||||
if (openHost !== syncedHost) {
|
||||
setSyncedHost(openHost);
|
||||
if (open) {
|
||||
methods.reset(defaultsFor(host));
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
const { nodes } = useNodesQuery();
|
||||
|
||||
const inboundSelectOptions = useMemo(
|
||||
@@ -219,6 +226,7 @@ export default function HostFormModal({
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await save(payload);
|
||||
if (!active.current) return;
|
||||
if (res?.success) {
|
||||
messageApi.success(
|
||||
t(mode === 'add' ? 'pages.hosts.toasts.add' : 'pages.hosts.toasts.update'),
|
||||
@@ -230,7 +238,7 @@ export default function HostFormModal({
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
if (active.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -238,7 +246,10 @@ export default function HostFormModal({
|
||||
<Modal
|
||||
open={open}
|
||||
title={t(mode === 'add' ? 'pages.hosts.addHost' : 'pages.hosts.editHost')}
|
||||
onOk={methods.handleSubmit(onFinish)}
|
||||
onOk={(event) => {
|
||||
if (commitAddressEdit.current?.() === false) return;
|
||||
void methods.handleSubmit(onFinish)(event);
|
||||
}}
|
||||
onCancel={() => onOpenChange(false)}
|
||||
confirmLoading={loading}
|
||||
okText={t('save')}
|
||||
@@ -302,12 +313,10 @@ export default function HostFormModal({
|
||||
tooltip={t('pages.hosts.hints.address')}
|
||||
rules={{ validate: rhfZodValidate(BulkAddHostSchema.shape.hosts) }}
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
tagRender={selectTagRender}
|
||||
<HostAddressSelect
|
||||
options={hostOptions}
|
||||
tokenSeparators={[',', ';', ' ']}
|
||||
placeholder="cdn.example.com, cdn2.example.com:443"
|
||||
commitEditRef={commitAddressEdit}
|
||||
validateEdit={() => void methods.trigger('hosts')}
|
||||
/>
|
||||
</FormField>
|
||||
{hasCidr && (
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useState } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect } from 'storybook/test';
|
||||
|
||||
import { keys } from '@/api/queryKeys';
|
||||
|
||||
import { useInbounds } from './useInbounds';
|
||||
|
||||
const meta = { title: 'Inbounds/Client rollup performance' } satisfies Meta;
|
||||
export default meta;
|
||||
|
||||
function Rollups() {
|
||||
const { dbInbounds, clientCount, applyTrafficEvent } = useInbounds();
|
||||
const [input, setInput] = useState('');
|
||||
return (
|
||||
<>
|
||||
<label>
|
||||
Filter
|
||||
<input value={input} onChange={(event) => setInput(event.target.value)} />
|
||||
</label>
|
||||
<p role="status">
|
||||
{clientCount[30]
|
||||
? 'Rollups ready'
|
||||
: dbInbounds.length
|
||||
? 'Calculating rollups'
|
||||
: 'Waiting for inbounds'}
|
||||
</p>
|
||||
<button
|
||||
onClick={() =>
|
||||
applyTrafficEvent({
|
||||
onlineByGuid: { node: ['client-3999@example.test'] },
|
||||
activeInbounds: { node: ['in-30'] },
|
||||
})
|
||||
}
|
||||
>
|
||||
Apply online update
|
||||
</button>
|
||||
<div>Last inbound online: {clientCount[30]?.online.length ?? '…'}</div>
|
||||
<div>First inbound online: {clientCount[1]?.online.length ?? '…'}</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Fixture() {
|
||||
const [queryClient] = useState(() => {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
client.setQueryData(keys.settings.defaults(), {});
|
||||
client.setQueryData(keys.inbounds.slim(), []);
|
||||
client.setQueryData(keys.clients.onlines(), []);
|
||||
client.setQueryData(keys.clients.onlinesByGuid(), {});
|
||||
client.setQueryData(keys.clients.activeInbounds(), {});
|
||||
client.setQueryData(keys.clients.lastOnline(), {});
|
||||
return client;
|
||||
});
|
||||
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<button
|
||||
onClick={() => {
|
||||
const clients = Array.from({ length: 4_000 }, (_, i) => ({
|
||||
email: 'client-' + i + '@example.test',
|
||||
enable: true,
|
||||
comment: 'shared client',
|
||||
}));
|
||||
const settings = JSON.stringify({ clients });
|
||||
queryClient.setQueryData(
|
||||
keys.inbounds.slim(),
|
||||
Array.from({ length: 30 }, (_, i) => ({
|
||||
id: i + 1,
|
||||
protocol: 'vless',
|
||||
enable: true,
|
||||
settings,
|
||||
originNodeGuid: 'node',
|
||||
tag: 'in-' + (i + 1),
|
||||
clientStats: clients.map(({ email }) => ({
|
||||
email,
|
||||
up: 1,
|
||||
down: 2,
|
||||
total: 0,
|
||||
expiryTime: 0,
|
||||
enable: true,
|
||||
})),
|
||||
})),
|
||||
);
|
||||
}}
|
||||
>
|
||||
Load 120,000 memberships
|
||||
</button>
|
||||
<Rollups />
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export const LargeDeployment: StoryObj<typeof meta> = {
|
||||
render: () => <Fixture />,
|
||||
play: async ({ canvas, userEvent }) => {
|
||||
const start = performance.now();
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Load 120,000 memberships' }));
|
||||
await userEvent.type(canvas.getByRole('textbox', { name: 'Filter' }), 'a');
|
||||
const responsiveAt = performance.now();
|
||||
await canvas.findByText('Rollups ready');
|
||||
const readyAt = performance.now();
|
||||
const updateAt = performance.now();
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Apply online update' }));
|
||||
await canvas.findByText('Last inbound online: 1');
|
||||
await expect(canvas.getByText('First inbound online: 0')).toBeVisible();
|
||||
await expect(canvas.getByRole('textbox', { name: 'Filter' })).toHaveValue('a');
|
||||
console.info('120,000 memberships (ms)', {
|
||||
input: Math.round(responsiveAt - start),
|
||||
initial: Math.round(readyAt - start),
|
||||
update: Math.round(performance.now() - updateAt),
|
||||
});
|
||||
},
|
||||
};
|
||||
@@ -50,7 +50,7 @@ import { InboundList } from './list';
|
||||
import { LazyMount } from '@/components/utility';
|
||||
const InboundFormModal = lazy(() => import('./form/InboundFormModal'));
|
||||
const CloneInboundModal = lazy(() => import('./CloneInboundModal'));
|
||||
const InboundInfoModal = lazy(() => import('./info/InboundInfoModal'));
|
||||
const InboundInfoModal = lazy(() => import('./info/PagedInboundInfoModal'));
|
||||
const AttachClientsModal = lazy(() => import('./clients/AttachClientsModal'));
|
||||
const AttachExistingClientsModal = lazy(() => import('./clients/AttachExistingClientsModal'));
|
||||
const DetachClientsModal = lazy(() => import('./clients/DetachClientsModal'));
|
||||
@@ -73,12 +73,6 @@ type RowAction =
|
||||
|
||||
type GeneralAction = 'import' | 'export' | 'subs' | 'resetInbounds';
|
||||
|
||||
interface ClientMatchTarget {
|
||||
id?: string;
|
||||
email?: string;
|
||||
password?: string;
|
||||
}
|
||||
|
||||
export default function InboundsPage() {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, antdThemeConfig } = useTheme();
|
||||
@@ -89,6 +83,7 @@ export default function InboundsPage() {
|
||||
fetchError,
|
||||
dbInbounds,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
onlineClients,
|
||||
lastOnlineMap,
|
||||
inboundSpeed,
|
||||
@@ -161,9 +156,10 @@ export default function InboundsPage() {
|
||||
const [formMode, setFormMode] = useState<'add' | 'edit'>('add');
|
||||
const [formDbInbound, setFormDbInbound] = useState<DBInbound | null>(null);
|
||||
|
||||
const [infoOpen, setInfoOpen] = useState(false);
|
||||
const [infoDbInbound, setInfoDbInbound] = useState<DBInbound | null>(null);
|
||||
const [infoClientIndex, setInfoClientIndex] = useState(0);
|
||||
const [infoTarget, setInfoTarget] = useState<{
|
||||
inbound: DBInbound;
|
||||
projectInbound: (detail: DBInbound) => DBInbound;
|
||||
} | null>(null);
|
||||
|
||||
const [attachOpen, setAttachOpen] = useState(false);
|
||||
const [attachSource, setAttachSource] = useState<DBInbound | null>(null);
|
||||
@@ -173,7 +169,7 @@ export default function InboundsPage() {
|
||||
const [detachSource, setDetachSource] = useState<DBInbound | null>(null);
|
||||
|
||||
const [groupOpen, setGroupOpen] = useState(false);
|
||||
const [groupSource, setGroupSource] = useState<DBInbound | null>(null);
|
||||
const [groupSourceID, setGroupSourceID] = useState<number | null>(null);
|
||||
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneSource, setCloneSource] = useState<DBInbound | null>(null);
|
||||
@@ -205,8 +201,8 @@ export default function InboundsPage() {
|
||||
);
|
||||
|
||||
const infoNodeAddress = useMemo(
|
||||
() => hostOverrideFor(infoDbInbound),
|
||||
[infoDbInbound, hostOverrideFor],
|
||||
() => hostOverrideFor(infoTarget?.inbound ?? null),
|
||||
[infoTarget, hostOverrideFor],
|
||||
);
|
||||
|
||||
const openText = useCallback(
|
||||
@@ -310,26 +306,6 @@ export default function InboundsPage() {
|
||||
[dbInbounds, projectChildThroughMaster],
|
||||
);
|
||||
|
||||
const findClientIndex = useCallback((dbInbound: DBInbound, client: ClientMatchTarget | null) => {
|
||||
if (!client) return 0;
|
||||
const settings = coerceInboundJsonField(dbInbound.settings) as {
|
||||
clients?: ClientMatchTarget[];
|
||||
};
|
||||
const clients = settings.clients || [];
|
||||
const idx = clients.findIndex((c) => {
|
||||
if (!c) return false;
|
||||
switch (dbInbound.protocol) {
|
||||
case 'trojan':
|
||||
case 'shadowsocks':
|
||||
case 'masque':
|
||||
return c.password === client.password && c.email === client.email;
|
||||
default:
|
||||
return c.id === client.id && c.email === client.email;
|
||||
}
|
||||
});
|
||||
return idx >= 0 ? idx : 0;
|
||||
}, []);
|
||||
|
||||
const exportInboundLinks = useCallback(
|
||||
(dbInbound: DBInbound) => {
|
||||
const projected = checkFallback(dbInbound);
|
||||
@@ -558,7 +534,8 @@ export default function InboundsPage() {
|
||||
|
||||
const confirmDelAllClients = useCallback(
|
||||
(dbInbound: DBInbound) => {
|
||||
const count = clientCount[dbInbound.id]?.clients || 0;
|
||||
const count = clientCount[dbInbound.id]?.clients;
|
||||
if (count === undefined || count === 0) return;
|
||||
modal.confirm({
|
||||
title: t('pages.inbounds.delAllClientsConfirmTitle', { remark: dbInbound.remark, count }),
|
||||
content: t('pages.inbounds.delAllClientsConfirmContent'),
|
||||
@@ -640,13 +617,11 @@ export default function InboundsPage() {
|
||||
// and then operate on the rehydrated record.
|
||||
const hydratingKeys: RowAction[] = [
|
||||
'edit',
|
||||
'showInfo',
|
||||
'export',
|
||||
'subs',
|
||||
'clipboard',
|
||||
'clone',
|
||||
'attachClients',
|
||||
'addToGroup',
|
||||
];
|
||||
let target = dbInbound;
|
||||
if (hydratingKeys.includes(key)) {
|
||||
@@ -658,9 +633,14 @@ export default function InboundsPage() {
|
||||
openEdit(target);
|
||||
break;
|
||||
case 'showInfo':
|
||||
setInfoDbInbound(checkFallback(target));
|
||||
setInfoClientIndex(findClientIndex(target, null));
|
||||
setInfoOpen(true);
|
||||
// Keep the fallback context for this open dialog across traffic pushes.
|
||||
setInfoTarget({
|
||||
inbound: target,
|
||||
projectInbound: (detail) => {
|
||||
detail.fallbackParent = target.fallbackParent;
|
||||
return checkFallback(detail);
|
||||
},
|
||||
});
|
||||
break;
|
||||
case 'export':
|
||||
exportInboundLinks(target);
|
||||
@@ -693,7 +673,7 @@ export default function InboundsPage() {
|
||||
setDetachOpen(true);
|
||||
break;
|
||||
case 'addToGroup':
|
||||
setGroupSource(target);
|
||||
setGroupSourceID(target.id);
|
||||
setGroupOpen(true);
|
||||
break;
|
||||
case 'clone':
|
||||
@@ -705,9 +685,8 @@ export default function InboundsPage() {
|
||||
},
|
||||
[
|
||||
hydrateInbound,
|
||||
openEdit,
|
||||
checkFallback,
|
||||
findClientIndex,
|
||||
openEdit,
|
||||
exportInboundLinks,
|
||||
exportInboundSubs,
|
||||
exportInboundClipboard,
|
||||
@@ -796,6 +775,7 @@ export default function InboundsPage() {
|
||||
<InboundList
|
||||
dbInbounds={dbInbounds}
|
||||
clientCount={clientCount}
|
||||
clientCountsPending={clientCountsPending}
|
||||
onlineClients={onlineClients}
|
||||
lastOnlineMap={lastOnlineMap}
|
||||
inboundSpeed={inboundSpeed}
|
||||
@@ -833,22 +813,25 @@ export default function InboundsPage() {
|
||||
availableNodesFetched={nodesFetched}
|
||||
/>
|
||||
</LazyMount>
|
||||
<LazyMount when={infoOpen}>
|
||||
<InboundInfoModal
|
||||
open={infoOpen}
|
||||
onClose={() => setInfoOpen(false)}
|
||||
dbInbound={infoDbInbound}
|
||||
clientIndex={infoClientIndex}
|
||||
expireDiff={expireDiff}
|
||||
trafficDiff={trafficDiff}
|
||||
ipLimitEnable={ipLimitEnable}
|
||||
tgBotEnable={tgBotEnable}
|
||||
subSettings={subSettings}
|
||||
hosts={hosts}
|
||||
lastOnlineMap={lastOnlineMap}
|
||||
nodeAddress={infoNodeAddress}
|
||||
/>
|
||||
</LazyMount>
|
||||
{infoTarget && (
|
||||
<LazyMount when>
|
||||
<InboundInfoModal
|
||||
open
|
||||
onClose={() => setInfoTarget(null)}
|
||||
key={infoTarget.inbound.id}
|
||||
inboundID={infoTarget.inbound.id}
|
||||
projectInbound={infoTarget.projectInbound}
|
||||
expireDiff={expireDiff}
|
||||
trafficDiff={trafficDiff}
|
||||
ipLimitEnable={ipLimitEnable}
|
||||
tgBotEnable={tgBotEnable}
|
||||
subSettings={subSettings}
|
||||
hosts={hosts}
|
||||
lastOnlineMap={lastOnlineMap}
|
||||
nodeAddress={infoNodeAddress}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
<LazyMount when={attachOpen}>
|
||||
<AttachClientsModal
|
||||
open={attachOpen}
|
||||
@@ -874,14 +857,17 @@ export default function InboundsPage() {
|
||||
source={detachSource}
|
||||
/>
|
||||
</LazyMount>
|
||||
<LazyMount when={groupOpen}>
|
||||
<AddClientsToGroupModal
|
||||
open={groupOpen}
|
||||
onClose={() => setGroupOpen(false)}
|
||||
onAdded={refresh}
|
||||
source={groupSource}
|
||||
/>
|
||||
</LazyMount>
|
||||
{groupSourceID !== null && (
|
||||
<LazyMount when={groupOpen}>
|
||||
<AddClientsToGroupModal
|
||||
open={groupOpen}
|
||||
onClose={() => setGroupOpen(false)}
|
||||
onAdded={refresh}
|
||||
inboundId={groupSourceID}
|
||||
count={clientCount[groupSourceID]?.clients ?? 0}
|
||||
/>
|
||||
</LazyMount>
|
||||
)}
|
||||
<LazyMount when={cloneOpen}>
|
||||
<CloneInboundModal
|
||||
open={cloneOpen}
|
||||
|
||||
@@ -1,64 +1,60 @@
|
||||
import { lazy, useEffect, useMemo, useState } from 'react';
|
||||
import { lazy } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { GroupSummaryListSchema } from '@/schemas/client';
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound';
|
||||
import { parseMsg } from '@/utils/zodValidate';
|
||||
|
||||
const BulkAddToGroupModal = lazy(() => import('@/pages/clients/BulkAddToGroupModal'));
|
||||
|
||||
interface AddClientsToGroupModalProps {
|
||||
open: boolean;
|
||||
source: DBInbound | null;
|
||||
inboundId: number;
|
||||
count: number;
|
||||
onClose: () => void;
|
||||
onAdded?: () => void;
|
||||
}
|
||||
|
||||
function readClientEmails(settings: unknown): string[] {
|
||||
const parsed = coerceInboundJsonField(settings) as { clients?: Array<{ email?: string }> };
|
||||
const clients = Array.isArray(parsed?.clients) ? parsed.clients : [];
|
||||
return clients.map((c) => (c?.email || '').trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
export default function AddClientsToGroupModal({
|
||||
open,
|
||||
source,
|
||||
inboundId,
|
||||
count,
|
||||
onClose,
|
||||
onAdded,
|
||||
}: AddClientsToGroupModalProps) {
|
||||
const [groups, setGroups] = useState<string[]>([]);
|
||||
|
||||
const emails = useMemo(() => (source ? readClientEmails(source.settings) : []), [source]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const msg = await HttpUtil.get('/panel/api/clients/groups', undefined, { silent: true });
|
||||
if (cancelled) return;
|
||||
const list = Array.isArray(msg?.obj) ? (msg.obj as Array<{ name?: string }>) : [];
|
||||
setGroups(list.map((g) => g?.name || '').filter(Boolean));
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const groups = useQuery({
|
||||
queryKey: keys.clients.groups(),
|
||||
enabled: open,
|
||||
queryFn: async ({ signal }) => {
|
||||
const response = await HttpUtil.get('/panel/api/clients/groups', undefined, {
|
||||
signal,
|
||||
silent: true,
|
||||
});
|
||||
const result = parseMsg(response, GroupSummaryListSchema, 'clients/groups');
|
||||
if (!result.success) throw new Error(result.msg);
|
||||
return result.obj ?? [];
|
||||
},
|
||||
});
|
||||
return (
|
||||
<BulkAddToGroupModal
|
||||
open={open}
|
||||
count={emails.length}
|
||||
groups={groups}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) onClose();
|
||||
count={count}
|
||||
groups={groups.data?.map((group) => group.name) ?? []}
|
||||
onOpenChange={(value) => {
|
||||
if (!value) onClose();
|
||||
}}
|
||||
onSubmit={async (group) => {
|
||||
const msg = await HttpUtil.post(
|
||||
const response = await HttpUtil.post<{ affected?: number }>(
|
||||
'/panel/api/clients/groups/bulkAdd',
|
||||
{ emails, group },
|
||||
{ inboundId, group },
|
||||
{ headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
if (!msg?.success) return null;
|
||||
if (!response?.success) return null;
|
||||
void queryClient.invalidateQueries({ queryKey: keys.clients.root() });
|
||||
onAdded?.();
|
||||
return (msg.obj as { affected?: number } | undefined) ?? { affected: 0 };
|
||||
return response.obj ?? { affected: 0 };
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, waitFor, within } from 'storybook/test';
|
||||
import { DBInbound } from '@/models/dbinbound';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import DetachClientsModal from './DetachClientsModal';
|
||||
|
||||
function Fixture({ population }: { population: number }) {
|
||||
const source = new DBInbound({
|
||||
id: population,
|
||||
tag: 'large-inbound',
|
||||
protocol: 'vless',
|
||||
settings: JSON.stringify({
|
||||
clients: Array.from({ length: population }, (_, i) => ({
|
||||
email: 'client-' + (i + 1) + '@test',
|
||||
})),
|
||||
}),
|
||||
});
|
||||
return <DetachClientsModal open source={source} onClose={() => {}} />;
|
||||
}
|
||||
|
||||
const meta = { title: 'Inbounds/Detach Clients', component: Fixture } satisfies Meta<
|
||||
typeof Fixture
|
||||
>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
function largeInbound(population: number): Story {
|
||||
let submitted: unknown;
|
||||
let openedAt = 0;
|
||||
let longTasks: number[] = [];
|
||||
return {
|
||||
args: { population },
|
||||
beforeEach: () => {
|
||||
const { get, post } = HttpUtil;
|
||||
submitted = undefined;
|
||||
openedAt = performance.now();
|
||||
longTasks = [];
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
for (const task of list.getEntries()) longTasks.push(task.duration);
|
||||
});
|
||||
if (PerformanceObserver.supportedEntryTypes.includes('longtask')) {
|
||||
observer.observe({ entryTypes: ['longtask'] });
|
||||
}
|
||||
HttpUtil.get = async <T,>(url: string, params?: unknown) => {
|
||||
if (url.endsWith('/fixture-job')) {
|
||||
return new Msg<T>(true, '', {
|
||||
running: false,
|
||||
processed: population - 1,
|
||||
total: population - 1,
|
||||
result: { detached: population - 1, skipped: 0, errors: 0 },
|
||||
} as T);
|
||||
}
|
||||
const { page, search, scopeToken } = params as {
|
||||
page: number;
|
||||
search: string;
|
||||
scopeToken?: string;
|
||||
};
|
||||
const ids =
|
||||
search === 'client-101@test'
|
||||
? [101]
|
||||
: Array.from({ length: 100 }, (_, i) => (page - 1) * 100 + i + 1);
|
||||
return new Msg<T>(true, '', {
|
||||
items: ids.map((id) => ({
|
||||
id,
|
||||
email: 'client-' + id + '@test',
|
||||
enable: true,
|
||||
inScope: Boolean(scopeToken),
|
||||
})),
|
||||
total: search ? 1 : population,
|
||||
attached: population,
|
||||
} as T);
|
||||
};
|
||||
HttpUtil.post = async <T,>(url: string, payload?: unknown) => {
|
||||
if (url.endsWith('/freeze')) {
|
||||
return new Msg<T>(true, '', { scopeToken: 'fixture-scope', total: population } as T);
|
||||
}
|
||||
submitted = payload;
|
||||
return new Msg<T>(true, '', { jobId: 'fixture-job' } as T);
|
||||
};
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
HttpUtil.get = get;
|
||||
HttpUtil.post = post;
|
||||
};
|
||||
},
|
||||
play: async ({ canvasElement, userEvent }) => {
|
||||
const screen = within(canvasElement.ownerDocument.body);
|
||||
const first = await screen.findByRole('checkbox', { name: 'client-1@test' });
|
||||
const openMs = performance.now() - openedAt;
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
const rendered = dialog.querySelectorAll('[data-row-key]').length;
|
||||
await expect(rendered).toBeGreaterThan(0);
|
||||
await expect(rendered).toBeLessThanOrEqual(100);
|
||||
const toggleStart = performance.now();
|
||||
await userEvent.click(first);
|
||||
await expect(first).toBeChecked();
|
||||
const toggleMs = performance.now() - toggleStart;
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Select this page' }));
|
||||
await expect(screen.getByText('100 selected')).toBeVisible();
|
||||
|
||||
await userEvent.click(screen.getByText('2', { exact: true }));
|
||||
await screen.findByRole('checkbox', { name: 'client-101@test' });
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Select all attached clients' }));
|
||||
const row = () => screen.getByRole('checkbox', { name: 'client-101@test' });
|
||||
await waitFor(() => expect(row()).toBeChecked());
|
||||
await userEvent.click(row());
|
||||
|
||||
const searchStart = performance.now();
|
||||
await userEvent.type(screen.getByRole('searchbox', { name: 'Search' }), 'client-101@test');
|
||||
await waitFor(() => expect(row()).not.toBeChecked());
|
||||
const searchMs = performance.now() - searchStart;
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Detach Clients' }));
|
||||
await waitFor(() =>
|
||||
expect(submitted).toEqual({
|
||||
requestId: expect.any(String),
|
||||
inboundIds: [population],
|
||||
selection: { mode: 'allMatching', scopeToken: 'fixture-scope', excludedClientIds: [101] },
|
||||
}),
|
||||
);
|
||||
console.info('Detach picker', {
|
||||
population,
|
||||
rendered,
|
||||
openMs,
|
||||
toggleMs,
|
||||
searchMs,
|
||||
longestTaskMs: Math.max(0, ...longTasks),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const Thousand = largeInbound(1_000);
|
||||
export const TenThousand = largeInbound(10_000);
|
||||
export const FiftyThousand = largeInbound(50_000);
|
||||
@@ -1,10 +1,32 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Input, Modal, Space, Table, Tag, Typography, message } from 'antd';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Input,
|
||||
Modal,
|
||||
Pagination,
|
||||
Progress,
|
||||
Space,
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound';
|
||||
import type {
|
||||
DetachCandidate as ClientRow,
|
||||
DetachCandidatePage as CandidatePage,
|
||||
DetachJobStatus as JobStatus,
|
||||
DetachScopeSummary as FrozenSelection,
|
||||
} from '@/generated/types';
|
||||
import { HttpUtil, PromiseUtil, RandomUtil } from '@/utils';
|
||||
import type { DBInbound } from '@/models/dbinbound';
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
const CANDIDATES = '/panel/api/clients/detachCandidates';
|
||||
const DETACH = '/panel/api/clients/bulkDetach';
|
||||
|
||||
interface DetachClientsModalProps {
|
||||
open: boolean;
|
||||
@@ -13,175 +35,392 @@ interface DetachClientsModalProps {
|
||||
onDetached?: () => void;
|
||||
}
|
||||
|
||||
interface BulkDetachResult {
|
||||
detached?: string[];
|
||||
skipped?: string[];
|
||||
errors?: string[];
|
||||
}
|
||||
|
||||
interface ClientRow {
|
||||
email: string;
|
||||
comment: string;
|
||||
enable: boolean;
|
||||
}
|
||||
|
||||
function readClientRows(settings: unknown): ClientRow[] {
|
||||
const parsed = coerceInboundJsonField(settings) as {
|
||||
clients?: Array<{ email?: string; comment?: string; enable?: boolean }>;
|
||||
};
|
||||
const clients = Array.isArray(parsed?.clients) ? parsed.clients : [];
|
||||
return clients
|
||||
.map((c) => ({
|
||||
email: (c?.email || '').trim(),
|
||||
comment: (c?.comment || '').trim(),
|
||||
enable: c?.enable !== false,
|
||||
}))
|
||||
.filter((r) => r.email);
|
||||
}
|
||||
|
||||
export default function DetachClientsModal({
|
||||
open,
|
||||
source,
|
||||
...callbacks
|
||||
}: DetachClientsModalProps) {
|
||||
if (!open || !source) return null;
|
||||
return <DetachClientPicker key={source.id} id={source.id} tag={source.tag} {...callbacks} />;
|
||||
}
|
||||
|
||||
function DetachClientPicker({
|
||||
id,
|
||||
tag,
|
||||
onClose,
|
||||
onDetached,
|
||||
}: DetachClientsModalProps) {
|
||||
}: Pick<DetachClientsModalProps, 'onClose' | 'onDetached'> & { id: number; tag: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [clientRows, setClientRows] = useState<ClientRow[]>([]);
|
||||
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
|
||||
const [messages, holder] = message.useMessage();
|
||||
const [search, setSearch] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const [rows, setRows] = useState<CandidatePage>();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [busy, setBusy] = useState<'freeze' | 'submit'>();
|
||||
const [frozen, setFrozen] = useState<FrozenSelection>();
|
||||
const [choices, setChoices] = useState(new Map<number, string>());
|
||||
const [exclusionPage, setExclusionPage] = useState(1);
|
||||
const [jobId, setJobId] = useState<string>();
|
||||
const [progress, setProgress] = useState<JobStatus>();
|
||||
const action = useRef<AbortController | undefined>(undefined);
|
||||
const requestId = useRef<string | undefined>(undefined);
|
||||
const scopeToken = frozen?.scopeToken;
|
||||
const selected = frozen ? frozen.total - choices.size : choices.size;
|
||||
const locked = Boolean(busy || jobId);
|
||||
const pageRows = rows?.items ?? [];
|
||||
|
||||
// Reset during render, not in an effect, so the first frame is already clean.
|
||||
const openSource = open ? source : null;
|
||||
const [syncedSource, setSyncedSource] = useState<DBInbound | null>(null);
|
||||
if (openSource !== syncedSource) {
|
||||
setSyncedSource(openSource);
|
||||
if (openSource) {
|
||||
setClientRows(readClientRows(openSource.settings));
|
||||
setSelectedEmails([]);
|
||||
setSearch('');
|
||||
}
|
||||
useEffect(() => () => action.current?.abort(), []);
|
||||
|
||||
useEffect(() => {
|
||||
const request = new AbortController();
|
||||
const timer = window.setTimeout(
|
||||
async () => {
|
||||
const response = await HttpUtil.get<CandidatePage>(
|
||||
CANDIDATES,
|
||||
{ inboundId: id, page, search, scopeToken },
|
||||
{ signal: request.signal, silent: true },
|
||||
);
|
||||
if (request.signal.aborted) return;
|
||||
if (response?.success && response.obj) {
|
||||
const lastPage = Math.max(1, Math.ceil(response.obj.total / PAGE_SIZE));
|
||||
if (page > lastPage) {
|
||||
setPage(lastPage);
|
||||
return;
|
||||
}
|
||||
setRows(response.obj);
|
||||
setLoadError('');
|
||||
} else {
|
||||
setRows(undefined);
|
||||
setLoadError(response?.msg || t('somethingWentWrong'));
|
||||
}
|
||||
setLoading(false);
|
||||
},
|
||||
search.trim() ? 220 : 0,
|
||||
);
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
request.abort();
|
||||
};
|
||||
}, [id, page, search, scopeToken, retry, t]);
|
||||
|
||||
function reloadPage() {
|
||||
setRows((previous) => (previous ? { ...previous, items: [] } : undefined));
|
||||
setLoadError('');
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
const q = search.trim().toLowerCase();
|
||||
if (!q) return clientRows;
|
||||
return clientRows.filter(
|
||||
(r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q),
|
||||
);
|
||||
}, [clientRows, search]);
|
||||
function changeSelection(next: Map<number, string>) {
|
||||
setChoices(next);
|
||||
setExclusionPage((current) => Math.min(current, Math.max(1, Math.ceil(next.size / 10))));
|
||||
requestId.current = undefined;
|
||||
}
|
||||
|
||||
const columns: ColumnsType<ClientRow> = useMemo(
|
||||
() => [
|
||||
{
|
||||
title: t('pages.inbounds.email'),
|
||||
dataIndex: 'email',
|
||||
key: 'email',
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: t('comment'),
|
||||
dataIndex: 'comment',
|
||||
key: 'comment',
|
||||
ellipsis: true,
|
||||
},
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
key: 'enable',
|
||||
width: 90,
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? (
|
||||
<Tag color="success">{t('enable')}</Tag>
|
||||
) : (
|
||||
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
|
||||
),
|
||||
},
|
||||
],
|
||||
[t],
|
||||
);
|
||||
function clearSelection() {
|
||||
if (frozen) reloadPage();
|
||||
setFrozen(undefined);
|
||||
changeSelection(new Map());
|
||||
setExclusionPage(1);
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!source || selectedEmails.length === 0) return;
|
||||
setSaving(true);
|
||||
function pickPage(keys: React.Key[]) {
|
||||
const checked = new Set(keys);
|
||||
const next = new Map(choices);
|
||||
for (const row of pageRows) {
|
||||
if (frozen && !row.inScope) continue;
|
||||
if (checked.has(row.id) !== Boolean(frozen)) next.set(row.id, row.email);
|
||||
else next.delete(row.id);
|
||||
}
|
||||
changeSelection(next);
|
||||
}
|
||||
|
||||
async function freeze() {
|
||||
if (action.current || locked) return;
|
||||
const operation = new AbortController();
|
||||
action.current = operation;
|
||||
setBusy('freeze');
|
||||
try {
|
||||
const msg = await HttpUtil.post(
|
||||
'/panel/api/clients/bulkDetach',
|
||||
{ emails: selectedEmails, inboundIds: [source.id] },
|
||||
{ headers: { 'Content-Type': 'application/json' } },
|
||||
const response = await HttpUtil.post<FrozenSelection>(
|
||||
CANDIDATES + '/freeze',
|
||||
{ inboundId: id },
|
||||
{ signal: operation.signal, silent: true },
|
||||
);
|
||||
if (!msg?.success) {
|
||||
messageApi.error(msg?.msg || t('somethingWentWrong'));
|
||||
if (operation.signal.aborted) return;
|
||||
if (!response?.success || !response.obj?.scopeToken) {
|
||||
messages.error(response?.msg || t('somethingWentWrong'));
|
||||
return;
|
||||
}
|
||||
const result = (msg.obj || {}) as BulkDetachResult;
|
||||
const detached = result.detached?.length ?? 0;
|
||||
const skipped = result.skipped?.length ?? 0;
|
||||
const errors = result.errors?.length ?? 0;
|
||||
if (errors > 0) {
|
||||
messageApi.warning(
|
||||
t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }),
|
||||
);
|
||||
} else {
|
||||
messageApi.success(t('pages.inbounds.detachClientsResult', { detached, skipped }));
|
||||
}
|
||||
onDetached?.();
|
||||
onClose();
|
||||
reloadPage();
|
||||
changeSelection(new Map());
|
||||
setExclusionPage(1);
|
||||
setFrozen(response.obj);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
action.current = undefined;
|
||||
if (!operation.signal.aborted) setBusy(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (action.current || (!jobId && selected <= 0)) return;
|
||||
const operation = new AbortController();
|
||||
action.current = operation;
|
||||
setBusy('submit');
|
||||
try {
|
||||
let job = jobId;
|
||||
if (!job) {
|
||||
const selection = frozen
|
||||
? {
|
||||
mode: 'allMatching',
|
||||
scopeToken: frozen.scopeToken,
|
||||
excludedClientIds: [...choices.keys()],
|
||||
}
|
||||
: { mode: 'explicit', clientIds: [...choices.keys()] };
|
||||
requestId.current ??= RandomUtil.randomUUID();
|
||||
const response = await HttpUtil.post<{ jobId: string }>(
|
||||
DETACH,
|
||||
{ inboundIds: [id], selection, requestId: requestId.current },
|
||||
{ signal: operation.signal, silent: true },
|
||||
);
|
||||
if (operation.signal.aborted) return;
|
||||
if (!response?.success || !response.obj?.jobId) {
|
||||
messages.error(response?.msg || t('somethingWentWrong'));
|
||||
return;
|
||||
}
|
||||
job = response.obj.jobId;
|
||||
setJobId(job);
|
||||
}
|
||||
|
||||
let failures = 0;
|
||||
const deadline = Date.now() + 6 * 60_000;
|
||||
while (!operation.signal.aborted && Date.now() < deadline) {
|
||||
const response = await HttpUtil.get<JobStatus>(
|
||||
DETACH + '/' + encodeURIComponent(job),
|
||||
undefined,
|
||||
{ signal: operation.signal, silent: true },
|
||||
);
|
||||
if (operation.signal.aborted) return;
|
||||
if (!response?.success || !response.obj) {
|
||||
if (++failures >= 3) {
|
||||
messages.error(response?.msg || t('somethingWentWrong'));
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
failures = 0;
|
||||
const status = response.obj;
|
||||
setProgress(status);
|
||||
if (!status.running) {
|
||||
setJobId(undefined);
|
||||
requestId.current = undefined;
|
||||
if (status.error && status.result?.detached) {
|
||||
messages.warning(status.error);
|
||||
onDetached?.();
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
if (status.result) {
|
||||
const { detached, skipped, errors, nodePending } = status.result;
|
||||
if (errors > 0)
|
||||
messages.warning(
|
||||
t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }),
|
||||
);
|
||||
else messages.success(t('pages.inbounds.detachClientsResult', { detached, skipped }));
|
||||
if (nodePending) messages.warning(t('pages.inbounds.detachNodePending'));
|
||||
}
|
||||
if (status.error || !status.result) {
|
||||
messages.error(status.error || t('somethingWentWrong'));
|
||||
return;
|
||||
}
|
||||
onDetached?.();
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
}
|
||||
await PromiseUtil.sleep(750);
|
||||
}
|
||||
if (!operation.signal.aborted) messages.error(t('somethingWentWrong'));
|
||||
} finally {
|
||||
action.current = undefined;
|
||||
if (!operation.signal.aborted) setBusy(undefined);
|
||||
}
|
||||
}
|
||||
|
||||
const columns: ColumnsType<ClientRow> = [
|
||||
{ title: t('pages.inbounds.email'), dataIndex: 'email', ellipsis: true },
|
||||
{ title: t('comment'), dataIndex: 'comment', ellipsis: true },
|
||||
{
|
||||
title: t('enable'),
|
||||
dataIndex: 'enable',
|
||||
width: 90,
|
||||
render: (enabled: boolean) =>
|
||||
enabled ? (
|
||||
<Tag color="success">{t('enable')}</Tag>
|
||||
) : (
|
||||
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
|
||||
),
|
||||
},
|
||||
];
|
||||
const selectedKeys = pageRows
|
||||
.filter((row) => (frozen ? row.inScope && !choices.has(row.id) : choices.has(row.id)))
|
||||
.map((row) => row.id);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onCancel={onClose}
|
||||
open
|
||||
onCancel={() => {
|
||||
if (!busy) onClose();
|
||||
}}
|
||||
onOk={submit}
|
||||
okButtonProps={{
|
||||
danger: true,
|
||||
disabled: selectedEmails.length === 0,
|
||||
loading: saving,
|
||||
disabled: busy === 'freeze' || (!jobId && selected <= 0),
|
||||
loading: busy === 'submit',
|
||||
}}
|
||||
okText={t('pages.inbounds.detachClients')}
|
||||
cancelButtonProps={{ disabled: Boolean(busy) }}
|
||||
okText={t(jobId ? 'refresh' : 'pages.inbounds.detachClients')}
|
||||
cancelText={t('cancel')}
|
||||
title={t('pages.inbounds.detachClientsTitle', { remark: source?.tag ?? '' })}
|
||||
title={t('pages.inbounds.detachClientsTitle', { remark: tag })}
|
||||
width={680}
|
||||
>
|
||||
{messageContextHolder}
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t('pages.inbounds.detachClientsDesc', { count: clientRows.length })}
|
||||
</Typography.Paragraph>
|
||||
|
||||
{holder}
|
||||
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
|
||||
<Typography.Text strong>{t('pages.inbounds.detachClientsSelectLabel')}</Typography.Text>
|
||||
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
|
||||
<Input.Search
|
||||
allowClear
|
||||
aria-label={t('search')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
style={{ maxWidth: 320 }}
|
||||
{rows && (
|
||||
<Typography.Paragraph type="secondary">
|
||||
{t('pages.inbounds.detachClientsDesc', { count: rows.attached })}
|
||||
</Typography.Paragraph>
|
||||
)}
|
||||
<Input.Search
|
||||
allowClear
|
||||
aria-label={t('search')}
|
||||
disabled={locked}
|
||||
maxLength={128}
|
||||
value={search}
|
||||
onChange={(event) => {
|
||||
reloadPage();
|
||||
setPage(1);
|
||||
setSearch(event.target.value);
|
||||
}}
|
||||
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
|
||||
/>
|
||||
{loadError && (
|
||||
<Alert
|
||||
type="error"
|
||||
title={loadError}
|
||||
action={
|
||||
<Button
|
||||
size="small"
|
||||
onClick={() => {
|
||||
reloadPage();
|
||||
setRetry(retry + 1);
|
||||
}}
|
||||
>
|
||||
{t('refresh')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<Typography.Text type="secondary">
|
||||
{t('pages.inbounds.attachClientsSelectedCount', {
|
||||
selected: selectedEmails.length,
|
||||
total: clientRows.length,
|
||||
})}
|
||||
)}
|
||||
<Space wrap>
|
||||
<Button
|
||||
disabled={locked || loading || !pageRows.some((row) => !frozen || row.inScope)}
|
||||
onClick={() => pickPage(pageRows.map((row) => row.id))}
|
||||
>
|
||||
{t('pages.inbounds.attachSelectPage')}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={locked || loading || Boolean(frozen) || !rows?.attached}
|
||||
onClick={freeze}
|
||||
loading={busy === 'freeze'}
|
||||
>
|
||||
{t('pages.inbounds.detachSelectAll')}
|
||||
</Button>
|
||||
<Button disabled={locked || (!frozen && !choices.size)} onClick={clearSelection}>
|
||||
{t('pages.inbounds.attachClearSelection')}
|
||||
</Button>
|
||||
<Typography.Text aria-live="polite">
|
||||
{t('pages.inbounds.selectedCount', { count: selected })}
|
||||
</Typography.Text>
|
||||
</Space>
|
||||
{frozen && choices.size > 0 && (
|
||||
<details>
|
||||
<summary>
|
||||
{t('pages.inbounds.attachExcludedClients')} ({choices.size})
|
||||
</summary>
|
||||
{Array.from(choices)
|
||||
.slice((exclusionPage - 1) * 10, exclusionPage * 10)
|
||||
.map(([clientId, email]) => (
|
||||
<Button
|
||||
key={clientId}
|
||||
size="small"
|
||||
disabled={locked}
|
||||
onClick={() => {
|
||||
const next = new Map(choices);
|
||||
next.delete(clientId);
|
||||
changeSelection(next);
|
||||
}}
|
||||
>
|
||||
{t('pages.inbounds.attachRestoreClient', { email })}
|
||||
</Button>
|
||||
))}
|
||||
<Pagination
|
||||
size="small"
|
||||
current={exclusionPage}
|
||||
pageSize={10}
|
||||
total={choices.size}
|
||||
hideOnSinglePage
|
||||
showSizeChanger={false}
|
||||
onChange={setExclusionPage}
|
||||
/>
|
||||
</details>
|
||||
)}
|
||||
{progress && (
|
||||
<Progress
|
||||
aria-label={t('pages.inbounds.detachClients')}
|
||||
percent={Math.floor((progress.processed * 100) / Math.max(1, progress.total))}
|
||||
status={progress.error ? 'exception' : progress.running ? 'active' : 'success'}
|
||||
/>
|
||||
)}
|
||||
<Table<ClientRow>
|
||||
size="small"
|
||||
rowKey="email"
|
||||
rowKey="id"
|
||||
columns={columns}
|
||||
dataSource={filteredRows}
|
||||
dataSource={pageRows}
|
||||
loading={loading}
|
||||
pagination={false}
|
||||
scroll={{ y: 280 }}
|
||||
virtual
|
||||
scroll={{ x: 540, y: 280 }}
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedEmails,
|
||||
onChange: (keys) => setSelectedEmails(keys as string[]),
|
||||
preserveSelectedRowKeys: true,
|
||||
hideSelectAll: true,
|
||||
columnTitle: (
|
||||
<span
|
||||
style={{
|
||||
position: 'absolute',
|
||||
width: 1,
|
||||
height: 1,
|
||||
overflow: 'hidden',
|
||||
clipPath: 'inset(50%)',
|
||||
}}
|
||||
>
|
||||
{t('pages.inbounds.detachClientsSelectLabel')}
|
||||
</span>
|
||||
),
|
||||
selectedRowKeys: selectedKeys,
|
||||
getCheckboxProps: (row) => ({
|
||||
disabled: locked || Boolean(frozen && !row.inScope),
|
||||
'aria-label': row.email,
|
||||
}),
|
||||
onChange: pickPage,
|
||||
}}
|
||||
/>
|
||||
<Pagination
|
||||
current={page}
|
||||
pageSize={PAGE_SIZE}
|
||||
total={rows?.total ?? 0}
|
||||
showSizeChanger={false}
|
||||
disabled={locked || loading}
|
||||
onChange={(next) => {
|
||||
reloadPage();
|
||||
setPage(next);
|
||||
}}
|
||||
/>
|
||||
</Space>
|
||||
|
||||
@@ -199,3 +199,7 @@
|
||||
background: color-mix(in srgb, var(--ant-color-primary) 12%, transparent);
|
||||
text-decoration-color: var(--ant-color-primary);
|
||||
}
|
||||
|
||||
.inbound-info-tabs .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
|
||||
color: var(--ant-color-text);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,15 @@
|
||||
import { Fragment, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Divider, Modal, Space, Tabs, Tag, Tooltip } from 'antd';
|
||||
import { Button, Divider, Modal, Space, Spin, Tabs, Tag, Tooltip } from 'antd';
|
||||
import { CopyOutlined, SyncOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
|
||||
|
||||
import { HttpUtil, IntlUtil, SizeFormatter, ColorUtils, Wireguard } from '@/utils';
|
||||
import { HttpUtil, IntlUtil, SizeFormatter, ColorUtils } from '@/utils';
|
||||
import { activateOnKey } from '@/utils/a11y';
|
||||
import { Protocols } from '@/schemas/primitives';
|
||||
import { InfinityIcon } from '@/components/ui';
|
||||
import { useDatepicker } from '@/hooks/useDatepicker';
|
||||
import {
|
||||
genAllLinks,
|
||||
genAmneziaWGPeerConfigs,
|
||||
genAmneziaWGPeerLinks,
|
||||
genWireguardPeerConfigs,
|
||||
genWireguardPeerLinks,
|
||||
preferPublicHost,
|
||||
} from '@/lib/xray/inbound-link';
|
||||
import { inboundFromDb } from '@/lib/xray/inbound-from-db';
|
||||
import { hostLinksClosed, withHostEndpoints } from '@/lib/hosts/host-link';
|
||||
import { genAllLinks, wireguardServerPublicKey } from '@/lib/xray/inbound-link';
|
||||
import { infoLinkInput, tunnelInfoOutputs } from './peerLinks';
|
||||
|
||||
import {
|
||||
buildInboundInfo,
|
||||
@@ -38,6 +30,10 @@ export default function InboundInfoModal({
|
||||
onClose,
|
||||
dbInbound,
|
||||
clientIndex = 0,
|
||||
peerOffset = 0,
|
||||
peerTools,
|
||||
feedback,
|
||||
loading = false,
|
||||
expireDiff = 0,
|
||||
trafficDiff = 0,
|
||||
ipLimitEnable = false,
|
||||
@@ -54,10 +50,8 @@ export default function InboundInfoModal({
|
||||
const [clientSettings, setClientSettings] = useState<ClientSetting | null>(null);
|
||||
const [clientStats, setClientStats] = useState<ClientStats | null>(null);
|
||||
const [links, setLinks] = useState<{ remark?: string; link: string }[]>([]);
|
||||
const [wireguardConfigs, setWireguardConfigs] = useState<string[][]>([]);
|
||||
const [wireguardLinks, setWireguardLinks] = useState<string[][]>([]);
|
||||
const [amneziawgConfigs, setAmneziawgConfigs] = useState<string[][]>([]);
|
||||
const [amneziawgLinks, setAmneziawgLinks] = useState<string[][]>([]);
|
||||
const [peerConfigs, setPeerConfigs] = useState<string[][]>([]);
|
||||
const [peerLinks, setPeerLinks] = useState<string[][]>([]);
|
||||
const [subLink, setSubLink] = useState('');
|
||||
const [subJsonLink, setSubJsonLink] = useState('');
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
@@ -65,179 +59,20 @@ export default function InboundInfoModal({
|
||||
const [clientIpsText, setClientIpsText] = useState('');
|
||||
const [activeTab, setActiveTab] = useState('client');
|
||||
|
||||
const loadClientIps = useCallback(async () => {
|
||||
if (!clientStats?.email) return;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const msg = await HttpUtil.post(
|
||||
`/panel/api/clients/ips/${encodeURIComponent(clientStats.email)}`,
|
||||
);
|
||||
if (!msg?.success) {
|
||||
setClientIpsText((msg?.obj as string) || 'No IP record');
|
||||
setClientIpsArray([]);
|
||||
return;
|
||||
}
|
||||
let ips: unknown = msg.obj;
|
||||
if (typeof ips === 'string') {
|
||||
try {
|
||||
ips = JSON.parse(ips);
|
||||
} catch {
|
||||
setClientIpsText(String(ips));
|
||||
setClientIpsArray([String(ips)]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (ips && !Array.isArray(ips) && typeof ips === 'object') ips = [ips];
|
||||
if (Array.isArray(ips) && ips.length > 0) {
|
||||
const arr = (ips as unknown[]).map(formatIpInfo).filter(Boolean) as string[];
|
||||
setClientIpsArray(arr);
|
||||
setClientIpsText(arr.join(' | '));
|
||||
} else {
|
||||
setClientIpsArray([]);
|
||||
setClientIpsText(String(ips || t('tgbot.noIpRecord')));
|
||||
}
|
||||
} finally {
|
||||
setRefreshing(false);
|
||||
}
|
||||
}, [clientStats, t]);
|
||||
|
||||
const clearClientIps = useCallback(async () => {
|
||||
if (!clientStats?.email) return;
|
||||
const msg = await HttpUtil.post(
|
||||
`/panel/api/clients/clearIps/${encodeURIComponent(clientStats.email)}`,
|
||||
);
|
||||
if (msg?.success) {
|
||||
setClientIpsArray([]);
|
||||
setClientIpsText(t('tgbot.noIpRecord'));
|
||||
}
|
||||
}, [clientStats, t]);
|
||||
|
||||
// The panel's contents are a pure function of the props, so they are adopted
|
||||
// during render; only the IP lookup below stays asynchronous.
|
||||
const [syncedProps, setSyncedProps] = useState<{
|
||||
dbInbound: typeof dbInbound;
|
||||
clientIndex: typeof clientIndex;
|
||||
nodeAddress: typeof nodeAddress;
|
||||
subSettings: typeof subSettings;
|
||||
hosts: typeof hosts;
|
||||
ipLimitEnable: typeof ipLimitEnable;
|
||||
} | null>(null);
|
||||
if (
|
||||
open &&
|
||||
dbInbound &&
|
||||
(syncedProps === null ||
|
||||
syncedProps.dbInbound !== dbInbound ||
|
||||
syncedProps.clientIndex !== clientIndex ||
|
||||
syncedProps.nodeAddress !== nodeAddress ||
|
||||
syncedProps.subSettings !== subSettings ||
|
||||
syncedProps.hosts !== hosts ||
|
||||
syncedProps.ipLimitEnable !== ipLimitEnable)
|
||||
) {
|
||||
setSyncedProps({ dbInbound, clientIndex, nodeAddress, subSettings, hosts, ipLimitEnable });
|
||||
const info = buildInboundInfo(dbInbound);
|
||||
setInbound(info);
|
||||
setActiveTab(info.clients.length > 0 ? 'client' : 'inbound');
|
||||
|
||||
const idx = clientIndex ?? 0;
|
||||
const clientSet = info.clients.length > 0 ? info.clients[idx] || null : null;
|
||||
setClientSettings(clientSet);
|
||||
const stats = clientSet
|
||||
? (dbInbound.clientStats || []).find((s) => s.email === clientSet.email) || null
|
||||
: null;
|
||||
setClientStats(stats);
|
||||
|
||||
const fallbackHostname = preferPublicHost(
|
||||
window.location.hostname,
|
||||
subSettings?.publicHost ?? '',
|
||||
);
|
||||
const baseInbound = inboundFromDb(dbInbound);
|
||||
const inboundForLinks = withHostEndpoints(
|
||||
baseInbound,
|
||||
dbInbound.id,
|
||||
hosts,
|
||||
nodeAddress,
|
||||
fallbackHostname,
|
||||
);
|
||||
if (hostLinksClosed(baseInbound, dbInbound.id, hosts)) {
|
||||
setWireguardConfigs([]);
|
||||
setWireguardLinks([]);
|
||||
setAmneziawgConfigs([]);
|
||||
setAmneziawgLinks([]);
|
||||
setLinks([]);
|
||||
} else if (info.protocol === Protocols.WIREGUARD) {
|
||||
setWireguardConfigs(
|
||||
genWireguardPeerConfigs({
|
||||
inbound: inboundForLinks,
|
||||
remark: dbInbound.remark,
|
||||
hostOverride: nodeAddress,
|
||||
fallbackHostname,
|
||||
}),
|
||||
);
|
||||
setWireguardLinks(
|
||||
genWireguardPeerLinks({
|
||||
inbound: inboundForLinks,
|
||||
remark: dbInbound.remark,
|
||||
hostOverride: nodeAddress,
|
||||
fallbackHostname,
|
||||
}),
|
||||
);
|
||||
setAmneziawgConfigs([]);
|
||||
setAmneziawgLinks([]);
|
||||
setLinks([]);
|
||||
} else if (info.protocol === Protocols.AMNEZIAWG) {
|
||||
setAmneziawgConfigs(
|
||||
genAmneziaWGPeerConfigs({
|
||||
inbound: inboundForLinks,
|
||||
remark: dbInbound.remark,
|
||||
hostOverride: nodeAddress,
|
||||
fallbackHostname,
|
||||
}),
|
||||
);
|
||||
setAmneziawgLinks(
|
||||
genAmneziaWGPeerLinks({
|
||||
inbound: inboundForLinks,
|
||||
remark: dbInbound.remark,
|
||||
hostOverride: nodeAddress,
|
||||
fallbackHostname,
|
||||
}),
|
||||
);
|
||||
setWireguardConfigs([]);
|
||||
setWireguardLinks([]);
|
||||
setLinks([]);
|
||||
} else {
|
||||
setLinks(
|
||||
genAllLinks({
|
||||
inbound: inboundForLinks,
|
||||
remark: dbInbound.remark,
|
||||
client: (clientSet ?? {}) as Parameters<typeof genAllLinks>[0]['client'],
|
||||
hostOverride: nodeAddress,
|
||||
fallbackHostname,
|
||||
}),
|
||||
);
|
||||
setWireguardConfigs([]);
|
||||
setWireguardLinks([]);
|
||||
setAmneziawgConfigs([]);
|
||||
setAmneziawgLinks([]);
|
||||
}
|
||||
|
||||
if (clientSet?.subId) {
|
||||
setSubLink((subSettings?.subURI || '') + clientSet.subId);
|
||||
setSubJsonLink(
|
||||
subSettings?.subJsonEnable ? (subSettings?.subJsonURI || '') + clientSet.subId : '',
|
||||
);
|
||||
} else {
|
||||
setSubLink('');
|
||||
setSubJsonLink('');
|
||||
}
|
||||
|
||||
setClientIpsArray([]);
|
||||
setClientIpsText('');
|
||||
|
||||
if (ipLimitEnable && (clientSet?.limitIp ?? 0) > 0 && stats?.email) {
|
||||
const email = encodeURIComponent(stats.email);
|
||||
void HttpUtil.post(`/panel/api/clients/ips/${email}`).then((msg) => {
|
||||
const loadClientIps = useCallback(
|
||||
async (signal?: AbortSignal) => {
|
||||
if (!clientStats?.email) return;
|
||||
setRefreshing(true);
|
||||
try {
|
||||
const msg = await HttpUtil.post(
|
||||
`/panel/api/clients/ips/${encodeURIComponent(clientStats.email)}`,
|
||||
undefined,
|
||||
{ signal },
|
||||
);
|
||||
if (signal?.aborted) return;
|
||||
if (!msg?.success) {
|
||||
setClientIpsText((msg?.obj as string) || 'No IP record');
|
||||
setClientIpsArray([]);
|
||||
return;
|
||||
}
|
||||
let ips: unknown = msg.obj;
|
||||
@@ -256,12 +91,109 @@ export default function InboundInfoModal({
|
||||
setClientIpsArray(arr);
|
||||
setClientIpsText(arr.join(' | '));
|
||||
} else {
|
||||
setClientIpsArray([]);
|
||||
setClientIpsText(String(ips || t('tgbot.noIpRecord')));
|
||||
}
|
||||
});
|
||||
} finally {
|
||||
if (!signal?.aborted) setRefreshing(false);
|
||||
}
|
||||
},
|
||||
[clientStats, t],
|
||||
);
|
||||
|
||||
const clearClientIps = useCallback(async () => {
|
||||
if (!clientStats?.email) return;
|
||||
const msg = await HttpUtil.post(
|
||||
`/panel/api/clients/clearIps/${encodeURIComponent(clientStats.email)}`,
|
||||
);
|
||||
if (msg?.success) {
|
||||
setClientIpsArray([]);
|
||||
setClientIpsText(t('tgbot.noIpRecord'));
|
||||
}
|
||||
}, [clientStats, t]);
|
||||
|
||||
// The panel's contents are a pure function of the props, so they are adopted
|
||||
// during render; only the IP lookup below stays asynchronous.
|
||||
const [syncedProps, setSyncedProps] = useState<{
|
||||
dbInbound: typeof dbInbound;
|
||||
clientIndex: typeof clientIndex;
|
||||
peerOffset: typeof peerOffset;
|
||||
nodeAddress: typeof nodeAddress;
|
||||
subSettings: typeof subSettings;
|
||||
hosts: typeof hosts;
|
||||
ipLimitEnable: typeof ipLimitEnable;
|
||||
} | null>(null);
|
||||
if (
|
||||
open &&
|
||||
dbInbound &&
|
||||
(syncedProps === null ||
|
||||
syncedProps.dbInbound !== dbInbound ||
|
||||
syncedProps.clientIndex !== clientIndex ||
|
||||
syncedProps.peerOffset !== peerOffset ||
|
||||
syncedProps.nodeAddress !== nodeAddress ||
|
||||
syncedProps.subSettings !== subSettings ||
|
||||
syncedProps.hosts !== hosts ||
|
||||
syncedProps.ipLimitEnable !== ipLimitEnable)
|
||||
) {
|
||||
setSyncedProps({
|
||||
dbInbound,
|
||||
clientIndex,
|
||||
peerOffset,
|
||||
nodeAddress,
|
||||
subSettings,
|
||||
hosts,
|
||||
ipLimitEnable,
|
||||
});
|
||||
const info = buildInboundInfo(dbInbound);
|
||||
setInbound(info);
|
||||
const tunnel = info.protocol === Protocols.WIREGUARD || info.protocol === Protocols.AMNEZIAWG;
|
||||
setActiveTab(!tunnel && info.clients.length > 0 ? 'client' : 'inbound');
|
||||
|
||||
const idx = clientIndex ?? 0;
|
||||
const clientSet = info.clients.length > 0 ? info.clients[idx] || null : null;
|
||||
setClientSettings(clientSet);
|
||||
const stats = clientSet
|
||||
? (dbInbound.clientStats || []).find((s) => s.email === clientSet.email) || null
|
||||
: null;
|
||||
setClientStats(stats);
|
||||
|
||||
const input = infoLinkInput(dbInbound, hosts, nodeAddress, subSettings?.publicHost, peerOffset);
|
||||
const outputs = tunnelInfoOutputs(input);
|
||||
setPeerConfigs(outputs.configs);
|
||||
setPeerLinks(outputs.links);
|
||||
setLinks(
|
||||
input && !tunnel
|
||||
? genAllLinks({
|
||||
...input,
|
||||
client: (clientSet ?? {}) as Parameters<typeof genAllLinks>[0]['client'],
|
||||
})
|
||||
: [],
|
||||
);
|
||||
|
||||
if (clientSet?.subId) {
|
||||
setSubLink((subSettings?.subURI || '') + clientSet.subId);
|
||||
setSubJsonLink(
|
||||
subSettings?.subJsonEnable ? (subSettings?.subJsonURI || '') + clientSet.subId : '',
|
||||
);
|
||||
} else {
|
||||
setSubLink('');
|
||||
setSubJsonLink('');
|
||||
}
|
||||
|
||||
setClientIpsArray([]);
|
||||
setClientIpsText('');
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !ipLimitEnable || !(clientSettings?.limitIp && clientSettings.limitIp > 0)) return;
|
||||
const controller = new AbortController();
|
||||
// Give the cleanup a chance to cancel a superseded request before it starts.
|
||||
queueMicrotask(() => {
|
||||
if (!controller.signal.aborted) void loadClientIps(controller.signal);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [open, ipLimitEnable, clientSettings?.limitIp, loadClientIps]);
|
||||
|
||||
// The expiry tag colours against the current time; a state-backed clock keeps
|
||||
// render pure and still refreshes the tag while the modal stays open.
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
@@ -295,7 +227,7 @@ export default function InboundInfoModal({
|
||||
const isWireguard = !!dbInbound?.isWireguard;
|
||||
const wgSecretKey = inbound?.settings?.secretKey as string | undefined;
|
||||
const wgPubKey = useMemo(
|
||||
() => (isWireguard && wgSecretKey ? Wireguard.generateKeypair(wgSecretKey).publicKey : ''),
|
||||
() => (isWireguard ? wireguardServerPublicKey(wgSecretKey) : ''),
|
||||
[isWireguard, wgSecretKey],
|
||||
);
|
||||
|
||||
@@ -324,7 +256,10 @@ export default function InboundInfoModal({
|
||||
title={t('pages.inbounds.inboundInfo')}
|
||||
footer={null}
|
||||
width={640}
|
||||
/>
|
||||
>
|
||||
{feedback}
|
||||
{peerTools}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1154,18 +1089,28 @@ export default function InboundInfoModal({
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{Array.isArray(inbound.settings.peers) &&
|
||||
{(Array.isArray(inbound.settings.clients) && inbound.settings.clients.length
|
||||
? inbound.settings.clients
|
||||
: Array.isArray(inbound.settings.peers)
|
||||
? inbound.settings.peers
|
||||
: []
|
||||
).map(
|
||||
(
|
||||
inbound.settings.peers as {
|
||||
privateKey: string;
|
||||
publicKey: string;
|
||||
psk: string;
|
||||
peer: {
|
||||
privateKey?: string;
|
||||
publicKey?: string;
|
||||
psk?: string;
|
||||
preSharedKey?: string;
|
||||
email?: string;
|
||||
allowedIPs?: string[];
|
||||
keepAlive?: number;
|
||||
}[]
|
||||
).map((peer, idx) => (
|
||||
<Fragment key={idx}>
|
||||
<Divider>{t('pages.inbounds.info.peerNumber', { n: idx + 1 })}</Divider>
|
||||
},
|
||||
idx,
|
||||
) => (
|
||||
<Fragment key={`${peer.publicKey || peer.email || 'peer'}-${peerOffset + idx}`}>
|
||||
<Divider>
|
||||
{t('pages.inbounds.info.peerNumber', { n: peerOffset + idx + 1 })}
|
||||
</Divider>
|
||||
<dl className="info-list info-list-block">
|
||||
<div className="info-row">
|
||||
<dt>{t('pages.xray.wireguard.secretKey')}</dt>
|
||||
@@ -1182,13 +1127,13 @@ export default function InboundInfoModal({
|
||||
<div className="info-row">
|
||||
<dt>PSK</dt>
|
||||
<dd>
|
||||
<Tag className="value-tag">{peer.psk}</Tag>
|
||||
<Tag className="value-tag">{peer.psk ?? peer.preSharedKey}</Tag>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="info-row">
|
||||
<dt>{t('pages.xray.wireguard.allowedIPs')}</dt>
|
||||
<dd>
|
||||
{(peer.allowedIPs || []).map((ip, j) => (
|
||||
{(Array.isArray(peer.allowedIPs) ? peer.allowedIPs : []).map((ip, j) => (
|
||||
<Tag key={`wg-ip-${idx}-${j}`} className="value-tag">
|
||||
{ip}
|
||||
</Tag>
|
||||
@@ -1202,13 +1147,13 @@ export default function InboundInfoModal({
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
{(wireguardConfigs[idx] ?? []).map(
|
||||
{(peerConfigs[idx] ?? []).map(
|
||||
(cfg, j, all) =>
|
||||
cfg && (
|
||||
<div key={`wg-cfg-${j}`} className="link-panel">
|
||||
<div className="link-panel-header">
|
||||
<Tag color="green">
|
||||
{t('pages.inbounds.info.peerNumberConfig', { n: idx + 1 })}
|
||||
<Tag>
|
||||
{t('pages.inbounds.info.peerNumberConfig', { n: peerOffset + idx + 1 })}
|
||||
</Tag>
|
||||
<Tooltip title={t('copy')}>
|
||||
<Button
|
||||
@@ -1224,7 +1169,7 @@ export default function InboundInfoModal({
|
||||
icon={<DownloadOutlined aria-hidden />}
|
||||
aria-label={t('download')}
|
||||
onClick={() =>
|
||||
downloadText(cfg, peerConfFileName(idx, j, all.length))
|
||||
downloadText(cfg, peerConfFileName(peerOffset + idx, j, all.length))
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
@@ -1233,12 +1178,12 @@ export default function InboundInfoModal({
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{(wireguardLinks[idx] ?? []).map(
|
||||
{(peerLinks[idx] ?? []).map(
|
||||
(link, j) =>
|
||||
link && (
|
||||
<div key={`wg-link-${j}`} className="link-panel">
|
||||
<div className="link-panel-header">
|
||||
<Tag color="green">Peer {idx + 1} link</Tag>
|
||||
<Tag>Peer {peerOffset + idx + 1} link</Tag>
|
||||
<Tooltip title={t('copy')}>
|
||||
<Button
|
||||
size="small"
|
||||
@@ -1253,22 +1198,23 @@ export default function InboundInfoModal({
|
||||
),
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
),
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{inbound?.protocol === Protocols.AMNEZIAWG && amneziawgConfigs.length > 0 && (
|
||||
{inbound?.protocol === Protocols.AMNEZIAWG && peerConfigs.length > 0 && (
|
||||
<>
|
||||
<Divider>{t('pages.inbounds.copyLink')}</Divider>
|
||||
{amneziawgConfigs.map((peerConfigs, idx) => (
|
||||
<Fragment key={idx}>
|
||||
{peerConfigs.map((peerConfigs, idx) => (
|
||||
<Fragment key={`${inbound.clients[idx]?.email ?? 'peer'}-${peerOffset + idx}`}>
|
||||
{peerConfigs.map(
|
||||
(cfg, j, all) =>
|
||||
cfg && (
|
||||
<div key={`awg-cfg-${j}`} className="link-panel">
|
||||
<div className="link-panel-header">
|
||||
<Tag color="green">
|
||||
{t('pages.inbounds.info.peerNumberConfig', { n: idx + 1 })}
|
||||
<Tag>
|
||||
{t('pages.inbounds.info.peerNumberConfig', { n: peerOffset + idx + 1 })}
|
||||
</Tag>
|
||||
<Tooltip title={t('copy')}>
|
||||
<Button
|
||||
@@ -1283,7 +1229,9 @@ export default function InboundInfoModal({
|
||||
size="small"
|
||||
icon={<DownloadOutlined aria-hidden />}
|
||||
aria-label={t('download')}
|
||||
onClick={() => downloadText(cfg, peerConfFileName(idx, j, all.length))}
|
||||
onClick={() =>
|
||||
downloadText(cfg, peerConfFileName(peerOffset + idx, j, all.length))
|
||||
}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -1291,12 +1239,12 @@ export default function InboundInfoModal({
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
{(amneziawgLinks[idx] ?? []).map(
|
||||
{(peerLinks[idx] ?? []).map(
|
||||
(link, j) =>
|
||||
link && (
|
||||
<div key={`awg-link-${j}`} className="link-panel">
|
||||
<div className="link-panel-header">
|
||||
<Tag color="green">Peer {idx + 1} link</Tag>
|
||||
<Tag>Peer {peerOffset + idx + 1} link</Tag>
|
||||
<Tooltip title={t('copy')}>
|
||||
<Button
|
||||
size="small"
|
||||
@@ -1332,7 +1280,16 @@ export default function InboundInfoModal({
|
||||
width={640}
|
||||
destroyOnHidden
|
||||
>
|
||||
<Tabs activeKey={activeTab} onChange={setActiveTab} items={tabItems} />
|
||||
{feedback}
|
||||
{peerTools}
|
||||
<Spin spinning={loading} aria-live="off">
|
||||
<Tabs
|
||||
className="inbound-info-tabs"
|
||||
activeKey={activeTab}
|
||||
onChange={setActiveTab}
|
||||
items={tabItems}
|
||||
/>
|
||||
</Spin>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useState } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, within } from 'storybook/test';
|
||||
|
||||
import PagedInboundInfoModal from './PagedInboundInfoModal';
|
||||
import type { DBInbound } from '@/models/dbinbound';
|
||||
|
||||
const serverKey = 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=';
|
||||
const peerKey = 'AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=';
|
||||
const totalPeers = 50_000;
|
||||
const requests: string[] = [];
|
||||
const identity = (inbound: DBInbound) => inbound;
|
||||
|
||||
function Fixture({ protocol }: { protocol: string }) {
|
||||
const [query] = useState(() => new QueryClient());
|
||||
return (
|
||||
<QueryClientProvider client={query}>
|
||||
<PagedInboundInfoModal
|
||||
inboundID={7}
|
||||
open
|
||||
onClose={() => {}}
|
||||
nodeAddress={protocol === 'wireguard' ? 'wg.node.example.test' : 'awg.node.example.test'}
|
||||
projectInbound={identity}
|
||||
/>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function fakePages(protocol: string) {
|
||||
requests.length = 0;
|
||||
const original = window.fetch;
|
||||
window.fetch = (input, init) => {
|
||||
const url = new URL(input instanceof Request ? input.url : input, window.location.href);
|
||||
if (url.pathname === '/panel/api/setting/defaultSettings') {
|
||||
return Promise.resolve(
|
||||
Response.json({ success: true, msg: '', obj: { datepicker: 'gregorian' } }),
|
||||
);
|
||||
}
|
||||
if (!url.pathname.startsWith('/panel/api/inbounds/')) return original(input, init);
|
||||
requests.push(url.pathname + url.search);
|
||||
if (url.pathname !== '/panel/api/inbounds/7/info')
|
||||
return Promise.resolve(new Response(null, { status: 404 }));
|
||||
const peerOffset = (Number(url.searchParams.get('page')) - 1) * 50;
|
||||
return Promise.resolve(
|
||||
Response.json({
|
||||
success: true,
|
||||
msg: '',
|
||||
obj: {
|
||||
inbound: {
|
||||
id: 7,
|
||||
protocol,
|
||||
port: 51820,
|
||||
listen: '',
|
||||
remark: 'fleet',
|
||||
settings: {
|
||||
secretKey: serverKey,
|
||||
server: { publicKey: serverKey },
|
||||
clients: Array.from({ length: 50 }, (_, index) => {
|
||||
const n = index + peerOffset + 1;
|
||||
return {
|
||||
email: `client-${n}@example.test`,
|
||||
allowedIPs: [`10.8.${Math.floor((n - 1) / 254)}.${((n - 1) % 254) + 1}/32`],
|
||||
publicKey: serverKey,
|
||||
privateKey: peerKey,
|
||||
};
|
||||
}),
|
||||
},
|
||||
},
|
||||
totalPeers,
|
||||
peerOffset,
|
||||
},
|
||||
}),
|
||||
);
|
||||
};
|
||||
return () => {
|
||||
window.fetch = original;
|
||||
};
|
||||
}
|
||||
|
||||
const meta = {
|
||||
title: 'Pages/Inbounds/Bounded inbound information',
|
||||
component: Fixture,
|
||||
parameters: { a11y: { context: '.ant-modal' } },
|
||||
} satisfies Meta<typeof Fixture>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
const play: NonNullable<Story['play']> = async ({ userEvent, args }) => {
|
||||
const screen = within(document.body);
|
||||
const el = await screen.findByRole('dialog');
|
||||
const dialog = within(el);
|
||||
await dialog.findByText('Peer 1 link');
|
||||
await expect(el.querySelectorAll('.link-panel').length).toBe(100);
|
||||
await expect(el.textContent).toContain(
|
||||
`${args.protocol === 'wireguard' ? 'wg' : 'awg'}.node.example.test:51820`,
|
||||
);
|
||||
await expect(dialog.queryByText('Peer 51 link')).toBeNull();
|
||||
const next = el.querySelector('.ant-pagination-next button');
|
||||
if (!(next instanceof HTMLButtonElement)) throw new Error('Next page control missing');
|
||||
await userEvent.click(next);
|
||||
await dialog.findByText('Peer 51 link');
|
||||
await expect(dialog.queryByText('Peer 1 link')).toBeNull();
|
||||
await expect(el.querySelectorAll('.link-panel').length).toBe(100);
|
||||
await expect(requests).toEqual([
|
||||
'/panel/api/inbounds/7/info?page=1',
|
||||
'/panel/api/inbounds/7/info?page=2',
|
||||
]);
|
||||
};
|
||||
|
||||
export const WireGuard: Story = {
|
||||
args: { protocol: 'wireguard' },
|
||||
beforeEach: () => fakePages('wireguard'),
|
||||
play,
|
||||
};
|
||||
|
||||
export const AmneziaWG: Story = {
|
||||
args: { protocol: 'amneziawg' },
|
||||
beforeEach: () => fakePages('amneziawg'),
|
||||
play,
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { Alert, Button, Pagination, Space, Spin, message } from 'antd';
|
||||
import { DownloadOutlined } from '@ant-design/icons';
|
||||
|
||||
import { INBOUND_PEER_PAGE_SIZE, fetchInboundInfo } from '@/api/inboundInfo';
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { allHostsExcluded } from '@/lib/hosts/host-link';
|
||||
import { DBInbound, type DBInboundInit } from '@/models/dbinbound';
|
||||
|
||||
import InboundInfoModal from './InboundInfoModal';
|
||||
import type { InboundInfoModalProps } from './types';
|
||||
|
||||
type PagedInboundInfoModalProps = Omit<InboundInfoModalProps, 'dbInbound'> & {
|
||||
inboundID: number;
|
||||
projectInbound: (inbound: DBInbound) => DBInbound;
|
||||
};
|
||||
|
||||
export default function PagedInboundInfoModal({
|
||||
inboundID,
|
||||
projectInbound,
|
||||
...props
|
||||
}: PagedInboundInfoModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const [page, setPage] = useState(1);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const exportRequest = useRef<AbortController | null>(null);
|
||||
const [messages, holder] = message.useMessage();
|
||||
const info = useQuery({
|
||||
queryKey: [...keys.inbounds.root(), 'info', inboundID, page],
|
||||
queryFn: ({ signal }) => fetchInboundInfo(inboundID, page, signal),
|
||||
enabled: props.open,
|
||||
gcTime: 0,
|
||||
retry: false,
|
||||
placeholderData: keepPreviousData,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
const data = info.data;
|
||||
const inbound = useMemo(
|
||||
() => (data ? projectInbound(new DBInbound(data.inbound as DBInboundInit)) : null),
|
||||
[data, projectInbound],
|
||||
);
|
||||
useEffect(() => {
|
||||
return () => exportRequest.current?.abort();
|
||||
}, []);
|
||||
const maxPage = Math.max(1, Math.ceil((data?.totalPeers ?? 0) / INBOUND_PEER_PAGE_SIZE));
|
||||
if (data && !info.isPlaceholderData && !info.isError && page > maxPage) setPage(maxPage);
|
||||
|
||||
async function exportAll() {
|
||||
if (exportRequest.current) return;
|
||||
const controller = new AbortController();
|
||||
exportRequest.current = controller;
|
||||
setExporting(true);
|
||||
try {
|
||||
const { buildInboundPeerArchive, saveInboundPeerArchive } = await import('./peerExport');
|
||||
const archive = await buildInboundPeerArchive(inboundID, props, controller.signal);
|
||||
if (!controller.signal.aborted) saveInboundPeerArchive(archive, inboundID);
|
||||
} catch {
|
||||
if (!controller.signal.aborted) messages.error(t('somethingWentWrong'));
|
||||
} finally {
|
||||
exportRequest.current = null;
|
||||
if (!controller.signal.aborted) setExporting(false);
|
||||
}
|
||||
}
|
||||
|
||||
const total = data?.totalPeers ?? 0;
|
||||
const isTunnel = inbound?.isWireguard || inbound?.isAmneziawg;
|
||||
const canExport = !allHostsExcluded(props.hosts ?? [], inboundID);
|
||||
const peerTools =
|
||||
isTunnel && total > 0 ? (
|
||||
<Space wrap style={{ marginBlockEnd: 12 }}>
|
||||
<Pagination
|
||||
size="small"
|
||||
current={page}
|
||||
total={total}
|
||||
pageSize={INBOUND_PEER_PAGE_SIZE}
|
||||
showSizeChanger={false}
|
||||
onChange={setPage}
|
||||
/>
|
||||
{canExport && (
|
||||
<Button
|
||||
icon={<DownloadOutlined aria-hidden />}
|
||||
loading={exporting}
|
||||
onClick={() => void exportAll()}
|
||||
>
|
||||
{t('pages.inbounds.info.exportAllPeers')}
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
) : null;
|
||||
const feedback = (
|
||||
<>
|
||||
{holder}
|
||||
{info.isPending && <Spin />}
|
||||
{info.isError && (
|
||||
<Alert
|
||||
showIcon
|
||||
type="error"
|
||||
title={info.error.message || t('somethingWentWrong')}
|
||||
action={<Button onClick={() => void info.refetch()}>{t('refresh')}</Button>}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<InboundInfoModal
|
||||
{...props}
|
||||
dbInbound={inbound}
|
||||
peerOffset={data?.peerOffset}
|
||||
peerTools={peerTools}
|
||||
feedback={feedback}
|
||||
loading={info.isFetching}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
import { BlobReader, Uint8ArrayReader, ZipWriter } from '@zip.js/zip.js';
|
||||
|
||||
import {
|
||||
INBOUND_PEER_PAGE_SIZE,
|
||||
InboundInfoPageSchema,
|
||||
inboundPeerExportPath,
|
||||
} from '@/api/inboundInfo';
|
||||
import { inboundFromDb } from '@/lib/xray/inbound-from-db';
|
||||
import type { GenWireguardFanoutInput } from '@/lib/xray/inbound-link';
|
||||
import { DBInbound, coerceInboundJsonField, type DBInboundInit } from '@/models/dbinbound';
|
||||
|
||||
import { peerConfFileName } from './helpers';
|
||||
import { infoLinkInput, tunnelInfoOutputs } from './peerLinks';
|
||||
import type { InboundInfoModalProps } from './types';
|
||||
|
||||
type ExportOptions = Pick<InboundInfoModalProps, 'hosts' | 'nodeAddress' | 'subSettings'>;
|
||||
|
||||
export async function buildInboundPeerArchive(
|
||||
id: number,
|
||||
options: ExportOptions,
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
const response = await fetch(inboundPeerExportPath(id), {
|
||||
credentials: 'same-origin',
|
||||
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||
signal,
|
||||
});
|
||||
if (
|
||||
!response.ok ||
|
||||
!response.body ||
|
||||
!response.headers.get('Content-Type')?.startsWith('application/x-ndjson')
|
||||
) {
|
||||
throw new Error('Unable to load inbound peers');
|
||||
}
|
||||
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
// Pack small ZIP writes into buffers so a large export does not create hundreds
|
||||
// of thousands of separate browser Blob parts.
|
||||
const archiveChunks: BlobPart[] = [];
|
||||
const bufferSize = 1024 * 1024;
|
||||
let buffer = new Uint8Array(bufferSize);
|
||||
let written = 0;
|
||||
const writer = new WritableStream<Uint8Array>({
|
||||
write(chunk) {
|
||||
let offset = 0;
|
||||
while (offset < chunk.length) {
|
||||
const length = Math.min(chunk.length - offset, buffer.length - written);
|
||||
buffer.set(chunk.subarray(offset, offset + length), written);
|
||||
offset += length;
|
||||
written += length;
|
||||
if (written === buffer.length) {
|
||||
archiveChunks.push(buffer);
|
||||
buffer = new Uint8Array(bufferSize);
|
||||
written = 0;
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
const zip = new ZipWriter(writer, { level: 0, useWebWorkers: false, zip64: true });
|
||||
const encoder = new TextEncoder();
|
||||
const linkChunks: BlobPart[] = [];
|
||||
let peerOffset = 0;
|
||||
let total: number | undefined;
|
||||
let pending = '';
|
||||
let configCount = 0;
|
||||
let exportInput: GenWireguardFanoutInput | undefined;
|
||||
let protocol: string | undefined;
|
||||
|
||||
async function addPage(line: string) {
|
||||
const page = InboundInfoPageSchema.parse(JSON.parse(line));
|
||||
const inbound = new DBInbound(page.inbound as DBInboundInit);
|
||||
const settings = coerceInboundJsonField(inbound.settings);
|
||||
const peers =
|
||||
Array.isArray(settings.clients) && settings.clients.length
|
||||
? settings.clients
|
||||
: Array.isArray(settings.peers)
|
||||
? settings.peers
|
||||
: [];
|
||||
if (
|
||||
inbound.id !== id ||
|
||||
(!inbound.isWireguard && !inbound.isAmneziawg) ||
|
||||
!peers.length ||
|
||||
peers.length > INBOUND_PEER_PAGE_SIZE ||
|
||||
(protocol !== undefined && protocol !== inbound.protocol) ||
|
||||
page.peerOffset !== peerOffset ||
|
||||
(total !== undefined && total !== page.totalPeers) ||
|
||||
page.peerOffset + peers.length > page.totalPeers
|
||||
) {
|
||||
throw new Error('Incomplete inbound peer export');
|
||||
}
|
||||
if (peerOffset === 0) {
|
||||
protocol = inbound.protocol;
|
||||
// Resolve Host overrides once so a randomized CIDR stays consistent across the archive.
|
||||
exportInput = infoLinkInput(
|
||||
inbound,
|
||||
options.hosts ?? [],
|
||||
options.nodeAddress,
|
||||
options.subSettings?.publicHost,
|
||||
);
|
||||
}
|
||||
const output = tunnelInfoOutputs(
|
||||
exportInput && {
|
||||
...exportInput,
|
||||
peerOffset,
|
||||
inbound: {
|
||||
...exportInput.inbound,
|
||||
settings: inboundFromDb(inbound).settings,
|
||||
} as GenWireguardFanoutInput['inbound'],
|
||||
},
|
||||
);
|
||||
for (const [index, variants] of output.configs.entries()) {
|
||||
for (const [endpoint, config] of variants.entries()) {
|
||||
if (!config) continue;
|
||||
signal.throwIfAborted();
|
||||
await zip.add(
|
||||
peerConfFileName(peerOffset + index, endpoint, variants.length),
|
||||
new Uint8ArrayReader(encoder.encode(config)),
|
||||
{ signal },
|
||||
);
|
||||
configCount++;
|
||||
}
|
||||
}
|
||||
const text = output.links.flat().filter(Boolean).join('\r\n');
|
||||
if (text) linkChunks.push((linkChunks.length ? '\r\n' : '') + text);
|
||||
peerOffset += peers.length;
|
||||
total = page.totalPeers;
|
||||
}
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const next = await reader.read();
|
||||
if (next.done) break;
|
||||
pending += next.value;
|
||||
let newline = pending.indexOf('\n');
|
||||
while (newline >= 0) {
|
||||
signal.throwIfAborted();
|
||||
await addPage(pending.slice(0, newline));
|
||||
pending = pending.slice(newline + 1);
|
||||
newline = pending.indexOf('\n');
|
||||
}
|
||||
// Yield between network chunks so a large download can be cancelled.
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 0));
|
||||
}
|
||||
if (pending !== '' || total !== peerOffset || (!configCount && !linkChunks.length)) {
|
||||
throw new Error('Incomplete inbound peer export');
|
||||
}
|
||||
if (linkChunks.length) {
|
||||
await zip.add('links.txt', new BlobReader(new Blob(linkChunks)), { signal });
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
await zip.close();
|
||||
return new Blob([...archiveChunks, buffer.subarray(0, written)], { type: 'application/zip' });
|
||||
} finally {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
export function saveInboundPeerArchive(blob: Blob, inboundID: number) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `inbound-${inboundID}-peers.zip`;
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { HostRecord } from '@/schemas/api/host';
|
||||
import { hostLinksClosed, withHostEndpoints } from '@/lib/hosts/host-link';
|
||||
import { inboundFromDb } from '@/lib/xray/inbound-from-db';
|
||||
import {
|
||||
type GenWireguardFanoutInput,
|
||||
genAmneziaWGPeerConfigs,
|
||||
genAmneziaWGPeerLinks,
|
||||
genWireguardPeerConfigs,
|
||||
genWireguardPeerLinks,
|
||||
preferPublicHost,
|
||||
} from '@/lib/xray/inbound-link';
|
||||
|
||||
import type { DBInboundLike } from './types';
|
||||
|
||||
export function infoLinkInput(
|
||||
dbInbound: DBInboundLike,
|
||||
hosts: HostRecord[],
|
||||
nodeAddress = '',
|
||||
publicHost = '',
|
||||
peerOffset = 0,
|
||||
): GenWireguardFanoutInput | undefined {
|
||||
const baseInbound = inboundFromDb(dbInbound);
|
||||
if (hostLinksClosed(baseInbound, dbInbound.id, hosts)) return undefined;
|
||||
const fallbackHostname = preferPublicHost(window.location.hostname, publicHost);
|
||||
return {
|
||||
inbound: withHostEndpoints(baseInbound, dbInbound.id, hosts, nodeAddress, fallbackHostname),
|
||||
remark: dbInbound.remark,
|
||||
hostOverride: nodeAddress,
|
||||
fallbackHostname,
|
||||
peerOffset,
|
||||
};
|
||||
}
|
||||
|
||||
export function tunnelInfoOutputs(input?: GenWireguardFanoutInput) {
|
||||
switch (input?.inbound.protocol) {
|
||||
case 'wireguard':
|
||||
return { configs: genWireguardPeerConfigs(input), links: genWireguardPeerLinks(input) };
|
||||
case 'amneziawg':
|
||||
return { configs: genAmneziaWGPeerConfigs(input), links: genAmneziaWGPeerLinks(input) };
|
||||
default:
|
||||
return { configs: [], links: [] };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import type { SubSettings } from '../useInbounds';
|
||||
import type { HostRecord } from '@/schemas/api/host';
|
||||
|
||||
@@ -76,6 +77,10 @@ export interface InboundInfoModalProps {
|
||||
onClose: () => void;
|
||||
dbInbound: DBInboundLike | null;
|
||||
clientIndex?: number;
|
||||
peerOffset?: number;
|
||||
peerTools?: ReactNode;
|
||||
feedback?: ReactNode;
|
||||
loading?: boolean;
|
||||
expireDiff?: number;
|
||||
trafficDiff?: number;
|
||||
ipLimitEnable?: boolean;
|
||||
|
||||
@@ -50,6 +50,7 @@ function HostRemarksSuffix({ remarks }: { remarks: string[] }) {
|
||||
export default function InboundList({
|
||||
dbInbounds,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
lastOnlineMap: _lastOnlineMap,
|
||||
inboundSpeed,
|
||||
expireDiff,
|
||||
@@ -173,6 +174,7 @@ export default function InboundList({
|
||||
nodesById,
|
||||
hostRemarksByInboundId,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
inboundSpeed,
|
||||
subEnable,
|
||||
expireDiff,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { onlineStatusLabel } from './onlineStatusLabel';
|
||||
import { Modal, Tag } from 'antd';
|
||||
|
||||
import { SizeFormatter, IntlUtil, ColorUtils } from '@/utils';
|
||||
@@ -133,9 +134,17 @@ export default function InboundStatsModal({
|
||||
<Tag color="green" className="client-count-tag">
|
||||
{clientCount[record.id].clients}
|
||||
</Tag>
|
||||
{clientCount[record.id].onlineAttribution &&
|
||||
clientCount[record.id].online.length === 0 && (
|
||||
<Tag>
|
||||
{t('online')}: {onlineStatusLabel(clientCount[record.id], t)}
|
||||
</Tag>
|
||||
)}
|
||||
{clientCount[record.id].online.length > 0 && (
|
||||
<Tag color="blue">
|
||||
{clientCount[record.id].online.length} {t('online')}
|
||||
{clientCount[record.id].onlineAttribution === 'node' &&
|
||||
` (${t('pages.inbounds.node')})`}
|
||||
</Tag>
|
||||
)}
|
||||
{clientCount[record.id].depleted.length > 0 && (
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { TFunction } from 'i18next';
|
||||
|
||||
import type { ClientCountEntry } from './types';
|
||||
|
||||
export function onlineStatusLabel(entry: ClientCountEntry, t: TFunction) {
|
||||
switch (entry.onlineAttribution) {
|
||||
case 'pending':
|
||||
return t('loading');
|
||||
case 'inbound':
|
||||
return '0';
|
||||
case 'node':
|
||||
return `0 (${t('pages.inbounds.node')})`;
|
||||
case 'unsupported':
|
||||
return `${t('pages.nodes.statusValues.unknown')} (${t('pages.inbounds.node')})`;
|
||||
default:
|
||||
return t('pages.nodes.statusValues.unknown');
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ export interface ClientCountEntry {
|
||||
depleted: string[];
|
||||
expiring: string[];
|
||||
online: string[];
|
||||
onlineAttribution?: 'pending' | 'unavailable' | 'inbound' | 'node' | 'unsupported';
|
||||
}
|
||||
|
||||
export interface InboundSpeedEntry {
|
||||
@@ -68,6 +69,7 @@ export type GeneralAction = 'import' | 'export' | 'subs' | 'resetInbounds';
|
||||
export interface InboundListProps {
|
||||
dbInbounds: DBInboundRecord[];
|
||||
clientCount: Record<number, ClientCountEntry>;
|
||||
clientCountsPending: boolean;
|
||||
onlineClients: string[];
|
||||
lastOnlineMap: Record<string, number>;
|
||||
inboundSpeed: Record<number, InboundSpeedEntry>;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo, type ReactElement } from 'react';
|
||||
import { useMemo, useState, type ReactElement } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { onlineStatusLabel } from './onlineStatusLabel';
|
||||
import { Popover, Switch, Tag, Tooltip, type TableColumnType } from 'antd';
|
||||
import { TeamOutlined } from '@ant-design/icons';
|
||||
|
||||
@@ -27,6 +28,49 @@ import {
|
||||
} from './helpers';
|
||||
import type { ClientCountEntry, DBInboundRecord, InboundSpeedEntry, RowAction } from './types';
|
||||
|
||||
function ClientEmailBadge({
|
||||
emails,
|
||||
title,
|
||||
color,
|
||||
suffix,
|
||||
}: {
|
||||
emails: string[];
|
||||
title: string;
|
||||
color?: string;
|
||||
suffix?: string;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const badge = (
|
||||
<Tag
|
||||
color={color}
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{emails.length}
|
||||
{suffix && ` ${suffix}`}
|
||||
</Tag>
|
||||
);
|
||||
if (!emails.length) return badge;
|
||||
return (
|
||||
<Popover
|
||||
title={title}
|
||||
onOpenChange={setOpen}
|
||||
destroyOnHidden
|
||||
content={
|
||||
open ? (
|
||||
<div className="client-email-list">
|
||||
{emails.map((email) => (
|
||||
<div key={email}>{email}</div>
|
||||
))}
|
||||
</div>
|
||||
) : null
|
||||
}
|
||||
>
|
||||
{badge}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
interface UseInboundColumnsParams {
|
||||
hasAnyRemark: boolean;
|
||||
hasAnySubSortIndex: boolean;
|
||||
@@ -34,6 +78,7 @@ interface UseInboundColumnsParams {
|
||||
nodesById: Map<number, NodeRecord>;
|
||||
hostRemarksByInboundId: Map<number, string[]>;
|
||||
clientCount: Record<number, ClientCountEntry>;
|
||||
clientCountsPending: boolean;
|
||||
inboundSpeed: Record<number, InboundSpeedEntry>;
|
||||
subEnable: boolean;
|
||||
expireDiff: number;
|
||||
@@ -49,6 +94,7 @@ export function useInboundColumns({
|
||||
nodesById,
|
||||
hostRemarksByInboundId,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
inboundSpeed,
|
||||
subEnable,
|
||||
expireDiff,
|
||||
@@ -69,7 +115,9 @@ export function useInboundColumns({
|
||||
};
|
||||
|
||||
const clientTotal = (record: DBInboundRecord) =>
|
||||
(clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0;
|
||||
clientCountsPending
|
||||
? 0
|
||||
: ((clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0);
|
||||
|
||||
const speedTotal = (record: DBInboundRecord) => {
|
||||
const speed = inboundSpeed[record.id];
|
||||
@@ -289,8 +337,11 @@ export function useInboundColumns({
|
||||
width: 200,
|
||||
sorter: (a, b) => clientTotal(a) - clientTotal(b),
|
||||
render: (_, record) => {
|
||||
if (clientCountsPending) return t('loading');
|
||||
const cc = clientCount[record.id] || fallbackClientCount(record);
|
||||
if (!cc) return null;
|
||||
const onlineScope =
|
||||
cc.onlineAttribution === 'node' ? `(${t('pages.inbounds.node')})` : undefined;
|
||||
return (
|
||||
<>
|
||||
<Tag
|
||||
@@ -299,92 +350,25 @@ export function useInboundColumns({
|
||||
>
|
||||
<TeamOutlined aria-hidden /> {cc.clients}
|
||||
</Tag>
|
||||
{cc.active.length > 0 ? (
|
||||
<Popover
|
||||
title={t('subscription.active')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.active.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
color="green"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{cc.active.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
) : (
|
||||
<Tag
|
||||
color="green"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
0
|
||||
</Tag>
|
||||
)}
|
||||
<ClientEmailBadge emails={cc.active} color="green" title={t('subscription.active')} />
|
||||
{cc.deactive.length > 0 && (
|
||||
<Popover
|
||||
title={t('disabled')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.deactive.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{cc.deactive.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
<ClientEmailBadge emails={cc.deactive} title={t('disabled')} />
|
||||
)}
|
||||
{cc.depleted.length > 0 && (
|
||||
<Popover
|
||||
title={t('depleted')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.depleted.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
color="red"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, marginRight: 4, padding: '0 2px' }}
|
||||
>
|
||||
{cc.depleted.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
<ClientEmailBadge emails={cc.depleted} color="red" title={t('depleted')} />
|
||||
)}
|
||||
{cc.onlineAttribution && cc.online.length === 0 && (
|
||||
<Tag className="client-count-tag" style={{ margin: 0, padding: '0 2px' }}>
|
||||
{t('online')}: {onlineStatusLabel(cc, t)}
|
||||
</Tag>
|
||||
)}
|
||||
{cc.online.length > 0 && (
|
||||
<Popover
|
||||
title={t('online')}
|
||||
content={
|
||||
<div className="client-email-list">
|
||||
{cc.online.map((e) => (
|
||||
<div key={e}>{e}</div>
|
||||
))}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Tag
|
||||
color="blue"
|
||||
className="client-count-tag"
|
||||
style={{ margin: 0, padding: '0 2px' }}
|
||||
>
|
||||
{cc.online.length}
|
||||
</Tag>
|
||||
</Popover>
|
||||
<ClientEmailBadge
|
||||
emails={cc.online}
|
||||
color="blue"
|
||||
title={`${t('online')}${onlineScope ? ` ${onlineScope}` : ''}`}
|
||||
suffix={onlineScope}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
@@ -477,6 +461,7 @@ export function useInboundColumns({
|
||||
nodesById,
|
||||
hostRemarksByInboundId,
|
||||
clientCount,
|
||||
clientCountsPending,
|
||||
inboundSpeed,
|
||||
subEnable,
|
||||
expireDiff,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { HttpUtil } from '@/utils';
|
||||
@@ -54,9 +54,19 @@ interface ClientRollup {
|
||||
depleted: string[];
|
||||
expiring: string[];
|
||||
online: string[];
|
||||
onlineAttribution: 'pending' | 'unavailable' | 'inbound' | 'node' | 'unsupported';
|
||||
comments: Map<string, string>;
|
||||
}
|
||||
|
||||
interface CachedClientRollup {
|
||||
base: ClientRollup;
|
||||
refreshAt: number;
|
||||
online?: { emails?: Set<string>; result: ClientRollup };
|
||||
}
|
||||
|
||||
const EMPTY_ONLINE: string[] = [];
|
||||
const EMPTY_ROLLUPS: Record<number, ClientRollup> = {};
|
||||
|
||||
const TRACKED_PROTOCOLS: readonly string[] = [
|
||||
Protocols.VMESS,
|
||||
Protocols.VLESS,
|
||||
@@ -101,12 +111,12 @@ async function fetchOnlineClientsByGuid(): Promise<Record<string, string[]>> {
|
||||
// Pairs with the per-node online map so a client attached to several inbounds
|
||||
// is only marked online on the ones that actually moved bytes — Xray's
|
||||
// user-level stat can't attribute traffic to a single inbound on its own.
|
||||
async function fetchActiveInboundsByNode(): Promise<Record<string, string[]>> {
|
||||
async function fetchActiveInboundsByNode(): Promise<Record<string, string[] | null>> {
|
||||
const msg = await HttpUtil.post('/panel/api/clients/activeInbounds', undefined, { silent: true });
|
||||
if (!msg?.success) throw new Error(msg?.msg || 'Failed to fetch activeInbounds');
|
||||
const validated = parseMsg(msg, ActiveInboundsByNodeSchema, 'clients/activeInbounds');
|
||||
return validated.obj && typeof validated.obj === 'object'
|
||||
? (validated.obj as Record<string, string[]>)
|
||||
? (validated.obj as Record<string, string[] | null>)
|
||||
: {};
|
||||
}
|
||||
|
||||
@@ -119,16 +129,41 @@ function toGuidOnlineMap(data: Record<string, string[]>): Map<string, Set<string
|
||||
return map;
|
||||
}
|
||||
|
||||
// Most pushes repeat the previous online sets; handing back a new Map anyway
|
||||
// re-ran the client rollup over every inbound on each traffic event.
|
||||
function sameGuidSets(a: Map<string, Set<string>>, b: Map<string, Set<string>>): boolean {
|
||||
if (a.size !== b.size) return false;
|
||||
for (const [key, set] of b) {
|
||||
const prev = a.get(key);
|
||||
if (!prev || prev.size !== set.size) return false;
|
||||
for (const value of set) if (!prev.has(value)) return false;
|
||||
function toActiveInboundMap(
|
||||
data: Record<string, string[] | null>,
|
||||
): Map<string, Set<string> | null> {
|
||||
const map = new Map<string, Set<string> | null>();
|
||||
for (const [guid, tags] of Object.entries(data)) {
|
||||
if (tags === null) map.set(guid, null);
|
||||
else if (Array.isArray(tags)) map.set(guid, new Set(tags));
|
||||
}
|
||||
return true;
|
||||
return map;
|
||||
}
|
||||
|
||||
function reuseGuidSets<T extends Set<string> | null>(
|
||||
previous: Map<string, T>,
|
||||
next: Map<string, T>,
|
||||
): Map<string, T> {
|
||||
let changed = previous.size !== next.size;
|
||||
for (const [guid, set] of next) {
|
||||
const prior = previous.get(guid);
|
||||
if (prior === set) continue;
|
||||
let same = !!prior && !!set && prior.size === set.size;
|
||||
if (same && prior && set) {
|
||||
for (const value of set) {
|
||||
if (!prior.has(value)) {
|
||||
same = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (same && prior) {
|
||||
next.set(guid, prior);
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed ? next : previous;
|
||||
}
|
||||
|
||||
async function fetchLastOnlineMap(): Promise<Record<string, number>> {
|
||||
@@ -221,6 +256,7 @@ export function useInbounds() {
|
||||
// dbInbounds mirrors the slim query data wrapped as DBInbound instances. The
|
||||
// WS handlers rebuild only the rows they touch, so no refetch is needed.
|
||||
const [dbInbounds, setDbInbounds] = useState<DBInboundInstance[]>([]);
|
||||
const [inboundGeneration, setInboundGeneration] = useState(0);
|
||||
const dbInboundsRef = useRef<DBInboundInstance[]>([]);
|
||||
useEffect(() => {
|
||||
dbInboundsRef.current = dbInbounds;
|
||||
@@ -240,20 +276,16 @@ export function useInbounds() {
|
||||
// hosts it, attributing a sub-node's clients to that sub-node (#4983).
|
||||
const [onlineByGuid, setOnlineByGuid] = useState<Map<string, Set<string>>>(() => new Map());
|
||||
|
||||
// Recently-active inbound tags keyed by the hosting node's panelGuid. A GUID
|
||||
// missing from this map means "no per-inbound activity reported" (e.g. remote
|
||||
// nodes), so the rollup leaves that node's inbounds ungated and falls back to
|
||||
// the email signal. A present GUID gates: a client only counts online on an
|
||||
// inbound whose tag carried traffic this window.
|
||||
const [activeByGuid, setActiveByGuid] = useState<Map<string, Set<string>>>(() => new Map());
|
||||
// An explicit empty set is an idle node. A missing set has no usable activity sample.
|
||||
const [activeByGuid, setActiveByGuid] = useState<Map<string, Set<string> | null>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const onlinePending = onlinesByGuidQuery.isPending || activeInboundsQuery.isPending;
|
||||
|
||||
const [lastOnlineMap, setLastOnlineMap] = useState<Record<string, number>>({});
|
||||
|
||||
const rollupClients = useCallback(
|
||||
(
|
||||
dbInbound: DBInboundInstance,
|
||||
inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] },
|
||||
): ClientRollup => {
|
||||
(dbInbound: DBInboundInstance, now: number): CachedClientRollup => {
|
||||
const clientStats = Array.isArray((dbInbound as { clientStats?: unknown }).clientStats)
|
||||
? (
|
||||
dbInbound as unknown as {
|
||||
@@ -267,29 +299,16 @@ export function useInbounds() {
|
||||
}
|
||||
).clientStats
|
||||
: [];
|
||||
const clients = inbound?.clients || [];
|
||||
const settings = coerceInboundJsonField(dbInbound.settings) as {
|
||||
clients?: { email?: string; enable?: boolean; comment?: string }[];
|
||||
};
|
||||
const clients = Array.isArray(settings.clients) ? settings.clients : [];
|
||||
const active: string[] = [];
|
||||
const deactive: string[] = [];
|
||||
const depleted: string[] = [];
|
||||
const expiring: string[] = [];
|
||||
const online: string[] = [];
|
||||
const comments = new Map<string, string>();
|
||||
const now = Date.now();
|
||||
|
||||
// Attribution key: the GUID of the node that physically hosts this
|
||||
// inbound. Local inbounds carry the panel's own GUID (filled server-side);
|
||||
// a node-managed inbound carries its origin node's GUID, or falls back to
|
||||
// the master-local synthetic id for an old-build node without one (#4983).
|
||||
const guid =
|
||||
dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
|
||||
const nodeOnline = onlineByGuid.get(guid);
|
||||
// A node absent from the active map reports no per-inbound activity, so
|
||||
// leave its inbounds ungated. When present, only mark a client online on
|
||||
// this inbound if its tag actually carried traffic — that's what stops a
|
||||
// multi-inbound client lighting up every inbound it's attached to.
|
||||
const activeForNode = activeByGuid.get(guid);
|
||||
const inboundActive =
|
||||
activeForNode === undefined || !dbInbound.tag || activeForNode.has(dbInbound.tag);
|
||||
let refreshAt = Infinity;
|
||||
|
||||
if (dbInbound.enable) {
|
||||
const statsByEmail = new Map<
|
||||
@@ -310,17 +329,20 @@ export function useInbounds() {
|
||||
depleted.push(client.email);
|
||||
continue;
|
||||
}
|
||||
if (stats && stats.expiryTime > now) refreshAt = Math.min(refreshAt, stats.expiryTime);
|
||||
if (!client.enable) {
|
||||
deactive.push(client.email);
|
||||
continue;
|
||||
}
|
||||
active.push(client.email);
|
||||
if (inboundActive && nodeOnline?.has(client.email)) online.push(client.email);
|
||||
if (stats) {
|
||||
const expiringSoon =
|
||||
(stats.expiryTime > 0 && stats.expiryTime - now < expireDiff) ||
|
||||
(stats.total > 0 && stats.total - (stats.up + stats.down) < trafficDiff);
|
||||
if (expiringSoon) expiring.push(client.email);
|
||||
if (stats.expiryTime > now && !expiringSoon && expireDiff > 0) {
|
||||
refreshAt = Math.min(refreshAt, Math.floor(stats.expiryTime - expireDiff) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -330,38 +352,148 @@ export function useInbounds() {
|
||||
}
|
||||
|
||||
return {
|
||||
clients: clients.length,
|
||||
active,
|
||||
deactive,
|
||||
depleted,
|
||||
expiring,
|
||||
online,
|
||||
comments,
|
||||
base: {
|
||||
clients: clients.length,
|
||||
active,
|
||||
deactive,
|
||||
depleted,
|
||||
expiring,
|
||||
online: EMPTY_ONLINE,
|
||||
onlineAttribution: 'inbound',
|
||||
comments,
|
||||
},
|
||||
refreshAt,
|
||||
};
|
||||
},
|
||||
[onlineByGuid, activeByGuid, expireDiff, trafficDiff],
|
||||
[expireDiff, trafficDiff],
|
||||
);
|
||||
|
||||
// Every write to a DBInbound row also replaces the dbInbounds array, so this
|
||||
// recomputes on both a refetch and a WS-merged stats update.
|
||||
const clientCount = useMemo(() => {
|
||||
const rollupCache = useMemo(
|
||||
() => ({ rows: new WeakMap<DBInboundInstance, CachedClientRollup>(), compute: rollupClients }),
|
||||
[rollupClients],
|
||||
);
|
||||
|
||||
// The WebSocket subscription keeps the callback installed at mount.
|
||||
const rollupCacheRef = useRef(rollupCache);
|
||||
useLayoutEffect(() => {
|
||||
rollupCacheRef.current = rollupCache;
|
||||
}, [rollupCache]);
|
||||
|
||||
const rollupForInbound = useCallback(
|
||||
(dbInbound: DBInboundInstance, now = Date.now()) => {
|
||||
if (!TRACKED_PROTOCOLS.includes(dbInbound.protocol)) return undefined;
|
||||
let rollup = rollupCache.rows.get(dbInbound);
|
||||
if (rollup === undefined || now >= rollup.refreshAt) {
|
||||
rollup = rollupCache.compute(dbInbound, now);
|
||||
rollupCache.rows.set(dbInbound, rollup);
|
||||
}
|
||||
|
||||
// Scope the report to the node that physically hosts this inbound.
|
||||
const guid =
|
||||
dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
|
||||
const nodeOnline = onlineByGuid.get(guid);
|
||||
const activeForNode = activeByGuid.get(guid);
|
||||
let attribution: ClientRollup['onlineAttribution'] = onlinePending
|
||||
? 'pending'
|
||||
: 'unavailable';
|
||||
let inboundActive = false;
|
||||
if (!dbInbound.enable) {
|
||||
attribution = 'inbound';
|
||||
} else if (activeForNode === null) {
|
||||
attribution = nodeOnline === undefined ? 'unsupported' : 'node';
|
||||
inboundActive = true;
|
||||
} else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) {
|
||||
inboundActive = activeForNode.has(dbInbound.tag);
|
||||
// A partial report only vouches for the listed sidecar inbounds.
|
||||
if (inboundActive || !activeForNode.has('\0')) attribution = 'inbound';
|
||||
}
|
||||
|
||||
const emails = inboundActive && nodeOnline?.size ? nodeOnline : undefined;
|
||||
const cached = rollup.online;
|
||||
if (cached && cached.emails === emails && cached.result.onlineAttribution === attribution) {
|
||||
return cached.result;
|
||||
}
|
||||
|
||||
const matched = emails
|
||||
? rollup.base.active.filter((email) => emails.has(email))
|
||||
: EMPTY_ONLINE;
|
||||
const result =
|
||||
matched.length || attribution !== rollup.base.onlineAttribution
|
||||
? { ...rollup.base, online: matched, onlineAttribution: attribution }
|
||||
: rollup.base;
|
||||
rollup.online = { emails, result };
|
||||
return result;
|
||||
},
|
||||
[rollupCache, activeByGuid, onlineByGuid, onlinePending],
|
||||
);
|
||||
|
||||
const largeList = useMemo(
|
||||
() =>
|
||||
dbInbounds.reduce((size, row) => {
|
||||
const settings = row.settings;
|
||||
const objectClients =
|
||||
settings && typeof settings === 'object' && !Array.isArray(settings)
|
||||
? settings.clients
|
||||
: undefined;
|
||||
return (
|
||||
size +
|
||||
(typeof settings === 'string' ? settings.length : 0) +
|
||||
(Array.isArray(objectClients) ? objectClients.length * 64 : 0) +
|
||||
(Array.isArray(row.clientStats) ? row.clientStats.length * 100 : 0)
|
||||
);
|
||||
}, 0) >
|
||||
256 * 1024,
|
||||
[dbInbounds],
|
||||
);
|
||||
const [scheduled, setScheduled] = useState<{
|
||||
generation: number;
|
||||
counts: Record<number, ClientRollup>;
|
||||
}>();
|
||||
useEffect(() => {
|
||||
if (!largeList) return;
|
||||
const counts: Record<number, ClientRollup> = {};
|
||||
for (const dbInbound of dbInbounds) {
|
||||
const protocol = dbInbound.protocol;
|
||||
if (!TRACKED_PROTOCOLS.includes(protocol)) continue;
|
||||
const settings = coerceInboundJsonField(dbInbound.settings) as {
|
||||
clients?: Array<{ email?: string; enable?: boolean; comment?: string }>;
|
||||
};
|
||||
counts[dbInbound.id] = rollupClients(dbInbound, { clients: settings.clients });
|
||||
const now = Date.now();
|
||||
let index = 0;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
function computeSlice() {
|
||||
const end = performance.now() + 8;
|
||||
do {
|
||||
const row = dbInbounds[index++];
|
||||
const rollup = rollupForInbound(row, now);
|
||||
if (rollup) counts[row.id] = rollup;
|
||||
} while (index < dbInbounds.length && performance.now() < end);
|
||||
if (index < dbInbounds.length) {
|
||||
timer = setTimeout(computeSlice, 0);
|
||||
} else {
|
||||
setScheduled({ generation: inboundGeneration, counts });
|
||||
}
|
||||
}
|
||||
timer = setTimeout(computeSlice, 0);
|
||||
return () => clearTimeout(timer);
|
||||
}, [largeList, dbInbounds, inboundGeneration, rollupForInbound]);
|
||||
|
||||
const syncCounts = useMemo(() => {
|
||||
if (largeList) return EMPTY_ROLLUPS;
|
||||
const counts: Record<number, ClientRollup> = {};
|
||||
for (const row of dbInbounds) {
|
||||
const rollup = rollupForInbound(row);
|
||||
if (rollup) counts[row.id] = rollup;
|
||||
}
|
||||
return counts;
|
||||
}, [dbInbounds, rollupClients]);
|
||||
}, [largeList, dbInbounds, rollupForInbound]);
|
||||
// Online and counter updates can reuse the last rollup while the next slice
|
||||
// runs, but a refetch or hydration may have changed the client membership.
|
||||
const rollupsReady = !largeList || scheduled?.generation === inboundGeneration;
|
||||
const clientCount = largeList
|
||||
? ((rollupsReady ? scheduled?.counts : undefined) ?? EMPTY_ROLLUPS)
|
||||
: syncCounts;
|
||||
|
||||
// Adopting fetched data during render (rather than in an effect) keeps the
|
||||
// list from painting one frame of the previous data after a refetch.
|
||||
const [syncedSlim, setSyncedSlim] = useState<unknown>();
|
||||
if (slimQuery.data && slimQuery.data !== syncedSlim) {
|
||||
setSyncedSlim(slimQuery.data);
|
||||
setInboundGeneration((generation) => generation + 1);
|
||||
setDbInbounds(
|
||||
(slimQuery.data as { protocol: string; id: number }[]).map(
|
||||
(row) => new DBInbound(row) as DBInboundInstance,
|
||||
@@ -384,7 +516,7 @@ export function useInbounds() {
|
||||
const [syncedActiveInbounds, setSyncedActiveInbounds] = useState<unknown>();
|
||||
if (activeInboundsQuery.data && activeInboundsQuery.data !== syncedActiveInbounds) {
|
||||
setSyncedActiveInbounds(activeInboundsQuery.data);
|
||||
setActiveByGuid(toGuidOnlineMap(activeInboundsQuery.data));
|
||||
setActiveByGuid(toActiveInboundMap(activeInboundsQuery.data));
|
||||
}
|
||||
|
||||
const [syncedLastOnline, setSyncedLastOnline] = useState<unknown>();
|
||||
@@ -426,6 +558,7 @@ export function useInbounds() {
|
||||
const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`);
|
||||
if (!validated.obj) return null;
|
||||
const dbInbound = new DBInbound(validated.obj) as DBInboundInstance;
|
||||
setInboundGeneration((generation) => generation + 1);
|
||||
setDbInbounds((prev) => {
|
||||
const next = prev.map((row) =>
|
||||
(row as unknown as { id: number }).id === id ? dbInbound : row,
|
||||
@@ -443,7 +576,7 @@ export function useInbounds() {
|
||||
nodeTraffics?: TrafficDelta[];
|
||||
onlineClients?: string[];
|
||||
onlineByGuid?: Record<string, string[]>;
|
||||
activeInbounds?: Record<string, string[]>;
|
||||
activeInbounds?: Record<string, string[] | null>;
|
||||
lastOnlineMap?: Record<string, number>;
|
||||
};
|
||||
if (Array.isArray(p.onlineClients)) {
|
||||
@@ -451,11 +584,11 @@ export function useInbounds() {
|
||||
}
|
||||
if (p.onlineByGuid && typeof p.onlineByGuid === 'object') {
|
||||
const next = toGuidOnlineMap(p.onlineByGuid);
|
||||
setOnlineByGuid((prev) => (sameGuidSets(prev, next) ? prev : next));
|
||||
setOnlineByGuid((prev) => reuseGuidSets(prev, next));
|
||||
}
|
||||
if (p.activeInbounds && typeof p.activeInbounds === 'object') {
|
||||
const next = toGuidOnlineMap(p.activeInbounds);
|
||||
setActiveByGuid((prev) => (sameGuidSets(prev, next) ? prev : next));
|
||||
const next = toActiveInboundMap(p.activeInbounds);
|
||||
setActiveByGuid((prev) => reuseGuidSets(prev, next));
|
||||
}
|
||||
if (p.lastOnlineMap && typeof p.lastOnlineMap === 'object') {
|
||||
setLastOnlineMap((prev) => ({ ...prev, ...p.lastOnlineMap! }));
|
||||
@@ -587,6 +720,11 @@ export function useInbounds() {
|
||||
if (typeof upd.enable === 'boolean') row.enable = upd.enable;
|
||||
}
|
||||
if (statsTouched && nextStats) row.clientStats = nextStats;
|
||||
if (!statsTouched && ib.enable === row.enable) {
|
||||
const cache = rollupCacheRef.current.rows;
|
||||
const cached = cache.get(ib);
|
||||
if (cached) cache.set(row, cached);
|
||||
}
|
||||
return row;
|
||||
});
|
||||
|
||||
@@ -611,6 +749,7 @@ export function useInbounds() {
|
||||
fetchError,
|
||||
dbInbounds,
|
||||
clientCount,
|
||||
clientCountsPending: !rollupsReady,
|
||||
onlineClients,
|
||||
lastOnlineMap,
|
||||
inboundSpeed,
|
||||
|
||||
@@ -4,8 +4,6 @@ import { Card, theme } from 'antd';
|
||||
|
||||
import { Sparkline } from '@/components/viz';
|
||||
import type { Status } from '@/models/status';
|
||||
import OverviewRangeSelect from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface ConnectionsCardProps {
|
||||
status: Status;
|
||||
@@ -13,8 +11,6 @@ interface ConnectionsCardProps {
|
||||
udp: number[];
|
||||
labels: string[];
|
||||
isMobile: boolean;
|
||||
range: OverviewRange;
|
||||
onRangeChange: (range: OverviewRange) => void;
|
||||
}
|
||||
|
||||
export default function ConnectionsCard({
|
||||
@@ -23,8 +19,6 @@ export default function ConnectionsCard({
|
||||
udp,
|
||||
labels,
|
||||
isMobile,
|
||||
range,
|
||||
onRangeChange,
|
||||
}: ConnectionsCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
@@ -49,9 +43,6 @@ export default function ConnectionsCard({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ov-range-toolbar">
|
||||
<OverviewRangeSelect value={range} onChange={onRangeChange} />
|
||||
</div>
|
||||
<div className="ov-conn-legend">
|
||||
<div className="ov-legend-label">
|
||||
<span className="ov-swatch" style={{ background: accent }} />
|
||||
|
||||
@@ -133,6 +133,12 @@
|
||||
}
|
||||
}
|
||||
|
||||
.ov-bar-range {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.ov-bar-sep {
|
||||
width: 1px;
|
||||
height: 20px;
|
||||
@@ -284,12 +290,13 @@
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.ov-range-toolbar {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
top: 14px;
|
||||
right: var(--ov-pad);
|
||||
display: flex;
|
||||
.ov-range-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--ov-label);
|
||||
}
|
||||
|
||||
.ov-range-select {
|
||||
|
||||
@@ -30,6 +30,7 @@ import ThroughputCard from './ThroughputCard';
|
||||
import ConnectionsCard from './ConnectionsCard';
|
||||
import SystemStrip from './SystemStrip';
|
||||
import { mean, peak, useOverviewHistory } from './useOverviewHistory';
|
||||
import { OVERVIEW_RANGES } from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
import type { PanelUpdateInfo } from './PanelUpdateModal';
|
||||
const JsonEditor = lazy(() => import('@/components/form/JsonEditor'));
|
||||
@@ -52,6 +53,15 @@ function metricFoot(label: string, value: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function readHistoryRange(key: string): OverviewRange {
|
||||
try {
|
||||
const saved = localStorage.getItem(key);
|
||||
return OVERVIEW_RANGES.find((range) => String(range) === saved) ?? 2;
|
||||
} catch {
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
export default function IndexPage() {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, antdThemeConfig } = useTheme();
|
||||
@@ -86,7 +96,16 @@ export default function IndexPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadingTip, setLoadingTip] = useState(t('loading'));
|
||||
|
||||
const [historyRange, setHistoryRange] = useState<OverviewRange>(2);
|
||||
const historyRangeKey = '3x-ui:overview-range:' + (basePath || '/');
|
||||
const [historyRange, setHistoryRange] = useState(() => readHistoryRange(historyRangeKey));
|
||||
const changeHistoryRange = (range: OverviewRange) => {
|
||||
setHistoryRange(range);
|
||||
try {
|
||||
localStorage.setItem(historyRangeKey, String(range));
|
||||
} catch {
|
||||
// A blocked browser store should still allow changes for this visit.
|
||||
}
|
||||
};
|
||||
const history = useOverviewHistory(status, fetched && !fetchError, historyRange);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -213,6 +232,8 @@ export default function IndexPage() {
|
||||
panelVersion={displayVersion}
|
||||
latestVersion={panelUpdateInfo.latestVersion}
|
||||
updateAvailable={panelUpdateInfo.updateAvailable}
|
||||
historyRange={historyRange}
|
||||
onHistoryRangeChange={changeHistoryRange}
|
||||
onStopXray={stopXray}
|
||||
onRestartXray={restartXray}
|
||||
onOpenLogs={() => setLogsOpen(true)}
|
||||
@@ -247,7 +268,11 @@ export default function IndexPage() {
|
||||
detail={
|
||||
status.resourceScope === 'container'
|
||||
? `${status.logicalPro} vCPU`
|
||||
: `${CPUFormatter.cpuCoreFormat(status.cpuCores)} / ${status.logicalPro}T · ${CPUFormatter.cpuSpeedFormat(status.cpuSpeedMhz)}`
|
||||
: CPUFormatter.cpuSpecFormat(
|
||||
status.cpuCores,
|
||||
status.logicalPro,
|
||||
status.cpuSpeedMhz,
|
||||
)
|
||||
}
|
||||
footLeft={metricFoot(
|
||||
t('pages.index.avg'),
|
||||
@@ -259,8 +284,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.cpu}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<VitalTile
|
||||
icon={<DatabaseOutlined aria-hidden />}
|
||||
@@ -278,8 +301,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.mem}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<VitalTile
|
||||
icon={<SwapOutlined aria-hidden />}
|
||||
@@ -298,8 +319,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.swap}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<VitalTile
|
||||
icon={<HddOutlined aria-hidden />}
|
||||
@@ -317,8 +336,6 @@ export default function IndexPage() {
|
||||
)}
|
||||
data={history.series.diskUsage}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -329,8 +346,6 @@ export default function IndexPage() {
|
||||
down={history.series.netDown}
|
||||
labels={history.labels}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
<ConnectionsCard
|
||||
status={status}
|
||||
@@ -338,8 +353,6 @@ export default function IndexPage() {
|
||||
udp={history.series.udpCount}
|
||||
labels={history.labels}
|
||||
isMobile={isMobile}
|
||||
range={historyRange}
|
||||
onRangeChange={setHistoryRange}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { formatPanelVersion } from '@/lib/panel-version';
|
||||
import { activateOnKey } from '@/utils/a11y';
|
||||
import type { Status } from '@/models/status';
|
||||
import OverviewRangeSelect, { type OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface OverviewActionBarProps {
|
||||
status: Status;
|
||||
@@ -27,6 +28,8 @@ interface OverviewActionBarProps {
|
||||
panelVersion: string;
|
||||
latestVersion: string;
|
||||
updateAvailable: boolean;
|
||||
historyRange: OverviewRange;
|
||||
onHistoryRangeChange: (range: OverviewRange) => void;
|
||||
onStopXray: () => void | Promise<void>;
|
||||
onRestartXray: () => void;
|
||||
onOpenLogs: () => void;
|
||||
@@ -64,6 +67,8 @@ export default function OverviewActionBar({
|
||||
panelVersion,
|
||||
latestVersion,
|
||||
updateAvailable,
|
||||
historyRange,
|
||||
onHistoryRangeChange,
|
||||
onStopXray,
|
||||
onRestartXray,
|
||||
onOpenLogs,
|
||||
@@ -158,12 +163,6 @@ export default function OverviewActionBar({
|
||||
text: t('pages.index.systemHistoryTitle'),
|
||||
onClick: onOpenSystemHistory,
|
||||
},
|
||||
{
|
||||
key: 'metrics',
|
||||
icon: <ArrowUpOutlined aria-hidden />,
|
||||
text: t('pages.index.xrayMetricsTitle'),
|
||||
onClick: onOpenXrayMetrics,
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
@@ -241,6 +240,18 @@ export default function OverviewActionBar({
|
||||
))}
|
||||
</Fragment>
|
||||
))}
|
||||
<div className="ov-bar-range">
|
||||
<Button
|
||||
type="text"
|
||||
size={size}
|
||||
icon={<ArrowUpOutlined aria-hidden />}
|
||||
aria-label={t('pages.index.xrayMetricsTitle')}
|
||||
onClick={onOpenXrayMetrics}
|
||||
>
|
||||
{isMobile ? undefined : t('pages.index.xrayMetricsTitle')}
|
||||
</Button>
|
||||
<OverviewRangeSelect value={historyRange} onChange={onHistoryRangeChange} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -9,26 +9,27 @@ interface OverviewRangeSelectProps {
|
||||
onChange: (value: OverviewRange) => void;
|
||||
}
|
||||
|
||||
const OPTIONS = [
|
||||
{ value: 2, label: '2m' },
|
||||
{ value: 5, label: '5m' },
|
||||
{ value: 30, label: '30m' },
|
||||
{ value: 60, label: '1h' },
|
||||
{ value: 360, label: '6h' },
|
||||
{ value: 720, label: '12h' },
|
||||
];
|
||||
const OPTIONS = OVERVIEW_RANGES.map((value) => ({
|
||||
value,
|
||||
label: value < 60 ? String(value) + 'm' : String(value / 60) + 'h',
|
||||
}));
|
||||
|
||||
export default function OverviewRangeSelect({ value, onChange }: OverviewRangeSelectProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const label = t('pages.index.timeRange');
|
||||
return (
|
||||
<Select
|
||||
aria-label={t('pages.index.timeRange')}
|
||||
className="ov-range-select"
|
||||
size="small"
|
||||
value={value}
|
||||
options={OPTIONS}
|
||||
onChange={(next: number) => onChange(next as OverviewRange)}
|
||||
/>
|
||||
<span className="ov-range-control">
|
||||
<span aria-hidden>{label}</span>
|
||||
<Select<OverviewRange>
|
||||
aria-label={label}
|
||||
className="ov-range-select"
|
||||
size="small"
|
||||
value={value}
|
||||
options={OPTIONS}
|
||||
virtual={false}
|
||||
onChange={(next) => onChange(next)}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,8 +7,6 @@ import { SizeFormatter } from '@/utils';
|
||||
import { Sparkline } from '@/components/viz';
|
||||
import type { Status } from '@/models/status';
|
||||
import { mean, peak } from './useOverviewHistory';
|
||||
import OverviewRangeSelect from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface ThroughputCardProps {
|
||||
status: Status;
|
||||
@@ -16,8 +14,6 @@ interface ThroughputCardProps {
|
||||
down: number[];
|
||||
labels: string[];
|
||||
isMobile: boolean;
|
||||
range: OverviewRange;
|
||||
onRangeChange: (range: OverviewRange) => void;
|
||||
}
|
||||
|
||||
export default function ThroughputCard({
|
||||
@@ -26,8 +22,6 @@ export default function ThroughputCard({
|
||||
down,
|
||||
labels,
|
||||
isMobile,
|
||||
range,
|
||||
onRangeChange,
|
||||
}: ThroughputCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
@@ -83,9 +77,6 @@ export default function ThroughputCard({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="ov-range-toolbar">
|
||||
<OverviewRangeSelect value={range} onChange={onRangeChange} />
|
||||
</div>
|
||||
<div className="ov-wide-chart">
|
||||
<Sparkline
|
||||
data={available ? up : []}
|
||||
|
||||
@@ -4,8 +4,6 @@ import { Card, theme } from 'antd';
|
||||
|
||||
import { Sparkline } from '@/components/viz';
|
||||
import { mean, peak } from './useOverviewHistory';
|
||||
import OverviewRangeSelect from './OverviewRangeSelect';
|
||||
import type { OverviewRange } from './OverviewRangeSelect';
|
||||
|
||||
interface VitalTileProps {
|
||||
available?: boolean;
|
||||
@@ -18,12 +16,8 @@ interface VitalTileProps {
|
||||
footRight: ReactNode;
|
||||
data: number[];
|
||||
isMobile: boolean;
|
||||
range?: OverviewRange;
|
||||
onRangeChange?: (range: OverviewRange) => void;
|
||||
}
|
||||
|
||||
const ignoreRangeChange = () => undefined;
|
||||
|
||||
export default function VitalTile({
|
||||
available = true,
|
||||
icon,
|
||||
@@ -35,8 +29,6 @@ export default function VitalTile({
|
||||
footRight,
|
||||
data,
|
||||
isMobile,
|
||||
range = 2,
|
||||
onRangeChange = ignoreRangeChange,
|
||||
}: VitalTileProps) {
|
||||
const { token } = theme.useToken();
|
||||
const labelId = useId();
|
||||
@@ -74,9 +66,6 @@ export default function VitalTile({
|
||||
<span dir="auto">{available ? footRight : '—'}</span>
|
||||
</div>
|
||||
|
||||
<div className="ov-range-toolbar">
|
||||
<OverviewRangeSelect value={range} onChange={onRangeChange} />
|
||||
</div>
|
||||
<div className="ov-tile-chart">
|
||||
<Sparkline
|
||||
data={data}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { HttpUtil, TimeFormatter } from '@/utils';
|
||||
import type { Status } from '@/models/status';
|
||||
@@ -81,25 +81,35 @@ export function peak(values: number[]): number {
|
||||
|
||||
/* the seed bucket must be in the backend's allowedHistoryBuckets whitelist;
|
||||
2s is the smallest and matches the status poll cadence */
|
||||
function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
const [trend, setTrend] = useState<HistoryWindow>(emptyWindow);
|
||||
interface LiveHistoryWindow extends HistoryWindow {
|
||||
scopeEpoch: number;
|
||||
scopeSeeded: boolean;
|
||||
unscopedSeeded: boolean;
|
||||
scopeSampledAt?: number;
|
||||
}
|
||||
|
||||
const seededUnscoped = useRef(false);
|
||||
const seedState = useRef<{ scope: string; complete: boolean } | null>(null);
|
||||
function seedTimesBefore(times: Iterable<number>, firstSample: number, windowStart: number) {
|
||||
return [...new Set(times)]
|
||||
.filter((t) => t >= windowStart && t + SEED_BUCKET_SECONDS <= firstSample)
|
||||
.sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
function useLiveTrend(status: Status, hasData: boolean, enabled: boolean): OverviewHistory {
|
||||
const [trend, setTrend] = useState<LiveHistoryWindow>(() => ({
|
||||
...emptyWindow(),
|
||||
scopeEpoch: 0,
|
||||
scopeSeeded: false,
|
||||
unscopedSeeded: false,
|
||||
}));
|
||||
const { scopeEpoch, scopeSeeded, unscopedSeeded } = trend;
|
||||
const scope = status.resourceScope;
|
||||
|
||||
useEffect(() => {
|
||||
// The placeholder has no resource scope. Wait for the first real status,
|
||||
// then seed each scope once even if polling temporarily loses data.
|
||||
if (
|
||||
!hasData ||
|
||||
(seedState.current?.scope === status.resourceScope && seedState.current.complete)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
seedState.current = { scope: status.resourceScope, complete: false };
|
||||
if (!enabled || !hasData || scopeSeeded) return;
|
||||
let cancelled = false;
|
||||
const seedUnscoped = !seededUnscoped.current;
|
||||
const keys = seedUnscoped ? SERIES_KEYS : (['cpu', 'swap'] as const);
|
||||
const keys = unscopedSeeded ? (['cpu', 'swap'] as const) : SERIES_KEYS;
|
||||
|
||||
const seed = async () => {
|
||||
const responses = new Map<OverviewSeriesKey, HistoryPoint[]>();
|
||||
@@ -114,35 +124,45 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
}),
|
||||
);
|
||||
if (cancelled || responses.size === 0) return;
|
||||
seedState.current = { scope: status.resourceScope, complete: true };
|
||||
seededUnscoped.current = true;
|
||||
|
||||
let axis: HistoryPoint[] = [];
|
||||
for (const points of responses.values()) {
|
||||
if (points.length > axis.length) axis = points;
|
||||
}
|
||||
axis = tailWindow(axis);
|
||||
if (axis.length === 0) return;
|
||||
|
||||
const seedTimes = axis.map((p) => Number(p.t) || 0);
|
||||
const seedSeries = emptySeries();
|
||||
for (const key of SERIES_KEYS) {
|
||||
const byTs = new Map<number, number>();
|
||||
for (const p of responses.get(key) ?? []) byTs.set(Number(p.t) || 0, Number(p.v) || 0);
|
||||
seedSeries[key] =
|
||||
status.resourceScope && (key === 'cpu' || key === 'swap')
|
||||
? seedTimes.flatMap((ts) => (byTs.has(ts) ? [byTs.get(ts)!] : []))
|
||||
: seedTimes.map((ts) => byTs.get(ts) ?? 0);
|
||||
}
|
||||
|
||||
const axisTimes = axis.map((p) => Number(p.t));
|
||||
setTrend((prev) => {
|
||||
const merged = emptyWindow();
|
||||
merged.times = seedUnscoped ? tailWindow(seedTimes.concat(prev.times)) : prev.times;
|
||||
for (const key of SERIES_KEYS) {
|
||||
merged.series[key] =
|
||||
seedUnscoped || key === 'cpu' || key === 'swap'
|
||||
? tailWindow(seedSeries[key].concat(prev.series[key]))
|
||||
: prev.series[key];
|
||||
if (prev.scopeEpoch !== scopeEpoch) return prev;
|
||||
// With no server timestamp on live samples, only join buckets inside the browser's window.
|
||||
const windowStart =
|
||||
prev.times[prev.times.length - 1] - OVERVIEW_WINDOW * LIVE_BUCKET_SECONDS;
|
||||
const unscopedTimes = unscopedSeeded
|
||||
? []
|
||||
: seedTimesBefore(axisTimes, prev.times[0], windowStart);
|
||||
const firstScopedSample = prev.scopeSampledAt ?? prev.times[0];
|
||||
const merged = {
|
||||
...prev,
|
||||
scopeSeeded: true,
|
||||
unscopedSeeded: true,
|
||||
times: unscopedTimes.length ? tailWindow(unscopedTimes.concat(prev.times)) : prev.times,
|
||||
series: { ...prev.series },
|
||||
};
|
||||
for (const key of keys) {
|
||||
const scoped = key === 'cpu' || key === 'swap';
|
||||
const byTime = new Map(
|
||||
(responses.get(key) ?? []).map((p) => [Number(p.t), Number(p.v) || 0]),
|
||||
);
|
||||
const seedTimes = scoped
|
||||
? seedTimesBefore(
|
||||
scope ? byTime.keys() : [...axisTimes, ...byTime.keys()],
|
||||
firstScopedSample,
|
||||
windowStart,
|
||||
)
|
||||
: unscopedTimes;
|
||||
if (seedTimes.length) {
|
||||
merged.series[key] = tailWindow(
|
||||
seedTimes.map((t) => byTime.get(t) ?? 0).concat(prev.series[key]),
|
||||
);
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
});
|
||||
@@ -152,7 +172,7 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hasData, status.resourceScope]);
|
||||
}, [enabled, hasData, scope, scopeEpoch, scopeSeeded, unscopedSeeded]);
|
||||
|
||||
// Each polled status is appended during render; an effect would show the
|
||||
// chart one sample behind the numbers beside it.
|
||||
@@ -160,10 +180,17 @@ function useLiveTrend(status: Status, hasData: boolean): OverviewHistory {
|
||||
if (hasData && status !== sampledStatus) {
|
||||
setSampledStatus(status);
|
||||
setTrend((prev) => {
|
||||
const scopeChanged = sampledStatus && sampledStatus.resourceScope !== status.resourceScope;
|
||||
const sampledAt = Math.floor(Date.now() / 1000);
|
||||
const scopeChanged = sampledStatus !== null && sampledStatus.resourceScope !== scope;
|
||||
const point = sampleOf(status);
|
||||
const next = emptyWindow();
|
||||
next.times = tailWindow(prev.times.concat(Math.floor(Date.now() / 1000)));
|
||||
const next = {
|
||||
...prev,
|
||||
series: emptySeries(),
|
||||
scopeEpoch: prev.scopeEpoch + Number(scopeChanged),
|
||||
scopeSeeded: prev.scopeSeeded && !scopeChanged,
|
||||
scopeSampledAt: scopeChanged ? sampledAt : (prev.scopeSampledAt ?? sampledAt),
|
||||
};
|
||||
next.times = tailWindow(prev.times.concat(sampledAt));
|
||||
for (const key of SERIES_KEYS) {
|
||||
const scoped = key === 'cpu' || key === 'swap';
|
||||
const previous = scoped && scopeChanged ? [] : prev.series[key];
|
||||
@@ -270,7 +297,7 @@ export function useOverviewHistory(
|
||||
hasData: boolean,
|
||||
bucketSeconds: number = LIVE_BUCKET_SECONDS,
|
||||
): OverviewHistory {
|
||||
const live = useLiveTrend(status, hasData);
|
||||
const live = useLiveTrend(status, hasData, bucketSeconds === LIVE_BUCKET_SECONDS);
|
||||
const ranged = useRangedHistory(
|
||||
status,
|
||||
hasData && bucketSeconds !== LIVE_BUCKET_SECONDS,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Checkbox,
|
||||
Col,
|
||||
Form,
|
||||
Input,
|
||||
@@ -36,8 +38,8 @@ interface NodeFormModalProps {
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
function defaultValues(): NodeFormValues {
|
||||
return {
|
||||
function initialFormValues(node: NodeRecord | null): NodeFormValues {
|
||||
const defaults: NodeFormValues = {
|
||||
id: 0,
|
||||
name: '',
|
||||
remark: '',
|
||||
@@ -55,9 +57,64 @@ function defaultValues(): NodeFormValues {
|
||||
inboundTags: [],
|
||||
outboundTag: '',
|
||||
};
|
||||
if (!node) return defaults;
|
||||
return {
|
||||
...defaults,
|
||||
...(node as unknown as Partial<NodeFormValues>),
|
||||
id: node.id,
|
||||
scheme: node.scheme === 'http' ? 'http' : 'https',
|
||||
tlsVerifyMode: node.scheme === 'http' ? 'skip' : (node.tlsVerifyMode ?? 'verify'),
|
||||
inboundSyncMode: node.inboundSyncMode === 'selected' ? 'selected' : 'all',
|
||||
inboundTags: node.inboundTags ?? [],
|
||||
apiToken: '',
|
||||
hasStoredToken: node.hasApiToken ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
export default function NodeFormModal({
|
||||
function NodeTokenInput({ value, onChange, ...props }: ComponentProps<typeof Input.Password>) {
|
||||
const text = String(value ?? '');
|
||||
const restore = (input: HTMLInputElement) => {
|
||||
if (input.value !== text) input.value = text;
|
||||
};
|
||||
|
||||
return (
|
||||
<Input.Password
|
||||
{...props}
|
||||
value={text}
|
||||
autoComplete="new-password"
|
||||
spellCheck={false}
|
||||
onFocus={(event) => restore(event.currentTarget)}
|
||||
onKeyDown={(event) => restore(event.currentTarget)}
|
||||
onPaste={(event) => restore(event.currentTarget)}
|
||||
onBeforeInput={(event) => restore(event.currentTarget)}
|
||||
onChange={(event) => {
|
||||
// Ignore autofill replacements and generic change events. Only explicit
|
||||
// input edits can change the credential held by the form.
|
||||
const inputType = (event.nativeEvent as InputEvent).inputType;
|
||||
if (
|
||||
inputType === 'insertText' ||
|
||||
inputType === 'insertFromPaste' ||
|
||||
inputType === 'insertCompositionText' ||
|
||||
inputType === 'insertFromComposition' ||
|
||||
inputType === 'historyUndo' ||
|
||||
inputType === 'historyRedo' ||
|
||||
inputType?.startsWith('delete')
|
||||
) {
|
||||
onChange?.(event);
|
||||
} else {
|
||||
restore(event.currentTarget);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default function NodeFormModal(props: NodeFormModalProps) {
|
||||
if (!props.open) return null;
|
||||
return <NodeFormSession key={`${props.mode}:${props.node?.id ?? 0}`} {...props} />;
|
||||
}
|
||||
|
||||
function NodeFormSession({
|
||||
open,
|
||||
mode,
|
||||
node,
|
||||
@@ -68,15 +125,26 @@ export default function NodeFormModal({
|
||||
onOpenChange,
|
||||
}: NodeFormModalProps) {
|
||||
const { t } = useTranslation();
|
||||
const methods = useForm<NodeFormValues>({ defaultValues: defaultValues() });
|
||||
const [initialValues] = useState(() => initialFormValues(mode === 'edit' ? node : null));
|
||||
const methods = useForm<NodeFormValues>({ defaultValues: initialValues });
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
const active = useRef(false);
|
||||
useEffect(() => {
|
||||
active.current = true;
|
||||
return () => {
|
||||
active.current = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [testing, setTesting] = useState(false);
|
||||
const [fetchingPin, setFetchingPin] = useState(false);
|
||||
const [fetchingInbounds, setFetchingInbounds] = useState(false);
|
||||
const [inboundOptions, setInboundOptions] = useState<RemoteInboundOption[]>([]);
|
||||
const [inboundOptions, setInboundOptions] = useState<RemoteInboundOption[]>(() =>
|
||||
initialValues.inboundTags.map((tag) => ({ tag })),
|
||||
);
|
||||
const [testResult, setTestResult] = useState<ProbeResult | null>(null);
|
||||
const [replacingToken, setReplacingToken] = useState(false);
|
||||
const scheme = useWatch({ control: methods.control, name: 'scheme' }) ?? 'https';
|
||||
const tlsVerifyMode = useWatch({ control: methods.control, name: 'tlsVerifyMode' }) ?? 'verify';
|
||||
const inboundSyncMode = useWatch({ control: methods.control, name: 'inboundSyncMode' }) ?? 'all';
|
||||
@@ -104,41 +172,16 @@ export default function NodeFormModal({
|
||||
];
|
||||
}, [outboundGroups, t]);
|
||||
|
||||
// Reset during render, not in an effect, so the first frame is already clean.
|
||||
const [synced, setSynced] = useState<{ mode: string; node: NodeRecord | null } | null>(null);
|
||||
if (!open) {
|
||||
if (synced) setSynced(null);
|
||||
} else if (!synced || synced.mode !== mode || synced.node !== (node ?? null)) {
|
||||
setSynced({ mode, node: node ?? null });
|
||||
const base = defaultValues();
|
||||
const next: NodeFormValues =
|
||||
mode === 'edit' && node
|
||||
? {
|
||||
...base,
|
||||
...(node as unknown as Partial<NodeFormValues>),
|
||||
id: node.id,
|
||||
scheme: (node.scheme as 'http' | 'https') || base.scheme,
|
||||
inboundSyncMode: (node.inboundSyncMode as 'all' | 'selected') || base.inboundSyncMode,
|
||||
inboundTags: node.inboundTags ?? [],
|
||||
apiToken: '',
|
||||
hasStoredToken: node.hasApiToken ?? false,
|
||||
}
|
||||
: base;
|
||||
if (next.scheme === 'http') next.tlsVerifyMode = 'skip';
|
||||
methods.reset(next);
|
||||
setInboundOptions((next.inboundTags || []).map((tag) => ({ tag })));
|
||||
setTestResult(null);
|
||||
}
|
||||
|
||||
const title = useMemo(
|
||||
() => (mode === 'edit' ? t('pages.nodes.editNode') : t('pages.nodes.addNode')),
|
||||
[mode, t],
|
||||
);
|
||||
|
||||
const editingWithToken = mode === 'edit' && Boolean(node?.hasApiToken);
|
||||
const editingWithToken = initialValues.hasStoredToken;
|
||||
const canEnterToken = !editingWithToken || replacingToken;
|
||||
|
||||
function buildPayload(values: NodeFormValues): Partial<NodeRecord> {
|
||||
const token = values.apiToken.trim();
|
||||
const token = canEnterToken ? values.apiToken.trim() : '';
|
||||
const payload: Partial<NodeRecord> = {
|
||||
id: values.id || 0,
|
||||
name: values.name.trim(),
|
||||
@@ -219,6 +262,7 @@ export default function NodeFormModal({
|
||||
try {
|
||||
const payload = buildPayload(result.data);
|
||||
const test = await testConnection(payload);
|
||||
if (!active.current) return;
|
||||
const probe = test?.success ? test.obj : null;
|
||||
if (!probe || probe.status !== 'online') {
|
||||
setTestResult(
|
||||
@@ -228,7 +272,7 @@ export default function NodeFormModal({
|
||||
}
|
||||
setTestResult(probe);
|
||||
const msg = await save(payload);
|
||||
if (msg?.success) {
|
||||
if (msg?.success && active.current) {
|
||||
onOpenChange(false);
|
||||
}
|
||||
} finally {
|
||||
@@ -251,7 +295,7 @@ export default function NodeFormModal({
|
||||
cancelText={t('cancel')}
|
||||
mask={{ closable: false }}
|
||||
width="640px"
|
||||
onOk={methods.handleSubmit(onFinish)}
|
||||
onOk={() => void methods.handleSubmit(onFinish)()}
|
||||
onCancel={close}
|
||||
>
|
||||
<FormProvider {...methods}>
|
||||
@@ -381,21 +425,30 @@ export default function NodeFormModal({
|
||||
</FormField>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
label={t('pages.nodes.apiToken')}
|
||||
name="apiToken"
|
||||
rules={{ validate: rhfZodValidate(NodeFormSchema.shape.apiToken) }}
|
||||
tooltip={t('pages.nodes.apiTokenHint')}
|
||||
extra={editingWithToken ? t('pages.nodes.apiTokenKeepHint') : undefined}
|
||||
>
|
||||
<Input.Password
|
||||
placeholder={
|
||||
editingWithToken
|
||||
? t('pages.nodes.apiTokenKeepHint')
|
||||
: t('pages.nodes.apiTokenPlaceholder')
|
||||
}
|
||||
/>
|
||||
</FormField>
|
||||
{editingWithToken && (
|
||||
<Form.Item extra={t('pages.nodes.apiTokenKeepHint')}>
|
||||
<Checkbox
|
||||
checked={replacingToken}
|
||||
onChange={(event) => {
|
||||
methods.setValue('apiToken', '');
|
||||
setReplacingToken(event.target.checked);
|
||||
setTestResult(null);
|
||||
}}
|
||||
>
|
||||
{t('pages.nodes.apiTokenReplace')}
|
||||
</Checkbox>
|
||||
</Form.Item>
|
||||
)}
|
||||
{canEnterToken && (
|
||||
<FormField
|
||||
label={t('pages.nodes.apiToken')}
|
||||
name="apiToken"
|
||||
rules={{ validate: rhfZodValidate(NodeFormSchema.shape.apiToken) }}
|
||||
tooltip={t('pages.nodes.apiTokenHint')}
|
||||
>
|
||||
<NodeTokenInput placeholder={t('pages.nodes.apiTokenPlaceholder')} />
|
||||
</FormField>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
label={t('pages.nodes.outboundTag')}
|
||||
|
||||
@@ -1,138 +1,15 @@
|
||||
.toolbar {
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.name-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.name-cell .name {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.name-cell .remark {
|
||||
font-size: 12px;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.address-header {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.ip-toggle-icon {
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.ip-toggle-icon:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.address-hidden {
|
||||
filter: blur(5px);
|
||||
transition: filter 0.2s ease;
|
||||
}
|
||||
|
||||
.address-visible {
|
||||
filter: none;
|
||||
}
|
||||
|
||||
.node-cards {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.node-card {
|
||||
border: 1px solid var(--ant-color-border-secondary);
|
||||
border-radius: 10px;
|
||||
padding: 12px;
|
||||
background: var(--ant-color-fill-quaternary);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.card-expand {
|
||||
font-size: 12px;
|
||||
opacity: 0.6;
|
||||
transition: transform 150ms ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.card-expand.is-expanded {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.node-name {
|
||||
font-weight: 600;
|
||||
flex: 1;
|
||||
.nodes-overview {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.card-actions {
|
||||
/* card-toolbar and card-empty are global classes owned by lazily-loaded page
|
||||
stylesheets: re-declared so a direct /nodes load is styled like the others. */
|
||||
.nodes-card .card-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.row-action-trigger {
|
||||
font-size: 20px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.card-stats {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.stat-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
opacity: 0.6;
|
||||
min-width: 96px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.card-stats .ant-tag {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.card-history {
|
||||
margin-top: 4px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--ant-color-border-secondary);
|
||||
}
|
||||
|
||||
.card-empty {
|
||||
text-align: center;
|
||||
color: var(--ant-color-text-secondary);
|
||||
@@ -142,19 +19,222 @@
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.nodes-card .nodes-search {
|
||||
width: min(220px, 100%);
|
||||
}
|
||||
.nodes-card .nodes-status-filter {
|
||||
width: 150px;
|
||||
}
|
||||
.node-registered {
|
||||
margin-inline-start: auto;
|
||||
color: var(--ant-color-text-secondary);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.nodes-table-scroll {
|
||||
container-type: inline-size;
|
||||
}
|
||||
/* Not the Table `scroll` prop: its hidden measure row repeats the header's
|
||||
select-all button, a focusable control inside aria-hidden content. */
|
||||
.nodes-table .ant-table-content {
|
||||
overflow-x: auto;
|
||||
}
|
||||
.nodes-table .ant-table-content > table {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
}
|
||||
.nodes-table .ant-table-tbody > tr > th.node-name-cell {
|
||||
background: transparent;
|
||||
font-weight: inherit;
|
||||
}
|
||||
.nodes-table .ant-table-tbody > tr.node-row-fleet > .ant-table-cell {
|
||||
background: var(--ant-color-fill-quaternary);
|
||||
}
|
||||
.nodes-table .node-enabled {
|
||||
text-align: center;
|
||||
}
|
||||
.node-actions-heading,
|
||||
.node-readonly-action,
|
||||
.node-status-button {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.node-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
.node-actions > .ant-checkbox-wrapper {
|
||||
margin-inline: 4px;
|
||||
}
|
||||
.node-readonly-action .ant-tag,
|
||||
.node-system-tag,
|
||||
.node-client-counts .ant-tag {
|
||||
margin: 0;
|
||||
}
|
||||
.node-sigma {
|
||||
margin-inline-end: 4px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.node-name,
|
||||
.node-cell-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
.node-name {
|
||||
max-width: 160px;
|
||||
}
|
||||
.node-name > span,
|
||||
.node-name > small {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.node-name > span {
|
||||
font-weight: 500;
|
||||
}
|
||||
.nodes-table small,
|
||||
.node-memory-detail,
|
||||
.node-connection-load {
|
||||
color: var(--ant-color-text-secondary);
|
||||
font-size: var(--ant-font-size-sm, 12px);
|
||||
}
|
||||
.nodes-table .node-open-link {
|
||||
height: auto;
|
||||
padding: 0;
|
||||
}
|
||||
.node-status-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.node-status-button .online-dot,
|
||||
.node-status-button .xray-error-dot {
|
||||
margin-inline-end: 0;
|
||||
}
|
||||
.node-status-info {
|
||||
color: var(--ant-color-text-tertiary);
|
||||
}
|
||||
.node-status-tooltip h3 {
|
||||
margin: 0 0 4px;
|
||||
color: inherit;
|
||||
font-size: inherit;
|
||||
font-weight: 600;
|
||||
}
|
||||
.node-status-tooltip dl {
|
||||
margin: 0;
|
||||
}
|
||||
.node-status-tooltip dl > div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
}
|
||||
.node-status-tooltip dd {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
.node-hardware,
|
||||
.node-network-speed {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.node-network-speed {
|
||||
display: inline-grid;
|
||||
row-gap: 2px;
|
||||
text-align: start;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.node-network-direction,
|
||||
.node-runtime .node-panel-line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.node-client-counts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
max-width: 190px;
|
||||
}
|
||||
.nodes-footnote {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-block-start: 8px;
|
||||
color: var(--ant-color-text-secondary);
|
||||
font-size: var(--ant-font-size-sm, 12px);
|
||||
}
|
||||
|
||||
.node-network-direction {
|
||||
display: grid;
|
||||
grid-template-columns: 1em auto;
|
||||
column-gap: 4px;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
@media (max-width: 650px) {
|
||||
.node-registered {
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
}
|
||||
@container (width < 720px) {
|
||||
.nodes-table .ant-table-content > table {
|
||||
display: block;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
.nodes-table .ant-table-thead,
|
||||
.nodes-table .ant-table-tbody,
|
||||
.nodes-table .ant-table-thead > tr,
|
||||
.nodes-table .ant-table-tbody > tr,
|
||||
.nodes-table .ant-table-tbody > tr:not(.ant-table-row) > td {
|
||||
display: block;
|
||||
}
|
||||
.nodes-table colgroup {
|
||||
display: none;
|
||||
}
|
||||
.nodes-table .ant-table-thead > tr > th:not(:first-child) {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
.nodes-table .ant-table-thead > tr > th:first-child {
|
||||
border-radius: 8px;
|
||||
}
|
||||
.nodes-table .ant-table-tbody > tr.ant-table-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
margin-block-start: 8px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--ant-color-border-secondary);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.nodes-table .ant-table-tbody > tr.node-row-fleet {
|
||||
background: var(--ant-color-fill-quaternary);
|
||||
}
|
||||
.nodes-table .ant-table-tbody > tr.ant-table-row > .ant-table-cell {
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: start;
|
||||
}
|
||||
.nodes-table .ant-table-row > .node-name-cell,
|
||||
.nodes-table .ant-table-row > td:first-child {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
.nodes-table .ant-table-row > .node-name-cell {
|
||||
grid-row: 1;
|
||||
}
|
||||
.node-name {
|
||||
max-width: none;
|
||||
}
|
||||
.nodes-table td[data-label]::before {
|
||||
display: block;
|
||||
margin-block-end: 4px;
|
||||
color: var(--ant-color-text-secondary);
|
||||
font-size: var(--ant-font-size-sm, 12px);
|
||||
content: attr(data-label);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, within } from 'storybook/test';
|
||||
import { ConfigProvider } from 'antd';
|
||||
import { useState } from 'react';
|
||||
import type { NodeRecord } from '@/schemas/node';
|
||||
import NodeList from './NodeList';
|
||||
|
||||
const counts = {
|
||||
clientCount: 7100,
|
||||
inboundCount: 40,
|
||||
activeCount: 6050,
|
||||
disabledCount: 50,
|
||||
depletedCount: 1000,
|
||||
onlineCount: 210,
|
||||
};
|
||||
const noop = () => {};
|
||||
|
||||
function Fixture({ rtl }: { rtl?: boolean }) {
|
||||
const [selectedIds, setSelectedIds] = useState<number[]>([]);
|
||||
const [now] = useState(Date.now);
|
||||
const nodes: NodeRecord[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Finland edge',
|
||||
status: 'online',
|
||||
enable: true,
|
||||
xrayVersion: '26.1.1',
|
||||
panelVersion: '3.12.0',
|
||||
latencyMs: 42,
|
||||
lastHeartbeat: Math.floor(now / 1000) - 2,
|
||||
scheme: 'https',
|
||||
address: '2001:db8::3',
|
||||
port: 2053,
|
||||
basePath: '/edge/',
|
||||
telemetry: {
|
||||
sampledAt: now,
|
||||
cpuPct: 0,
|
||||
logicalCores: 8,
|
||||
memUsedBytes: 4 * 2 ** 30,
|
||||
memTotalBytes: 16 * 2 ** 30,
|
||||
netUp: 1024,
|
||||
netDown: 2048,
|
||||
tcpCount: 0,
|
||||
udpCount: 21,
|
||||
load1: 0.25,
|
||||
load5: 0.15,
|
||||
load15: 0.1,
|
||||
uptimeSecs: 5000,
|
||||
},
|
||||
clientCount: 3077,
|
||||
onlineCount: 31,
|
||||
onlineTotalCount: 53,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'Frankfurt',
|
||||
status: 'online',
|
||||
enable: true,
|
||||
panelVersion: '3.13.0',
|
||||
scheme: 'https',
|
||||
address: 'frankfurt-with-a-very-long-hostname.example.test',
|
||||
port: 443,
|
||||
telemetry: { sampledAt: now, cpuPct: 40, logicalCores: 4, tcpCount: 4, load1: 0.75 },
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'This-is-an-intentionally-long-node-name-without-spaces',
|
||||
status: 'offline',
|
||||
enable: true,
|
||||
lastError: 'Remote panel did not respond',
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
name: 'Standby',
|
||||
status: 'online',
|
||||
enable: false,
|
||||
telemetry: { sampledAt: now, cpuPct: 100, tcpCount: 9 },
|
||||
},
|
||||
];
|
||||
return (
|
||||
<ConfigProvider direction={rtl ? 'rtl' : 'ltr'}>
|
||||
<div dir={rtl ? 'rtl' : 'ltr'} className="nodes-story">
|
||||
<NodeList
|
||||
nodes={nodes}
|
||||
selectedIds={selectedIds}
|
||||
onSelectionChange={setSelectedIds}
|
||||
master={{
|
||||
counts: {
|
||||
inboundCount: 8,
|
||||
clientCount: 2200,
|
||||
activeCount: 1860,
|
||||
disabledCount: 50,
|
||||
depletedCount: 290,
|
||||
onlineCount: 80,
|
||||
},
|
||||
panelVersion: '3.13.0',
|
||||
xrayVersion: '26.1.1',
|
||||
xrayState: 'running',
|
||||
telemetry: {
|
||||
sampledAt: now,
|
||||
cpuPct: 20,
|
||||
logicalCores: 4,
|
||||
memUsedBytes: 2 * 2 ** 30,
|
||||
memTotalBytes: 8 * 2 ** 30,
|
||||
netUp: 1024,
|
||||
netDown: 2048,
|
||||
tcpCount: 10,
|
||||
udpCount: 5,
|
||||
load1: 0.5,
|
||||
load5: 0.3,
|
||||
load15: 0.15,
|
||||
uptimeSecs: 91000,
|
||||
},
|
||||
}}
|
||||
fleet={counts}
|
||||
latestVersion="3.13.0"
|
||||
onAdd={noop}
|
||||
onMtls={noop}
|
||||
onEdit={noop}
|
||||
onDelete={noop}
|
||||
onProbe={noop}
|
||||
onToggleEnable={noop}
|
||||
onUpdateNode={noop}
|
||||
onUpdateSelected={noop}
|
||||
onRestart={noop}
|
||||
/>
|
||||
</div>
|
||||
</ConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = { title: 'Nodes/Fleet Monitoring', component: Fixture } satisfies Meta<typeof Fixture>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Desktop: Story = {
|
||||
play: async ({ canvasElement, userEvent }) => {
|
||||
const canvas = within(canvasElement);
|
||||
const row = canvas.getByRole('row', { name: /All nodes/ });
|
||||
await expect(within(row).getByText('3/5 reporting')).toBeVisible();
|
||||
await expect(within(row).getByText('20.0%')).toBeVisible();
|
||||
await expect(within(row).queryByRole('checkbox')).toBeNull();
|
||||
await expect(
|
||||
within(canvas.getByRole('row', { name: /Master/ })).queryByRole('switch'),
|
||||
).toBeNull();
|
||||
const edge = canvas.getByRole('row', { name: /Finland edge/ });
|
||||
const link = within(edge).getByRole('link', { name: 'Open' });
|
||||
await expect(link).toHaveAttribute('href', 'https://[2001:db8::3]:2053/edge/');
|
||||
await expect(link).toHaveAttribute('rel', 'noopener noreferrer');
|
||||
const status = within(edge).getByRole('button', { name: 'Online' });
|
||||
await userEvent.click(status);
|
||||
await expect(await within(canvasElement.ownerDocument.body).findByText('42 ms')).toBeVisible();
|
||||
const input = canvas.getByRole('searchbox', { name: 'Search' });
|
||||
await userEvent.click(input);
|
||||
for (const viewport of [1280, 1440, 1664, 1920]) {
|
||||
const container = canvas.getByRole('region', { name: 'Nodes' });
|
||||
container.style.width = `${viewport - 260}px`;
|
||||
await expect(container.scrollWidth).toBeLessThanOrEqual(container.clientWidth + 1);
|
||||
const table = container.querySelector('.ant-table-content') as HTMLElement;
|
||||
if (viewport >= 1664) {
|
||||
await expect(table.scrollWidth).toBeLessThanOrEqual(table.clientWidth + 1);
|
||||
}
|
||||
container.style.width = '';
|
||||
}
|
||||
await userEvent.type(input, 'Frankfurt');
|
||||
await expect(canvas.queryByText('Finland edge')).toBeNull();
|
||||
await expect(canvas.getByText('3/5 reporting')).toBeVisible();
|
||||
await userEvent.clear(input);
|
||||
},
|
||||
};
|
||||
|
||||
export const RTL: Story = { args: { rtl: true }, globals: { theme: 'light' } };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,8 +15,6 @@ export default function NodeNetworkSpeed({
|
||||
node: NodeRecord;
|
||||
receivedAt?: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
const expiration =
|
||||
receivedAt && node.heartbeatAgeMillis != null
|
||||
? receivedAt + HEARTBEAT_FRESHNESS_MS - node.heartbeatAgeMillis
|
||||
@@ -40,15 +38,36 @@ export default function NodeNetworkSpeed({
|
||||
};
|
||||
const fresh = useSyncExternalStore(subscribe, isFresh);
|
||||
const available = node.enable && node.status === 'online' && !node.transitive && fresh;
|
||||
return (
|
||||
<NetworkSpeedValues
|
||||
up={available && !node.unavailableMetrics?.includes('netUp') ? node.netUp : undefined}
|
||||
down={available && !node.unavailableMetrics?.includes('netDown') ? node.netDown : undefined}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function NetworkSpeedValues({
|
||||
up,
|
||||
down,
|
||||
uploadFirst,
|
||||
}: {
|
||||
up?: number | null;
|
||||
down?: number | null;
|
||||
uploadFirst?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { token } = theme.useToken();
|
||||
const directions = [
|
||||
{
|
||||
key: 'netDown' as const,
|
||||
rate: down,
|
||||
isUpload: false,
|
||||
label: t('pages.index.download'),
|
||||
Icon: ArrowDownOutlined,
|
||||
color: token.colorTextTertiary,
|
||||
},
|
||||
{
|
||||
key: 'netUp' as const,
|
||||
rate: up,
|
||||
isUpload: true,
|
||||
label: t('pages.index.upload'),
|
||||
Icon: ArrowUpOutlined,
|
||||
color: token.colorPrimary,
|
||||
@@ -56,30 +75,27 @@ export default function NodeNetworkSpeed({
|
||||
];
|
||||
return (
|
||||
<span className="node-network-speed">
|
||||
{directions.map(({ key, label, Icon, color }) => {
|
||||
const rate = node[key];
|
||||
const value =
|
||||
available &&
|
||||
!node.unavailableMetrics?.includes(key) &&
|
||||
typeof rate === 'number' &&
|
||||
Number.isFinite(rate) &&
|
||||
rate >= 0
|
||||
? SizeFormatter.speedFormat(rate)
|
||||
: '—';
|
||||
return (
|
||||
<Tooltip key={key} title={label}>
|
||||
<span
|
||||
role="img"
|
||||
aria-label={label + ' ' + value}
|
||||
className="node-network-direction"
|
||||
dir="ltr"
|
||||
>
|
||||
<Icon aria-hidden style={{ color }} />
|
||||
<span aria-hidden>{value}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
{(uploadFirst ? directions.reverse() : directions).map(
|
||||
({ rate, label, Icon, color, isUpload }) => {
|
||||
const value =
|
||||
typeof rate === 'number' && Number.isFinite(rate) && rate >= 0
|
||||
? SizeFormatter.speedFormat(rate)
|
||||
: '—';
|
||||
return (
|
||||
<Tooltip key={label} title={label}>
|
||||
<span
|
||||
role="img"
|
||||
aria-label={label + ' ' + value}
|
||||
className={'node-network-direction' + (isUpload ? ' node-network-up' : '')}
|
||||
dir="ltr"
|
||||
>
|
||||
<Icon aria-hidden style={{ color }} />
|
||||
<span aria-hidden>{value}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
},
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,30 +4,18 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
Card,
|
||||
Checkbox,
|
||||
Col,
|
||||
ConfigProvider,
|
||||
Input,
|
||||
Layout,
|
||||
Modal,
|
||||
Result,
|
||||
Row,
|
||||
Spin,
|
||||
Statistic,
|
||||
Typography,
|
||||
message,
|
||||
} from 'antd';
|
||||
import {
|
||||
CheckCircleOutlined,
|
||||
CloseCircleOutlined,
|
||||
CloudServerOutlined,
|
||||
ThunderboltOutlined,
|
||||
} from '@ant-design/icons';
|
||||
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { useMediaQuery } from '@/hooks/useMediaQuery';
|
||||
import { useNodesQuery } from '@/api/queries/useNodesQuery';
|
||||
import { useNodeOverviewQuery } from '@/api/queries/useNodesQuery';
|
||||
import type { NodeRecord } from '@/api/queries/useNodesQuery';
|
||||
import { useNodeMutations } from '@/api/queries/useNodeMutations';
|
||||
import AppSidebar from '@/layouts/AppSidebar';
|
||||
@@ -70,14 +58,23 @@ function UpdateChannelChoice({ onChange }: { onChange: (dev: boolean) => void })
|
||||
export default function NodesPage() {
|
||||
const { t } = useTranslation();
|
||||
const { isDark, isUltra, antdThemeConfig } = useTheme();
|
||||
const { isMobile } = useMediaQuery();
|
||||
const [modal, modalContextHolder] = Modal.useModal();
|
||||
const [messageApi, messageContextHolder] = message.useMessage();
|
||||
useEffect(() => {
|
||||
setMessageInstance(messageApi);
|
||||
}, [messageApi]);
|
||||
|
||||
const { nodes, nodesUpdatedAt, loading, fetched, fetchError, refetch, totals } = useNodesQuery();
|
||||
const {
|
||||
nodes,
|
||||
master,
|
||||
fleet,
|
||||
nodesUpdatedAt,
|
||||
loading,
|
||||
fetched,
|
||||
fetchError,
|
||||
refreshError,
|
||||
refetch,
|
||||
} = useNodeOverviewQuery();
|
||||
const {
|
||||
create,
|
||||
update,
|
||||
@@ -360,74 +357,29 @@ export default function NodesPage() {
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
|
||||
<Col span={24}>
|
||||
<Card size="small" hoverable className="summary-card">
|
||||
<Row gutter={[16, isMobile ? 16 : 12]}>
|
||||
<Col xs={12} sm={12} md={6}>
|
||||
<Statistic
|
||||
title={t('pages.nodes.totalNodes')}
|
||||
value={String(totals.total)}
|
||||
prefix={<CloudServerOutlined aria-hidden />}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={12} sm={12} md={6}>
|
||||
<Statistic
|
||||
title={t('pages.nodes.onlineNodes')}
|
||||
value={String(totals.online)}
|
||||
prefix={
|
||||
<CheckCircleOutlined
|
||||
aria-hidden
|
||||
style={{ color: 'var(--ant-color-success)' }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={12} sm={12} md={6}>
|
||||
<Statistic
|
||||
title={t('pages.nodes.offlineNodes')}
|
||||
value={String(totals.offline)}
|
||||
prefix={
|
||||
<CloseCircleOutlined
|
||||
aria-hidden
|
||||
style={{ color: 'var(--ant-color-error)' }}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</Col>
|
||||
<Col xs={12} sm={12} md={6}>
|
||||
<Statistic
|
||||
title={t('pages.nodes.avgLatency')}
|
||||
value={totals.avgLatency > 0 ? `${totals.avgLatency} ms` : '-'}
|
||||
prefix={<ThunderboltOutlined aria-hidden />}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
</Card>
|
||||
</Col>
|
||||
|
||||
<Col span={24}>
|
||||
<NodeList
|
||||
nodes={nodes}
|
||||
nodesUpdatedAt={nodesUpdatedAt}
|
||||
loading={loading}
|
||||
isMobile={isMobile}
|
||||
latestVersion={latestVersion}
|
||||
selectedIds={selectedIds}
|
||||
onSelectionChange={setSelectedIds}
|
||||
onAdd={onAdd}
|
||||
onMtls={() => setMtlsOpen(true)}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onProbe={onProbe}
|
||||
onToggleEnable={onToggleEnable}
|
||||
onUpdateNode={onUpdateNode}
|
||||
onUpdateSelected={onUpdateSelected}
|
||||
onRestart={onRestart}
|
||||
restartingIds={restartingIds}
|
||||
/>
|
||||
</Col>
|
||||
</Row>
|
||||
<>
|
||||
{refreshError && <Alert type="warning" showIcon title={refreshError} />}
|
||||
<NodeList
|
||||
nodes={nodes}
|
||||
master={master}
|
||||
fleet={fleet}
|
||||
nodesUpdatedAt={nodesUpdatedAt}
|
||||
loading={loading}
|
||||
latestVersion={latestVersion}
|
||||
selectedIds={selectedIds}
|
||||
onSelectionChange={setSelectedIds}
|
||||
onAdd={onAdd}
|
||||
onMtls={() => setMtlsOpen(true)}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onProbe={onProbe}
|
||||
onToggleEnable={onToggleEnable}
|
||||
onUpdateNode={onUpdateNode}
|
||||
onUpdateSelected={onUpdateSelected}
|
||||
onRestart={onRestart}
|
||||
restartingIds={restartingIds}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Spin>
|
||||
</Layout.Content>
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { useCallback, useMemo, useState, useSyncExternalStore } from 'react';
|
||||
import type { NodeTelemetry } from '@/generated/types';
|
||||
|
||||
const FRESHNESS_MS = 30_000;
|
||||
|
||||
function expires(sample: NodeTelemetry, receivedAt?: number) {
|
||||
return receivedAt && sample.sampleAgeMillis != null
|
||||
? receivedAt + FRESHNESS_MS - sample.sampleAgeMillis
|
||||
: sample.sampledAt + FRESHNESS_MS;
|
||||
}
|
||||
|
||||
export function freshTelemetry(
|
||||
sample: NodeTelemetry | null | undefined,
|
||||
now: number,
|
||||
receivedAt?: number,
|
||||
) {
|
||||
if (!sample) return undefined;
|
||||
const remaining = expires(sample, receivedAt) - now;
|
||||
return remaining > 0 && remaining <= FRESHNESS_MS ? sample : undefined;
|
||||
}
|
||||
|
||||
export function useTelemetryClock(
|
||||
samples: readonly (NodeTelemetry | null | undefined)[],
|
||||
receivedAt?: number,
|
||||
) {
|
||||
const [mountedAt] = useState(Date.now);
|
||||
const deadlines = useMemo(
|
||||
() =>
|
||||
samples
|
||||
.flatMap((sample) => (sample ? [expires(sample, receivedAt)] : []))
|
||||
.sort((a, b) => a - b),
|
||||
[samples, receivedAt],
|
||||
);
|
||||
const subscribe = useCallback(
|
||||
(refresh: () => void) => {
|
||||
let timer: number | undefined;
|
||||
const schedule = () => {
|
||||
const now = Date.now();
|
||||
const deadline = deadlines.find((time) => time > now && time <= now + FRESHNESS_MS);
|
||||
if (deadline !== undefined) {
|
||||
timer = window.setTimeout(() => {
|
||||
refresh();
|
||||
schedule();
|
||||
}, deadline - now);
|
||||
}
|
||||
};
|
||||
schedule();
|
||||
return () => window.clearTimeout(timer);
|
||||
},
|
||||
[deadlines],
|
||||
);
|
||||
const snapshot = () => {
|
||||
const now = Date.now();
|
||||
const latestExpiry = deadlines.reduce((last, time) => (time <= now ? time : last), 0);
|
||||
return Math.max(mountedAt, receivedAt ?? 0, latestExpiry);
|
||||
};
|
||||
return useSyncExternalStore(subscribe, snapshot, snapshot);
|
||||
}
|
||||
|
||||
export function aggregateTelemetry(samples: NodeTelemetry[]) {
|
||||
const cpu = samples.filter((host) => host.cpuPct != null);
|
||||
const memory = samples.filter(
|
||||
(host) =>
|
||||
host.memTotalBytes != null &&
|
||||
host.memTotalBytes > 0 &&
|
||||
host.memUsedBytes != null &&
|
||||
host.memUsedBytes <= host.memTotalBytes,
|
||||
);
|
||||
function sum(key: keyof NodeTelemetry, hosts = samples) {
|
||||
let total: number | undefined;
|
||||
for (const sample of hosts) {
|
||||
const value = sample[key];
|
||||
if (typeof value === 'number') total = (total ?? 0) + value;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
const telemetry: NodeTelemetry = {
|
||||
sampledAt: 0,
|
||||
cpuPct: cpu.length ? (sum('cpuPct', cpu) ?? 0) / cpu.length : undefined,
|
||||
logicalCores: cpu.every((host) => host.logicalCores != null)
|
||||
? sum('logicalCores', cpu)
|
||||
: undefined,
|
||||
memUsedBytes: sum('memUsedBytes', memory),
|
||||
memTotalBytes: sum('memTotalBytes', memory),
|
||||
memAvailableBytes: memory.every((host) => host.memAvailableBytes != null)
|
||||
? sum('memAvailableBytes', memory)
|
||||
: undefined,
|
||||
netUp: sum('netUp'),
|
||||
netDown: sum('netDown'),
|
||||
tcpCount: sum('tcpCount'),
|
||||
udpCount: sum('udpCount'),
|
||||
load1: sum('load1'),
|
||||
load5: sum('load5'),
|
||||
load15: sum('load15'),
|
||||
};
|
||||
return { telemetry, cpuHosts: cpu.length, memoryHosts: memory.length };
|
||||
}
|
||||
|
||||
export function reportingSample(sample: NodeTelemetry | null | undefined): sample is NodeTelemetry {
|
||||
if (!sample) return false;
|
||||
const { sampledAt: _time, sampleAgeMillis: _age, resourceScope: _scope, ...metrics } = sample;
|
||||
return Object.values(metrics).some((metric) => typeof metric === 'number');
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, fn, waitFor, within } from 'storybook/test';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { useState } from 'react';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { ThemeProvider } from '@/hooks/useTheme';
|
||||
import { AntdRootConfig } from '@/i18n/AntdRootConfig';
|
||||
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import RuleFormModal from './RuleFormModal';
|
||||
|
||||
function QueryFixture({ children }: { children: ReactNode }) {
|
||||
const [client] = useState(
|
||||
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
|
||||
);
|
||||
return (
|
||||
<QueryClientProvider client={client}>
|
||||
<AntdRootConfig>
|
||||
<ThemeProvider>{children}</ThemeProvider>
|
||||
</AntdRootConfig>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function RoutingRuleFixture(props: ComponentProps<typeof RuleFormModal>) {
|
||||
const [open, setOpen] = useState(props.open);
|
||||
return (
|
||||
<RuleFormModal
|
||||
{...props}
|
||||
open={open}
|
||||
onClose={() => {
|
||||
props.onClose();
|
||||
setOpen(false);
|
||||
}}
|
||||
onConfirm={(rule) => {
|
||||
props.onConfirm(rule);
|
||||
setOpen(false);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = {
|
||||
title: 'Xray/Routing Rule',
|
||||
component: RuleFormModal,
|
||||
render: (args) => <RoutingRuleFixture {...args} />,
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<QueryFixture>
|
||||
<Story />
|
||||
</QueryFixture>
|
||||
),
|
||||
],
|
||||
args: {
|
||||
open: true,
|
||||
rule: { user: ['existing@test'], outboundTag: 'direct' },
|
||||
inboundTags: [],
|
||||
outboundTags: ['direct'],
|
||||
balancerTags: [],
|
||||
onClose: fn(),
|
||||
onConfirm: fn(),
|
||||
},
|
||||
} satisfies Meta<typeof RuleFormModal>;
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
function largeCatalog(size: number): Story {
|
||||
const requests: Array<{ path: string; search: string; count: number }> = [];
|
||||
const target = `client-${size}@test`;
|
||||
const legacyList = '/panel/api/clients/list';
|
||||
const suggestionsPath = '/panel/api/clients/userSuggestions';
|
||||
|
||||
return {
|
||||
beforeEach: () => {
|
||||
requests.length = 0;
|
||||
const get = HttpUtil.get;
|
||||
const fixture = Array.from({ length: size }, (_, index) => `client-${index + 1}@test`);
|
||||
HttpUtil.get = async <T,>(path: string, params?: unknown) => {
|
||||
if (path === legacyList) {
|
||||
requests.push({ path, search: '', count: size });
|
||||
return new Msg<T>(true, '', fixture.map((email) => ({ email })) as T);
|
||||
}
|
||||
if (path === suggestionsPath) {
|
||||
const { search } = params as { search: string };
|
||||
const emails = fixture.filter((email) => email.includes(search)).slice(0, 50);
|
||||
requests.push({ path, search, count: emails.length });
|
||||
return new Msg<T>(true, '', { emails } as T);
|
||||
}
|
||||
return new Msg<T>(true, '', [] as T);
|
||||
};
|
||||
return () => {
|
||||
HttpUtil.get = get;
|
||||
};
|
||||
},
|
||||
play: async ({ args, canvasElement, userEvent }) => {
|
||||
const screen = within(canvasElement.ownerDocument.body);
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
const picker = within(dialog).getByRole('combobox', { name: 'User' });
|
||||
await expect(requests).toEqual([]);
|
||||
await userEvent.click(picker);
|
||||
await waitFor(() =>
|
||||
expect(requests).toEqual([{ path: suggestionsPath, search: '', count: 50 }]),
|
||||
);
|
||||
|
||||
const search = target.replace('client-', '');
|
||||
await userEvent.type(picker, search);
|
||||
const option = await screen.findByText(target, {
|
||||
selector: '.ant-select-item-option-content',
|
||||
});
|
||||
await userEvent.click(option);
|
||||
await userEvent.type(picker, 'manual@test,existing@test,');
|
||||
await expect(screen.getByRole('button', { name: 'Remove existing@test' })).toBeVisible();
|
||||
await expect(screen.getByRole('button', { name: `Remove ${target}` })).toBeVisible();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
|
||||
await expect(args.onConfirm).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
user: ['existing@test', target, 'manual@test'],
|
||||
outboundTag: 'direct',
|
||||
}),
|
||||
);
|
||||
await expect(requests.filter(({ search }) => search)).toEqual([
|
||||
{ path: suggestionsPath, search, count: 1 },
|
||||
]);
|
||||
await expect(
|
||||
requests.every(({ path, count }) => path === suggestionsPath && count <= 50),
|
||||
).toBe(true);
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const Thousand = largeCatalog(1_000);
|
||||
export const TenThousand = largeCatalog(10_000);
|
||||
export const FiftyThousand = largeCatalog(50_000);
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Form, Input, Modal, Select, Space, Switch } from 'antd';
|
||||
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
|
||||
@@ -71,6 +71,73 @@ function csv(value: string): string[] {
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function RoutingUserField({ active }: { active: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [search, setSearch] = useState('');
|
||||
const { data, isFetching, isError } = useClientOptions(
|
||||
active && pickerOpen ? search.trim() : null,
|
||||
);
|
||||
const user = useWatch<RuleFormValues, 'user'>({ name: 'user' }) ?? '';
|
||||
const selectedUsers = useMemo(() => csv(user), [user]);
|
||||
const options = useMemo(
|
||||
() =>
|
||||
[...new Set([...(data ?? []), ...selectedUsers])].map((email) => ({
|
||||
value: email,
|
||||
label: email,
|
||||
})),
|
||||
[data, selectedUsers],
|
||||
);
|
||||
const status = isFetching
|
||||
? t('loading')
|
||||
: isError
|
||||
? t('pages.xray.ruleForm.userLoadError')
|
||||
: !data?.length
|
||||
? t('pages.xray.ruleForm.userEmpty')
|
||||
: undefined;
|
||||
const showStatusInMenu = Boolean(search || options.length);
|
||||
|
||||
return (
|
||||
<FormField
|
||||
name="user"
|
||||
label={t('pages.xray.ruleForm.user')}
|
||||
tooltip={t('pages.xray.rules.useComma')}
|
||||
transform={{
|
||||
input: (value) => csv(typeof value === 'string' ? value : ''),
|
||||
output: (value) => (Array.isArray(value) ? value.join(',') : ''),
|
||||
}}
|
||||
onAfterChange={() => setSearch('')}
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
tagRender={selectTagRender}
|
||||
tokenSeparators={[',']}
|
||||
allowClear
|
||||
loading={isFetching}
|
||||
placeholder={t('pages.xray.ruleForm.userPlaceholder')}
|
||||
open={active && pickerOpen}
|
||||
onOpenChange={(next) => {
|
||||
setPickerOpen(next);
|
||||
if (!next) setSearch('');
|
||||
}}
|
||||
showSearch={{ searchValue: search, onSearch: setSearch, filterOption: false }}
|
||||
notFoundContent={<span role="status">{status}</span>}
|
||||
popupRender={(menu) => (
|
||||
<>
|
||||
{menu}
|
||||
{showStatusInMenu && status && (
|
||||
<div role="status" className="px-8 py-4">
|
||||
{status}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
options={options}
|
||||
/>
|
||||
</FormField>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RuleFormModal({
|
||||
open,
|
||||
rule,
|
||||
@@ -86,21 +153,6 @@ export default function RuleFormModal({
|
||||
|
||||
const { data: inboundOptions } = useInboundOptions();
|
||||
const remarkByTag = useMemo(() => buildRemarkByTag(inboundOptions || []), [inboundOptions]);
|
||||
const {
|
||||
data: clientEmails = [],
|
||||
isFetching: clientsLoading,
|
||||
isError: clientsError,
|
||||
} = useClientOptions(open);
|
||||
const user = useWatch({ control: methods.control, name: 'user' }) ?? '';
|
||||
const selectedUsers = useMemo(() => csv(user), [user]);
|
||||
const userOptions = useMemo(
|
||||
() =>
|
||||
[...new Set([...clientEmails, ...selectedUsers])].map((email) => ({
|
||||
value: email,
|
||||
label: email,
|
||||
})),
|
||||
[clientEmails, selectedUsers],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -286,33 +338,7 @@ export default function RuleFormModal({
|
||||
<GeoTokenInput kind="domain" placeholder="google.com, geosite:cn" />
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
name="user"
|
||||
label={t('pages.xray.ruleForm.user')}
|
||||
tooltip={t('pages.xray.rules.useComma')}
|
||||
transform={{
|
||||
input: (value) => csv(typeof value === 'string' ? value : ''),
|
||||
output: (value) => (Array.isArray(value) ? value.join(',') : ''),
|
||||
}}
|
||||
>
|
||||
<Select
|
||||
mode="tags"
|
||||
tagRender={selectTagRender}
|
||||
tokenSeparators={[',']}
|
||||
allowClear
|
||||
loading={clientsLoading}
|
||||
placeholder={t('pages.xray.ruleForm.userPlaceholder')}
|
||||
showSearch={{ optionFilterProp: 'label' }}
|
||||
notFoundContent={
|
||||
clientsLoading
|
||||
? t('loading')
|
||||
: clientsError
|
||||
? t('pages.xray.ruleForm.userLoadError')
|
||||
: t('pages.xray.ruleForm.userEmpty')
|
||||
}
|
||||
options={userOptions}
|
||||
/>
|
||||
</FormField>
|
||||
<RoutingUserField key={String(open)} active={open} />
|
||||
|
||||
<FormField
|
||||
name="port"
|
||||
|
||||
@@ -220,6 +220,7 @@ export const ClientHydrateSchema = z.object({
|
||||
});
|
||||
|
||||
export const BulkAdjustResultSchema = z.object({
|
||||
skippedCount: z.number().optional(),
|
||||
adjusted: z.number(),
|
||||
skipped: z.array(z.object({ email: z.string(), reason: z.string() })).optional(),
|
||||
externalLinks: z
|
||||
@@ -228,6 +229,7 @@ export const BulkAdjustResultSchema = z.object({
|
||||
});
|
||||
|
||||
export const BulkDeleteResultSchema = z.object({
|
||||
skippedCount: z.number().optional(),
|
||||
deleted: z.number(),
|
||||
skipped: z.array(z.object({ email: z.string(), reason: z.string() })).optional(),
|
||||
});
|
||||
@@ -284,7 +286,7 @@ export const OnlineByNodeSchema = z
|
||||
.transform((v) => v ?? {});
|
||||
|
||||
export const ActiveInboundsByNodeSchema = z
|
||||
.record(z.string(), nullableStringArray)
|
||||
.record(z.string(), z.array(z.string()).nullable())
|
||||
.nullable()
|
||||
.transform((v) => v ?? {});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod';
|
||||
import { NodeFleetCountsSchema, NodeMasterViewSchema, NodeTelemetrySchema } from '@/generated/zod';
|
||||
|
||||
export const NodeRecordSchema = z
|
||||
.object({
|
||||
@@ -23,6 +24,7 @@ export const NodeRecordSchema = z
|
||||
panelVersion: z.string().optional(),
|
||||
uptimeSecs: z.number().optional(),
|
||||
unavailableMetrics: z.array(z.string()).optional(),
|
||||
telemetry: NodeTelemetrySchema.optional(),
|
||||
inboundCount: z.number().optional(),
|
||||
clientCount: z.number().optional(),
|
||||
onlineCount: z.number().optional(),
|
||||
@@ -54,6 +56,11 @@ export const NodeRecordSchema = z
|
||||
.loose();
|
||||
|
||||
export const NodeListSchema = z.array(NodeRecordSchema);
|
||||
export const NodeOverviewSchema = z.object({
|
||||
nodes: NodeListSchema,
|
||||
master: NodeMasterViewSchema,
|
||||
fleet: NodeFleetCountsSchema,
|
||||
});
|
||||
|
||||
export const ProbeResultSchema = z
|
||||
.object({
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
|
||||
import ClientBulkAddModal from '@/pages/clients/ClientBulkAddModal';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
const { bulkCreate } = vi.hoisted(() => ({ bulkCreate: vi.fn() }));
|
||||
vi.mock('@/hooks/useClients', () => ({ useClients: () => ({ bulkCreate }) }));
|
||||
|
||||
function mockHttp() {
|
||||
vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) => {
|
||||
if (typeof url === 'string' && url.includes('fail2banStatus'))
|
||||
return new Msg(true, '', { enabled: true, installed: true, usable: true, windows: false });
|
||||
return new Msg(true, '', {});
|
||||
});
|
||||
vi.spyOn(HttpUtil, 'post').mockImplementation(async (url) => {
|
||||
if (url !== '/panel/api/clients/renewalPreview')
|
||||
return new Msg(true, '', { datepicker: 'gregorian' });
|
||||
return new Msg(true, '', {
|
||||
timeZone: 'Asia/Taipei',
|
||||
renewAt: '',
|
||||
validThrough: '',
|
||||
nextExpiry: '',
|
||||
suggestedExpiryTime: 1893427200000,
|
||||
suggestedExpiry: '2030-01-01T00:00:00+08:00',
|
||||
renewals: 0,
|
||||
canRenew: false,
|
||||
delayedStart: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderModal(onOpenChange = vi.fn()) {
|
||||
renderWithProviders(
|
||||
<ClientBulkAddModal
|
||||
open
|
||||
inbounds={[{ id: 1, protocol: 'vless', tag: 'calendar' }]}
|
||||
onOpenChange={onOpenChange}
|
||||
/>,
|
||||
);
|
||||
return onOpenChange;
|
||||
}
|
||||
|
||||
function fillBatch(quantity: string, subId: string) {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select all' }));
|
||||
fireEvent.change(screen.getByLabelText('Number of Clients'), { target: { value: quantity } });
|
||||
fireEvent.change(screen.getByLabelText('Subscription ID'), { target: { value: subId } });
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const button = document.querySelector('.ant-modal-footer .ant-btn-primary');
|
||||
if (!button) throw new Error('Create button missing');
|
||||
await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false));
|
||||
fireEvent.click(button);
|
||||
}
|
||||
|
||||
function subIdsOf(call: unknown[]): string[] {
|
||||
const payloads = call[0] as { client: { subId: string } }[];
|
||||
return payloads.map((p) => p.client.subId);
|
||||
}
|
||||
|
||||
describe('ClientBulkAddModal subscription IDs', () => {
|
||||
beforeEach(() => {
|
||||
bulkCreate.mockClear();
|
||||
bulkCreate.mockResolvedValue(new Msg(true, '', { created: 3, skipped: [] }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('sends the typed prefix for server allocation without fetching all clients', async () => {
|
||||
mockHttp();
|
||||
renderModal();
|
||||
fillBatch('3', 'test123');
|
||||
await submit();
|
||||
await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1));
|
||||
expect(subIdsOf(bulkCreate.mock.calls[0])).toEqual(['', '', '']);
|
||||
expect(bulkCreate.mock.calls[0][0]).toEqual(
|
||||
Array.from({ length: 3 }, () => expect.objectContaining({ subIdPrefix: 'test123' })),
|
||||
);
|
||||
expect(
|
||||
vi.mocked(HttpUtil.get).mock.calls.some(([url]) => url === '/panel/api/clients/list'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps a typed ID exact for a single client', async () => {
|
||||
mockHttp();
|
||||
renderModal();
|
||||
fillBatch('1', 'test123');
|
||||
await submit();
|
||||
await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1));
|
||||
expect(subIdsOf(bulkCreate.mock.calls[0])).toEqual(['test123']);
|
||||
expect(bulkCreate.mock.calls[0][0][0].subIdPrefix).toBeUndefined();
|
||||
});
|
||||
|
||||
it('leaves the form open for retry when server allocation fails', async () => {
|
||||
mockHttp();
|
||||
bulkCreate.mockResolvedValueOnce(new Msg(false, 'Could not allocate subscription IDs', null));
|
||||
const onOpenChange = renderModal();
|
||||
fillBatch('3', 'test123');
|
||||
await submit();
|
||||
await screen.findByText('Could not allocate subscription IDs');
|
||||
expect(onOpenChange).not.toHaveBeenCalled();
|
||||
expect((screen.getByLabelText('Subscription ID') as HTMLInputElement).value).toBe('test123');
|
||||
await submit();
|
||||
await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));
|
||||
});
|
||||
|
||||
it('gives each client a different random ID when Subscription ID is empty', async () => {
|
||||
mockHttp();
|
||||
renderModal();
|
||||
fillBatch('3', '');
|
||||
await submit();
|
||||
await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1));
|
||||
const subIds = subIdsOf(bulkCreate.mock.calls[0]);
|
||||
expect(subIds).toHaveLength(3);
|
||||
expect(new Set(subIds).size).toBe(3);
|
||||
for (const subId of subIds) expect(subId).toMatch(/^[a-z0-9]{16}$/);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
import { Status } from '@/models/status';
|
||||
import { useOverviewHistory } from '@/pages/index/useOverviewHistory';
|
||||
@@ -12,8 +12,11 @@ vi.mock('@/utils', async (importOriginal) => {
|
||||
|
||||
beforeEach(() => {
|
||||
get.mockReset();
|
||||
vi.spyOn(Date, 'now').mockReturnValue(10_000);
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('keeps missing samples out of trends and resets a changed metric scope', async () => {
|
||||
get.mockImplementation(async (path: string) => ({
|
||||
success: true,
|
||||
@@ -37,6 +40,7 @@ it('keeps missing samples out of trends and resets a changed metric scope', asyn
|
||||
expect(result.current.series.cpu).toEqual([10, 20]);
|
||||
rerender({ status: new Status({ cpu: 50 }) });
|
||||
expect(result.current.series.cpu).toEqual([50]);
|
||||
await act(async () => undefined);
|
||||
});
|
||||
|
||||
it('ignores a legacy seed that resolves after the scope changes', async () => {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
|
||||
import DetachClientsModal from '@/pages/inbounds/clients/DetachClientsModal';
|
||||
import { DBInbound } from '@/models/dbinbound';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
@@ -27,10 +28,153 @@ function sourceInbound() {
|
||||
}
|
||||
|
||||
describe('DetachClientsModal', () => {
|
||||
it('lists the attached clients when first mounted already open', async () => {
|
||||
it('uses the bounded server page instead of rendering embedded settings clients', async () => {
|
||||
const get = vi.spyOn(HttpUtil, 'get').mockResolvedValue(
|
||||
new Msg(true, '', {
|
||||
items: [{ id: 12, email: 'server@test', comment: '', enable: true, inScope: false }],
|
||||
total: 50000,
|
||||
attached: 50000,
|
||||
}),
|
||||
);
|
||||
renderWithProviders(<DetachClientsModal open source={sourceInbound()} onClose={() => {}} />);
|
||||
|
||||
expect(await screen.findByText('alice@test')).toBeTruthy();
|
||||
expect(screen.getByText('bob@test')).toBeTruthy();
|
||||
expect(await screen.findByText('server@test')).toBeTruthy();
|
||||
expect(screen.queryByText('alice@test')).toBeNull();
|
||||
expect(get).toHaveBeenCalledWith(
|
||||
'/panel/api/clients/detachCandidates',
|
||||
expect.objectContaining({ inboundId: 7, page: 1 }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps page and frozen selections separate and sends only the scope and exclusions', async () => {
|
||||
const status = '/panel/api/clients/bulkDetach/job-1';
|
||||
const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url, params) => {
|
||||
if (url === status) {
|
||||
return new Msg(true, '', {
|
||||
running: false,
|
||||
processed: 49999,
|
||||
total: 49999,
|
||||
result: { detached: 49998, skipped: 1, errors: 0 },
|
||||
});
|
||||
}
|
||||
const { page, search, scopeToken } = params as {
|
||||
page: number;
|
||||
search: string;
|
||||
scopeToken?: string;
|
||||
};
|
||||
const id = page === 2 || search ? 101 : 1;
|
||||
return new Msg(true, '', {
|
||||
items: [
|
||||
{
|
||||
id,
|
||||
email: 'client-' + id + '@test',
|
||||
comment: '',
|
||||
enable: true,
|
||||
inScope: Boolean(scopeToken),
|
||||
},
|
||||
],
|
||||
total: search ? 1 : 50000,
|
||||
attached: 50000,
|
||||
});
|
||||
});
|
||||
const post = vi
|
||||
.spyOn(HttpUtil, 'post')
|
||||
.mockImplementation(
|
||||
async (url) =>
|
||||
new Msg(
|
||||
true,
|
||||
'',
|
||||
url.endsWith('/freeze') ? { scopeToken: 'frozen', total: 50000 } : { jobId: 'job-1' },
|
||||
),
|
||||
);
|
||||
const detached = vi.fn();
|
||||
const close = vi.fn();
|
||||
renderWithProviders(
|
||||
<DetachClientsModal open source={sourceInbound()} onClose={close} onDetached={detached} />,
|
||||
);
|
||||
await screen.findByText('client-1@test');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select this page' }));
|
||||
expect(screen.getByText('1 selected')).toBeTruthy();
|
||||
fireEvent.click(screen.getByText('2', { exact: true }));
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.objectContaining({ page: 2 }),
|
||||
expect.anything(),
|
||||
),
|
||||
);
|
||||
await screen.findByText('client-101@test');
|
||||
expect(screen.getByText('1 selected')).toBeTruthy();
|
||||
expect(
|
||||
screen.getByRole<HTMLInputElement>('checkbox', { name: 'client-101@test' }).checked,
|
||||
).toBe(false);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Select all attached clients' }));
|
||||
const choice = () =>
|
||||
screen.getByRole<HTMLInputElement>('checkbox', { name: 'client-101@test' });
|
||||
await waitFor(() => expect(choice().checked).toBe(true));
|
||||
fireEvent.click(choice());
|
||||
expect(screen.getByText('49999 selected')).toBeTruthy();
|
||||
fireEvent.change(screen.getByRole('searchbox', { name: 'Search' }), {
|
||||
target: { value: '101' },
|
||||
});
|
||||
await waitFor(() => expect(choice().checked).toBe(false));
|
||||
fireEvent.click(choice());
|
||||
expect(screen.getByText('50000 selected')).toBeTruthy();
|
||||
fireEvent.click(choice());
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Detach Clients' }));
|
||||
await waitFor(() => expect(detached).toHaveBeenCalledTimes(1));
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(post).toHaveBeenCalledWith(
|
||||
'/panel/api/clients/bulkDetach',
|
||||
{
|
||||
requestId: expect.any(String),
|
||||
inboundIds: [7],
|
||||
selection: { mode: 'allMatching', scopeToken: 'frozen', excludedClientIds: [101] },
|
||||
},
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it('ignores an older search response after the server page has changed', async () => {
|
||||
let release!: (value: Msg) => void;
|
||||
const old = new Promise<Msg>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (_url, params) => {
|
||||
const { search } = params as { search: string };
|
||||
if (search === 'old') return old;
|
||||
return new Msg(true, '', {
|
||||
items: [
|
||||
{ id: 2, email: search + '-current@test', comment: '', enable: true, inScope: false },
|
||||
],
|
||||
total: 1,
|
||||
attached: 2,
|
||||
});
|
||||
});
|
||||
renderWithProviders(<DetachClientsModal open source={sourceInbound()} onClose={() => {}} />);
|
||||
await screen.findByText('-current@test');
|
||||
const search = screen.getByRole('searchbox', { name: 'Search' });
|
||||
fireEvent.change(search, { target: { value: 'old' } });
|
||||
await waitFor(() =>
|
||||
expect(get).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.objectContaining({ search: 'old' }),
|
||||
expect.anything(),
|
||||
),
|
||||
);
|
||||
fireEvent.change(search, { target: { value: 'new' } });
|
||||
await screen.findByText('new-current@test');
|
||||
await act(async () =>
|
||||
release(
|
||||
new Msg(true, '', {
|
||||
items: [{ id: 3, email: 'stale@test', comment: '', enable: true }],
|
||||
total: 1,
|
||||
attached: 2,
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(screen.queryByText('stale@test')).toBeNull();
|
||||
expect(screen.getByText('new-current@test')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,11 +15,11 @@ const STANDARD_SOURCES = [
|
||||
file: 'geosite.dat',
|
||||
},
|
||||
{
|
||||
url: 'https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geoip.dat',
|
||||
url: 'https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geoip.dat',
|
||||
file: 'geoip_IR.dat',
|
||||
},
|
||||
{
|
||||
url: 'https://github.com/chocolate4u/Iran-v2ray-rules/releases/latest/download/geosite.dat',
|
||||
url: 'https://github.com/FDeghy/Iran-v2ray-rules/releases/latest/download/geosite.dat',
|
||||
file: 'geosite_IR.dat',
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { HostRecord } from '@/api/queries/useHostsQuery';
|
||||
import HostFormModal from '@/pages/hosts/HostFormModal';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
const ipv6 = '[2001:db8::a]:8443';
|
||||
const cidr = '192.0.2.0/24';
|
||||
const host = {
|
||||
groupId: 'g1',
|
||||
remark: 'Fixture host',
|
||||
inboundIds: [1],
|
||||
hosts: [ipv6, cidr],
|
||||
} as HostRecord;
|
||||
|
||||
function renderHost() {
|
||||
const save = vi.fn().mockResolvedValue({ success: true });
|
||||
renderWithProviders(
|
||||
<HostFormModal
|
||||
open
|
||||
mode="edit"
|
||||
host={host}
|
||||
inboundOptions={[{ id: 1, remark: 'In', tag: 'in', protocol: 'vless' }]}
|
||||
existingHosts={[host]}
|
||||
save={save}
|
||||
onOpenChange={() => {}}
|
||||
/>,
|
||||
);
|
||||
return save;
|
||||
}
|
||||
|
||||
describe('Host address tags', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it.each(['Edit', 'Copy'])(
|
||||
'keeps all addresses when Backspace is pressed on %s',
|
||||
async (action) => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
const button = screen.getByRole('button', { name: `${action} ${ipv6}` });
|
||||
button.focus();
|
||||
expect(document.activeElement).toBe(button);
|
||||
await user.keyboard('{Backspace}');
|
||||
|
||||
expect(screen.getByRole('button', { name: `Remove ${ipv6}` })).not.toBeNull();
|
||||
expect(screen.getByRole('button', { name: `Remove ${cidr}` })).not.toBeNull();
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(expect.objectContaining({ hosts: [ipv6, cidr] }));
|
||||
},
|
||||
);
|
||||
|
||||
it('pastes single and mixed-delimiter addresses and copies the exact tag text', async () => {
|
||||
vi.stubGlobal('isSecureContext', true);
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
const address = await screen.findByRole('combobox', { name: 'Address' });
|
||||
await user.click(address);
|
||||
await user.paste('Example.TEST:444');
|
||||
expect(screen.getByRole('button', { name: 'Remove Example.TEST:444' })).not.toBeNull();
|
||||
await user.paste(
|
||||
'proxy.test;192.0.2.7:443,\r\n2001:db8::7\tother.test duplicate.test duplicate.test',
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'Remove 2001:db8::7' })).not.toBeNull();
|
||||
|
||||
const copy = screen.getByRole('button', { name: `Copy ${ipv6}` });
|
||||
copy.focus();
|
||||
await user.keyboard('{Enter}');
|
||||
await waitFor(async () => expect(await navigator.clipboard.readText()).toBe(ipv6));
|
||||
const remark = screen.getByRole<HTMLInputElement>('textbox', { name: 'Remark' });
|
||||
await user.click(remark);
|
||||
await user.keyboard('{Control>}a{/Control}');
|
||||
await user.paste();
|
||||
expect(remark.value).toBe(ipv6);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
hosts: [
|
||||
ipv6,
|
||||
cidr,
|
||||
'Example.TEST:444',
|
||||
'proxy.test',
|
||||
'192.0.2.7:443',
|
||||
'2001:db8::7',
|
||||
'other.test',
|
||||
'duplicate.test',
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('edits one tag with Enter, cancels with Escape and keeps removal working', async () => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
const address = await screen.findByRole('combobox', { name: 'Address' });
|
||||
await user.dblClick(screen.getByText(ipv6, { exact: true }));
|
||||
let edit = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
|
||||
expect(document.activeElement).toBe(edit);
|
||||
expect(address.getAttribute('aria-expanded')).toBe('false');
|
||||
await user.clear(edit);
|
||||
await user.paste('[2001:db8::f]:8443');
|
||||
await user.keyboard('{Enter}');
|
||||
const replaced = screen.getByRole('button', { name: 'Edit [2001:db8::f]:8443' });
|
||||
expect(document.activeElement).toBe(replaced);
|
||||
expect(address.getAttribute('aria-expanded')).toBe('false');
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
|
||||
await user.keyboard('{Enter}');
|
||||
edit = screen.getByRole('textbox', { name: 'Edit [2001:db8::f]:8443' });
|
||||
await user.clear(edit);
|
||||
await user.type(edit, cidr);
|
||||
await user.keyboard('{Enter}');
|
||||
expect(await screen.findByText('This address is already in the list.')).not.toBeNull();
|
||||
expect(document.activeElement).toBe(edit);
|
||||
await user.clear(edit);
|
||||
await user.type(edit, 'cancelled.test');
|
||||
await user.keyboard('{Escape}');
|
||||
expect(screen.getByRole('dialog')).not.toBeNull();
|
||||
expect(document.activeElement).toBe(
|
||||
screen.getByRole('button', { name: 'Edit [2001:db8::f]:8443' }),
|
||||
);
|
||||
expect(screen.queryByText('cancelled.test')).toBeNull();
|
||||
|
||||
fireEvent.paste(address, { clipboardData: { getData: () => 'append.test' } });
|
||||
await user.click(screen.getByRole('button', { name: 'Remove append.test' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ hosts: ['[2001:db8::f]:8443', cidr] }),
|
||||
);
|
||||
});
|
||||
|
||||
it('saves the address being edited when the operator clicks Save', async () => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
await user.dblClick(screen.getByText(ipv6, { exact: true }));
|
||||
const editor = screen.getByRole('textbox', { name: `Edit ${ipv6}` });
|
||||
await user.clear(editor);
|
||||
await user.type(editor, 'replacement.test');
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }));
|
||||
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ hosts: ['replacement.test', cidr] }),
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps an invalid draft and blocks saving until it is corrected', async () => {
|
||||
const user = userEvent.setup();
|
||||
const save = renderHost();
|
||||
await user.dblClick(screen.getByText(ipv6, { exact: true }));
|
||||
const editor = screen.getByRole<HTMLInputElement>('textbox', { name: `Edit ${ipv6}` });
|
||||
const saveButton = screen.getByRole('button', { name: 'Save' });
|
||||
await user.clear(editor);
|
||||
await user.type(editor, cidr);
|
||||
await user.click(saveButton);
|
||||
expect(await screen.findByText('This address is already in the list.')).not.toBeNull();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
expect(editor.value).toBe(cidr);
|
||||
expect(screen.getByRole('textbox', { name: `Edit ${ipv6}` })).toBe(editor);
|
||||
|
||||
await user.clear(editor);
|
||||
await user.type(editor, 'corrected.test');
|
||||
await user.tab();
|
||||
const replacement = screen.getByRole('button', { name: 'Edit corrected.test' });
|
||||
expect(document.activeElement).not.toBe(replacement);
|
||||
await user.click(saveButton);
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(expect.objectContaining({ hosts: ['corrected.test', cidr] }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import { useState, type ComponentProps } from 'react';
|
||||
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
|
||||
import { ConfigProvider } from 'antd';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { HostRecord } from '@/api/queries/useHostsQuery';
|
||||
import HostFormModal from '@/pages/hosts/HostFormModal';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import { chooseSelectOption, renderWithProviders } from './test-utils';
|
||||
|
||||
const inboundOptions = [{ id: 1, remark: 'Fixture inbound', tag: 'in', protocol: 'vless' }];
|
||||
const first = {
|
||||
groupId: 'first',
|
||||
remark: 'First host',
|
||||
inboundIds: [1],
|
||||
hosts: ['first.example.test'],
|
||||
port: 8443,
|
||||
} as HostRecord;
|
||||
const second = {
|
||||
...first,
|
||||
groupId: 'second',
|
||||
remark: 'Second host',
|
||||
hosts: ['second.example.test'],
|
||||
port: 443,
|
||||
} as HostRecord;
|
||||
|
||||
function Sessions({ save }: { save: ComponentProps<typeof HostFormModal>['save'] }) {
|
||||
const [host, setHost] = useState<HostRecord | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
function show(next: HostRecord | null) {
|
||||
setHost(next);
|
||||
setOpen(true);
|
||||
}
|
||||
return (
|
||||
<ConfigProvider theme={{ token: { motion: false } }}>
|
||||
<button onClick={() => show(null)}>New session</button>
|
||||
<button onClick={() => show(first)}>First session</button>
|
||||
<button onClick={() => show(second)}>Second session</button>
|
||||
<button onClick={() => setOpen(false)}>Close externally</button>
|
||||
<HostFormModal
|
||||
open={open}
|
||||
mode={host ? 'edit' : 'add'}
|
||||
host={host}
|
||||
inboundOptions={inboundOptions}
|
||||
existingHosts={[first, second]}
|
||||
save={save}
|
||||
onOpenChange={setOpen}
|
||||
/>
|
||||
</ConfigProvider>
|
||||
);
|
||||
}
|
||||
|
||||
async function openSession(name = 'New session') {
|
||||
fireEvent.click(screen.getByRole('button', { name }));
|
||||
return screen.findByRole<HTMLInputElement>('textbox', { name: 'Remark' });
|
||||
}
|
||||
|
||||
function fillDraft(remark: HTMLElement) {
|
||||
fireEvent.change(remark, { target: { value: 'Draft host' } });
|
||||
const inbound = screen.getByRole('combobox', { name: 'Inbounds' });
|
||||
chooseSelectOption(inbound.id, 'Fixture inbound');
|
||||
fireEvent.change(screen.getByRole('spinbutton', { name: 'Port' }), { target: { value: '9443' } });
|
||||
const address = screen.getByRole('combobox', { name: 'Address' });
|
||||
fireEvent.change(address, { target: { value: 'draft.example.test,' } });
|
||||
}
|
||||
|
||||
async function closeSession() {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
}
|
||||
|
||||
describe('Host form sessions', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
|
||||
});
|
||||
|
||||
it.each(['success', 'rejection', 'error', 'cancel'])(
|
||||
'starts from Add defaults after a previous %s',
|
||||
async (result) => {
|
||||
const save = vi.fn().mockResolvedValue({ success: result === 'success', msg: 'Cannot save' });
|
||||
if (result === 'error') {
|
||||
save.mockRejectedValue(new Error('Request failed'));
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
}
|
||||
renderWithProviders(<Sessions save={save} />);
|
||||
const remark = await openSession();
|
||||
fillDraft(remark);
|
||||
if (result !== 'cancel') {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
remark: 'Draft host',
|
||||
port: 9443,
|
||||
hosts: ['draft.example.test'],
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (result === 'success') {
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
} else {
|
||||
expect(screen.getByRole<HTMLInputElement>('textbox', { name: 'Remark' }).value).toBe(
|
||||
'Draft host',
|
||||
);
|
||||
await closeSession();
|
||||
}
|
||||
|
||||
expect((await openSession()).value).toBe('');
|
||||
expect(screen.getByRole<HTMLInputElement>('spinbutton', { name: 'Port' }).value).toBe('0');
|
||||
expect(screen.queryByRole('button', { name: 'Remove draft.example.test' })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Remove Fixture inbound' })).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it('loads a different Edit host and then opens a clean Add form', async () => {
|
||||
renderWithProviders(<Sessions save={vi.fn()} />);
|
||||
expect((await openSession('First session')).value).toBe('First host');
|
||||
expect((await openSession('Second session')).value).toBe('Second host');
|
||||
expect(screen.getByRole('button', { name: 'Remove second.example.test' })).not.toBeNull();
|
||||
await closeSession();
|
||||
expect((await openSession()).value).toBe('');
|
||||
expect(screen.queryByRole('button', { name: 'Remove second.example.test' })).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a later session open when a cancelled request finishes', async () => {
|
||||
let resolve!: (value: { success: boolean }) => void;
|
||||
const pending = new Promise<{ success: boolean }>((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
const save = vi.fn().mockReturnValue(pending);
|
||||
renderWithProviders(<Sessions save={save} />);
|
||||
await openSession('First session');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close externally' }));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
|
||||
expect((await openSession('Second session')).value).toBe('Second host');
|
||||
await act(async () => resolve({ success: true }));
|
||||
expect(screen.getByRole<HTMLInputElement>('textbox', { name: 'Remark' }).value).toBe(
|
||||
'Second host',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { act, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
import { expect, it, vi } from 'vitest';
|
||||
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import InboundsPage from '@/pages/inbounds/InboundsPage';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
|
||||
import { makeTestQueryClient, renderWithProviders } from './test-utils';
|
||||
|
||||
const socket = vi.hoisted(() => ({
|
||||
handlers: {} as Record<string, (payload: unknown) => void>,
|
||||
}));
|
||||
vi.mock('@/hooks/useWebSocket', () => ({
|
||||
useWebSocket: (handlers: typeof socket.handlers) => {
|
||||
socket.handlers = handlers;
|
||||
},
|
||||
}));
|
||||
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
|
||||
|
||||
it('keeps the selected inbound info tab and loaded IPs across live counter updates', async () => {
|
||||
const client = { email: 'edge@example.test', enable: true, limitIp: 1 };
|
||||
const stats = { email: client.email, up: 0, down: 0, total: 0, expiryTime: 0, enable: true };
|
||||
const inbound = {
|
||||
id: 7,
|
||||
protocol: 'socks',
|
||||
remark: 'Edge',
|
||||
tag: 'inbound-7000',
|
||||
port: 7000,
|
||||
enable: true,
|
||||
settings: { clients: [client] },
|
||||
streamSettings: { network: 'tcp', security: 'none' },
|
||||
clientStats: [stats],
|
||||
};
|
||||
const queryClient = makeTestQueryClient();
|
||||
queryClient.setDefaultOptions({ queries: { retry: false, staleTime: Infinity } });
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [inbound]);
|
||||
queryClient.setQueryData(keys.settings.defaults(), { ipLimitEnable: true });
|
||||
queryClient.setQueryData(keys.hosts.list(), []);
|
||||
queryClient.setQueryData(keys.nodes.list(), []);
|
||||
queryClient.setQueryData(keys.clients.onlines(), []);
|
||||
queryClient.setQueryData(keys.clients.onlinesByGuid(), {});
|
||||
queryClient.setQueryData(keys.clients.activeInbounds(), {});
|
||||
queryClient.setQueryData(keys.clients.lastOnline(), {});
|
||||
vi.mocked(HttpUtil.get).mockResolvedValue(
|
||||
new Msg(true, '', { inbound, totalPeers: 0, peerOffset: 0 }),
|
||||
);
|
||||
const clientIp = '192.0.2.5';
|
||||
const post = vi
|
||||
.mocked(HttpUtil.post)
|
||||
.mockImplementation(
|
||||
async (url) => new Msg(true, '', url.startsWith('/panel/api/clients/ips/') ? [clientIp] : {}),
|
||||
);
|
||||
|
||||
const user = userEvent.setup();
|
||||
renderWithProviders(
|
||||
<MemoryRouter>
|
||||
<InboundsPage />
|
||||
</MemoryRouter>,
|
||||
{ queryClient },
|
||||
);
|
||||
await user.click(await screen.findByRole('button', { name: /^more$/i }));
|
||||
await user.click(await screen.findByRole('menuitem', { name: 'Inbound Information' }));
|
||||
const dialog = within(await screen.findByRole('dialog', { name: 'Inbound Information' }));
|
||||
await dialog.findByText(clientIp);
|
||||
const inboundTab = dialog.getByRole('tab', { name: 'Inbound' });
|
||||
await user.click(inboundTab);
|
||||
|
||||
act(() =>
|
||||
socket.handlers.client_stats({
|
||||
inbounds: [{ id: inbound.id, up: 1024, down: 0, total: 0, enable: true }],
|
||||
clients: [{ ...stats, up: 1024 }],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(inboundTab.getAttribute('aria-selected')).toBe('true');
|
||||
await user.click(dialog.getByRole('tab', { name: 'Client' }));
|
||||
expect(dialog.getByText(clientIp)).toBeTruthy();
|
||||
expect(post.mock.calls.filter(([url]) => url.startsWith('/panel/api/clients/ips/'))).toHaveLength(
|
||||
1,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest';
|
||||
import { BlobReader, TextWriter, ZipReader } from '@zip.js/zip.js';
|
||||
|
||||
import { buildInboundPeerArchive } from '@/pages/inbounds/info/peerExport';
|
||||
|
||||
const inboundID = 19;
|
||||
const serverKey = 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=';
|
||||
const peerKey = 'AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=';
|
||||
|
||||
function exportPage(peerOffset: number, totalPeers = 2, protocol = 'wireguard') {
|
||||
return {
|
||||
inbound: {
|
||||
id: inboundID,
|
||||
protocol,
|
||||
port: 51820,
|
||||
listen: '',
|
||||
remark: 'edge',
|
||||
settings: {
|
||||
secretKey: serverKey,
|
||||
server: { publicKey: serverKey, h1: '10-20' },
|
||||
clients: [
|
||||
{
|
||||
email: `client-${peerOffset + 1}`,
|
||||
publicKey: serverKey,
|
||||
privateKey: peerKey,
|
||||
allowedIPs: [`10.8.0.${peerOffset + 2}/32`],
|
||||
},
|
||||
],
|
||||
},
|
||||
streamSettings: {
|
||||
externalProxy: [
|
||||
{ dest: 'edge-a.example.test', port: 4443, forceTls: 'same', remark: 'A' },
|
||||
{ dest: 'edge-b.example.test', port: 5443, forceTls: 'same', remark: 'B' },
|
||||
],
|
||||
},
|
||||
},
|
||||
totalPeers,
|
||||
peerOffset,
|
||||
};
|
||||
}
|
||||
|
||||
function mockExport(pages: unknown[]) {
|
||||
const data = new TextEncoder().encode(pages.map((page) => JSON.stringify(page) + '\n').join(''));
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
controller.enqueue(data.subarray(0, 61));
|
||||
controller.enqueue(data.subarray(61));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
const fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(stream, { headers: { 'Content-Type': 'application/x-ndjson' } }),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
vi.stubGlobal('window', { setTimeout, location: { hostname: 'panel.example.test' } });
|
||||
return fetch;
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it.each(['wireguard', 'amneziawg'])(
|
||||
'archives ordered %s peer configurations and links for every host',
|
||||
async (protocol) => {
|
||||
const fetch = mockExport([exportPage(0, 2, protocol), exportPage(1, 2, protocol)]);
|
||||
const archive = await buildInboundPeerArchive(inboundID, {}, new AbortController().signal);
|
||||
expect(fetch.mock.calls.map(([url]) => url)).toEqual([
|
||||
`/panel/api/inbounds/${inboundID}/peerExport`,
|
||||
]);
|
||||
const zip = new ZipReader(new BlobReader(archive));
|
||||
try {
|
||||
const files = await zip.getEntries();
|
||||
expect(files.map((file) => file.filename)).toEqual([
|
||||
'peer-1-1.conf',
|
||||
'peer-1-2.conf',
|
||||
'peer-2-1.conf',
|
||||
'peer-2-2.conf',
|
||||
'links.txt',
|
||||
]);
|
||||
const result = await Promise.all(
|
||||
files.map((file) => {
|
||||
if (file.directory) throw new Error('Unexpected directory');
|
||||
return file.getData(new TextWriter());
|
||||
}),
|
||||
);
|
||||
expect(result[0]).toContain('# edge-A-1');
|
||||
expect(result[0]).toContain('Endpoint = edge-a.example.test:4443');
|
||||
expect(result[3]).toContain('# edge-B-2');
|
||||
expect(result[3]).toContain('Address = 10.8.0.3/32');
|
||||
const links = result[4]!.split('\r\n');
|
||||
expect(links).toHaveLength(4);
|
||||
if (protocol === 'wireguard') {
|
||||
expect(new URL(links[3]!).hash).toBe('#edge-B-2');
|
||||
} else {
|
||||
const encoded = links[3]!.slice('vpn://'.length).replace(/-/g, '+').replace(/_/g, '/');
|
||||
expect(atob(encoded)).toBe(result[3]);
|
||||
}
|
||||
} finally {
|
||||
await zip.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('does not publish an archive when a peer stream ends before its advertised total', async () => {
|
||||
mockExport([exportPage(0)]);
|
||||
await expect(
|
||||
buildInboundPeerArchive(inboundID, {}, new AbortController().signal),
|
||||
).rejects.toThrow('Incomplete inbound peer export');
|
||||
});
|
||||
|
||||
it('cancels the reader when the export is interrupted', async () => {
|
||||
const controller = new AbortController();
|
||||
const cancel = vi.fn();
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
start(reader) {
|
||||
reader.enqueue(new TextEncoder().encode(JSON.stringify(exportPage(0)) + '\n'));
|
||||
controller.abort();
|
||||
},
|
||||
cancel,
|
||||
});
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
new Response(stream, { headers: { 'Content-Type': 'application/x-ndjson' } }),
|
||||
),
|
||||
);
|
||||
vi.stubGlobal('window', { setTimeout, location: { hostname: 'panel.example.test' } });
|
||||
await expect(buildInboundPeerArchive(inboundID, {}, controller.signal)).rejects.toMatchObject({
|
||||
name: 'AbortError',
|
||||
});
|
||||
expect(cancel).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -1,18 +1,27 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { useLayoutEffect, type ReactNode } from 'react';
|
||||
import { act, fireEvent, renderHook, screen, waitFor, within } from '@testing-library/react';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { MemoryRouter } from 'react-router';
|
||||
|
||||
import { keys } from '@/api/queryKeys';
|
||||
import { getSharedWebSocketClient } from '@/api/websocket';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import InboundsPage from '@/pages/inbounds/InboundsPage';
|
||||
import { HttpUtil, Msg } from '@/utils';
|
||||
import { useInbounds } from '@/pages/inbounds/useInbounds';
|
||||
|
||||
import { makeTestQueryClient } from './test-utils';
|
||||
import { makeTestQueryClient, renderWithProviders } from './test-utils';
|
||||
|
||||
vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
|
||||
vi.mock('@/pages/inbounds/form/InboundFormModal', () => ({ default: () => null }));
|
||||
|
||||
function seedInbounds() {
|
||||
const rows = [1, 2].map((id) => ({
|
||||
id,
|
||||
protocol: 'vless',
|
||||
tag: `in-${id}`,
|
||||
originNodeGuid: `node-${id}`,
|
||||
enable: true,
|
||||
up: 10,
|
||||
down: 20,
|
||||
@@ -33,7 +42,7 @@ function seedInbounds() {
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
return { rows, wrapper };
|
||||
return { queryClient, rows, wrapper };
|
||||
}
|
||||
|
||||
async function renderInbounds() {
|
||||
@@ -71,6 +80,7 @@ describe('inbound websocket merges keep unchanged state', () => {
|
||||
it('still rebuilds exactly the rows whose numbers moved', async () => {
|
||||
const { result } = await renderInbounds();
|
||||
const before = result.current.dbInbounds;
|
||||
const countsBefore = result.current.clientCount;
|
||||
|
||||
act(() =>
|
||||
result.current.applyClientStatsEvent({
|
||||
@@ -85,8 +95,10 @@ describe('inbound websocket merges keep unchanged state', () => {
|
||||
const [first, second] = result.current.dbInbounds;
|
||||
expect(first).not.toBe(before[0]);
|
||||
expect(first.up).toBe(99);
|
||||
expect(result.current.clientCount[1]).toBe(countsBefore[1]);
|
||||
expect(second).not.toBe(before[1]);
|
||||
expect(second.clientStats?.[0]?.up).toBe(5);
|
||||
expect(result.current.clientCount[2]).not.toBe(countsBefore[2]);
|
||||
});
|
||||
|
||||
it('keeps the client rollup when a traffic push repeats the same online sets', async () => {
|
||||
@@ -105,3 +117,280 @@ describe('inbound websocket merges keep unchanged state', () => {
|
||||
expect(result.current.clientCount).toBe(rollup);
|
||||
});
|
||||
});
|
||||
|
||||
it('reuses unaffected rollups and client metadata on large online updates', async () => {
|
||||
const { queryClient, rows, wrapper } = seedInbounds();
|
||||
const clients = Array.from({ length: 4000 }, (_, i) => ({
|
||||
email: `client-${i}@x`,
|
||||
enable: true,
|
||||
comment: 'shared subscription',
|
||||
}));
|
||||
const settings = JSON.stringify({ clients });
|
||||
queryClient.setQueryData(
|
||||
keys.inbounds.slim(),
|
||||
Array.from({ length: 30 }, (_, i) => ({
|
||||
...rows[i % 2],
|
||||
id: i + 1,
|
||||
tag: `large-${i + 1}`,
|
||||
settings,
|
||||
})),
|
||||
);
|
||||
const { result } = renderHook(() => useInbounds(), { wrapper });
|
||||
await waitFor(() => expect(result.current.clientCount[30]?.clients).toBe(4000));
|
||||
const before = result.current.clientCount;
|
||||
act(() =>
|
||||
result.current.applyTrafficEvent({
|
||||
onlineByGuid: { 'node-1': [clients[0].email], 'node-2': [clients[1].email] },
|
||||
activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[0].email]));
|
||||
const initial = result.current.clientCount;
|
||||
expect(initial[1].active).toBe(before[1].active);
|
||||
expect(initial[1].online).toEqual([clients[0].email]);
|
||||
|
||||
act(() =>
|
||||
result.current.applyTrafficEvent({
|
||||
onlineByGuid: { 'node-1': [clients[2].email], 'node-2': [clients[1].email] },
|
||||
activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[2].email]));
|
||||
expect(result.current.clientCount[1].active).toBe(initial[1].active);
|
||||
for (let id = 2; id <= 30; id++) {
|
||||
expect(result.current.clientCount[id]).toBe(initial[id]);
|
||||
}
|
||||
});
|
||||
|
||||
it('loads inbounds whose clientStats is null in the slim response', () => {
|
||||
const { rows, queryClient, wrapper } = seedInbounds();
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [
|
||||
{ ...rows[0], protocol: 'mixed', settings: '{}', clientStats: null },
|
||||
{ ...rows[1], settings: '{"clients":[]}', clientStats: null },
|
||||
]);
|
||||
const { result } = renderHook(() => useInbounds(), { wrapper });
|
||||
expect(result.current.fetched).toBe(true);
|
||||
expect(result.current.dbInbounds.map((row) => row.id)).toEqual([1, 2]);
|
||||
expect(result.current.clientCount[1]).toBeUndefined();
|
||||
expect(result.current.clientCount[2].clients).toBe(0);
|
||||
});
|
||||
|
||||
it('withholds large inbound rollups until they match the refetched structure', async () => {
|
||||
const { queryClient, rows, wrapper } = seedInbounds();
|
||||
const withClients = (count: number, remark: string) => ({
|
||||
...rows[0],
|
||||
remark,
|
||||
settings: JSON.stringify({
|
||||
clients: Array.from({ length: count }, (_, i) => ({
|
||||
email: `member-${i}@example.test`,
|
||||
enable: true,
|
||||
})),
|
||||
}),
|
||||
});
|
||||
const seed = withClients(7000, 'initial');
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [seed]);
|
||||
const displayed: { remark: string; fetched: boolean; pending: boolean; count?: number }[] = [];
|
||||
const { result } = renderHook(
|
||||
() => {
|
||||
const data = useInbounds();
|
||||
useLayoutEffect(() => {
|
||||
const row = data.dbInbounds[0];
|
||||
if (row)
|
||||
displayed.push({
|
||||
remark: row.remark,
|
||||
fetched: data.fetched,
|
||||
pending: data.clientCountsPending,
|
||||
count: data.clientCount[row.id]?.clients,
|
||||
});
|
||||
});
|
||||
return data;
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(7000));
|
||||
for (const [count, remark] of [
|
||||
[8000, 'large refetch'],
|
||||
[1, 'small refetch'],
|
||||
[9000, 'large again'],
|
||||
] as const) {
|
||||
act(() => queryClient.setQueryData(keys.inbounds.slim(), [withClients(count, remark)]));
|
||||
await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(count));
|
||||
expect(displayed.filter((view) => view.remark === remark)).toEqual(
|
||||
expect.arrayContaining([{ remark, fetched: true, pending: false, count }]),
|
||||
);
|
||||
for (const view of displayed.filter((view) => view.remark === remark)) {
|
||||
expect(view.fetched).toBe(true);
|
||||
expect(view.count).toBe(view.pending ? undefined : count);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the search, node filter and selection through large-list refetch and detail hydration', async () => {
|
||||
const { queryClient, rows } = seedInbounds();
|
||||
const clients = (count: number) =>
|
||||
JSON.stringify({
|
||||
clients: Array.from({ length: count }, (_, i) => ({
|
||||
email: `member-${i}@example.test`,
|
||||
enable: true,
|
||||
})),
|
||||
});
|
||||
const local = { ...rows[0], remark: 'Kept local', settings: clients(7000) };
|
||||
const remote = { ...rows[1], remark: 'Kept remote', nodeId: 7 };
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [local, remote]);
|
||||
queryClient.setQueryDefaults(keys.nodes.list(), { staleTime: Infinity });
|
||||
queryClient.setQueryData(keys.nodes.list(), [
|
||||
{ id: 7, name: 'Remote', enable: true, status: 'online' },
|
||||
]);
|
||||
queryClient.setQueryData(keys.hosts.list(), []);
|
||||
const get = vi.mocked(HttpUtil.get);
|
||||
const fallback = get.getMockImplementation();
|
||||
get.mockImplementation(async (url, ...args) =>
|
||||
url === '/panel/api/inbounds/get/1'
|
||||
? new Msg(true, '', { ...local, remark: 'Kept hydrated', settings: clients(9000) })
|
||||
: ((await fallback?.(url, ...args)) ?? new Msg(true, '', [])),
|
||||
);
|
||||
|
||||
const view = renderWithProviders(
|
||||
<MemoryRouter>
|
||||
<InboundsPage />
|
||||
</MemoryRouter>,
|
||||
{ queryClient },
|
||||
);
|
||||
try {
|
||||
await screen.findAllByText('7000');
|
||||
const search = screen.getByRole('textbox', { name: 'Search' });
|
||||
fireEvent.change(search, { target: { value: 'Kept' } });
|
||||
fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Nodes' }));
|
||||
fireEvent.click(await screen.findByText('Local (this panel)'));
|
||||
const row = () => screen.getByRole('row', { name: /Kept (local|refetched|hydrated)/ });
|
||||
fireEvent.click(within(row()).getByRole('checkbox'));
|
||||
const expectContext = () => {
|
||||
expect(screen.getByRole('textbox', { name: 'Search' })).toBe(search);
|
||||
expect((search as HTMLInputElement).value).toBe('Kept');
|
||||
expect(screen.queryByText('Kept remote')).toBeNull();
|
||||
expect((within(row()).getByRole('checkbox') as HTMLInputElement).checked).toBe(true);
|
||||
};
|
||||
expectContext();
|
||||
|
||||
act(() =>
|
||||
queryClient.setQueryData(keys.inbounds.slim(), [
|
||||
{ ...local, remark: 'Kept refetched', settings: clients(8000) },
|
||||
remote,
|
||||
]),
|
||||
);
|
||||
await screen.findAllByText('8000');
|
||||
expectContext();
|
||||
|
||||
fireEvent.click(within(row()).getByRole('button', { name: 'Edit' }));
|
||||
await screen.findAllByText('9000');
|
||||
expectContext();
|
||||
} finally {
|
||||
view.unmount();
|
||||
getSharedWebSocketClient().disconnect();
|
||||
if (fallback) get.mockImplementation(fallback);
|
||||
}
|
||||
});
|
||||
|
||||
it('reuses the current rollup cache for subscribed websocket updates after defaults change', async () => {
|
||||
const { queryClient, wrapper } = seedInbounds();
|
||||
const sockets: EventTarget[] = [];
|
||||
class FixtureSocket extends EventTarget {
|
||||
static readonly CONNECTING = 0;
|
||||
static readonly OPEN = 1;
|
||||
readyState = FixtureSocket.CONNECTING;
|
||||
constructor() {
|
||||
super();
|
||||
sockets.push(this);
|
||||
}
|
||||
close() {}
|
||||
}
|
||||
const socketClient = getSharedWebSocketClient();
|
||||
socketClient.disconnect();
|
||||
vi.stubGlobal('WebSocket', FixtureSocket);
|
||||
const { result, unmount } = renderHook(
|
||||
() => {
|
||||
const data = useInbounds();
|
||||
useWebSocket({ client_stats: data.applyClientStatsEvent });
|
||||
return data;
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
try {
|
||||
await waitFor(() => expect(result.current.clientCount[1]?.clients).toBe(1));
|
||||
act(() => queryClient.setQueryData(keys.settings.defaults(), { expireDiff: 3 }));
|
||||
await waitFor(() => expect(result.current.expireDiff).toBe(3 * 86400000));
|
||||
const afterDefaults = result.current.clientCount[1];
|
||||
const [socket] = sockets;
|
||||
if (!socket) throw new Error('WebSocket was not connected');
|
||||
act(() =>
|
||||
socket.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({
|
||||
type: 'client_stats',
|
||||
payload: { inbounds: [{ id: 1, up: 99 }] },
|
||||
}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(result.current.dbInbounds[0].up).toBe(99);
|
||||
expect(result.current.clientCount[1]).toBe(afterDefaults);
|
||||
} finally {
|
||||
unmount();
|
||||
socketClient.disconnect();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not attribute shared online clients without matching inbound activity', async () => {
|
||||
const { rows, queryClient, wrapper } = seedInbounds();
|
||||
queryClient.setQueryData(
|
||||
keys.inbounds.slim(),
|
||||
rows.map((row) => ({
|
||||
...row,
|
||||
originNodeGuid: 'shared-node',
|
||||
settings: JSON.stringify({ clients: [{ email: 'c1@x', enable: true }] }),
|
||||
})),
|
||||
);
|
||||
const { result } = renderHook(() => useInbounds(), { wrapper });
|
||||
await waitFor(() => expect(result.current.dbInbounds).toHaveLength(2));
|
||||
const publish = (
|
||||
onlineByGuid: Record<string, string[]>,
|
||||
activeInbounds: Record<string, string[] | null>,
|
||||
) => act(() => result.current.applyTrafficEvent({ onlineByGuid, activeInbounds }));
|
||||
publish({ 'shared-node': ['c1@x'] }, {});
|
||||
expect(result.current.clientCount[1].online).toEqual([]);
|
||||
expect(result.current.clientCount[1].onlineAttribution).toBe('unavailable');
|
||||
expect(result.current.clientCount[2].onlineAttribution).toBe('unavailable');
|
||||
publish({ 'shared-node': ['c1@x'] }, { 'shared-node': ['in-2', '\0'] });
|
||||
expect(result.current.clientCount[1].onlineAttribution).toBe('unavailable');
|
||||
expect(result.current.clientCount[2].onlineAttribution).toBe('inbound');
|
||||
expect(result.current.clientCount[2].online).toEqual(['c1@x']);
|
||||
publish({ 'shared-node': ['c1@x'] }, { 'shared-node': [] });
|
||||
expect(result.current.clientCount[1].online).toEqual([]);
|
||||
expect(result.current.clientCount[1].onlineAttribution).toBe('inbound');
|
||||
publish({ 'shared-node': ['c1@x'] }, { 'shared-node': ['in-2'] });
|
||||
expect(result.current.clientCount[1].online).toEqual([]);
|
||||
expect(result.current.clientCount[2].online).toEqual(['c1@x']);
|
||||
publish({}, {});
|
||||
expect(result.current.clientCount[2].onlineAttribution).toBe('unavailable');
|
||||
publish({ 'shared-node': ['c1@x'] }, { 'shared-node': null });
|
||||
expect(result.current.clientCount[2].onlineAttribution).toBe('node');
|
||||
expect(result.current.clientCount[2].online).toEqual(['c1@x']);
|
||||
publish({ 'shared-node': [] }, { 'shared-node': [] });
|
||||
expect(result.current.clientCount[2].onlineAttribution).toBe('inbound');
|
||||
expect(result.current.clientCount[2].online).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps online status pending while the activity query is unresolved', async () => {
|
||||
const { queryClient, wrapper } = seedInbounds();
|
||||
queryClient.removeQueries({ queryKey: keys.clients.activeInbounds() });
|
||||
const post = vi.spyOn(HttpUtil, 'post').mockImplementation(() => new Promise(() => {}));
|
||||
try {
|
||||
const { result } = renderHook(() => useInbounds(), { wrapper });
|
||||
await waitFor(() => expect(result.current.clientCount[1].onlineAttribution).toBe('pending'));
|
||||
expect(result.current.clientCount[1].online).toEqual([]);
|
||||
} finally {
|
||||
post.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -39,8 +39,6 @@ describe('network traffic status', () => {
|
||||
down={[200]}
|
||||
labels={['12:00']}
|
||||
isMobile={false}
|
||||
range={2}
|
||||
onRangeChange={() => undefined}
|
||||
/>,
|
||||
);
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { act, fireEvent, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import NodeList from '@/pages/nodes/NodeList';
|
||||
import type { NodeRecord } from '@/schemas/node';
|
||||
import { renderWithProviders } from './test-utils';
|
||||
|
||||
const counts = {
|
||||
inboundCount: 1,
|
||||
clientCount: 2,
|
||||
activeCount: 2,
|
||||
disabledCount: 0,
|
||||
depletedCount: 0,
|
||||
onlineCount: 1,
|
||||
};
|
||||
const noop = () => {};
|
||||
const actions = {
|
||||
onAdd: noop,
|
||||
onMtls: noop,
|
||||
onEdit: noop,
|
||||
onDelete: noop,
|
||||
onProbe: noop,
|
||||
onToggleEnable: noop,
|
||||
onUpdateNode: noop,
|
||||
onUpdateSelected: noop,
|
||||
onRestart: noop,
|
||||
};
|
||||
|
||||
it('hides Master and All nodes without a remote, even with fresh Master telemetry', async () => {
|
||||
const onAdd = vi.fn();
|
||||
const sampledAt = Date.now();
|
||||
function list(nodes: NodeRecord[]) {
|
||||
return (
|
||||
<NodeList
|
||||
{...actions}
|
||||
onAdd={onAdd}
|
||||
nodes={nodes}
|
||||
master={{ counts, telemetry: { sampledAt, cpuPct: 31 } }}
|
||||
fleet={counts}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const view = renderWithProviders(list([]));
|
||||
expect(screen.getAllByRole('row')).toHaveLength(2);
|
||||
expect(screen.queryByRole('searchbox')).toBeNull();
|
||||
expect(screen.queryByText('All nodes')).toBeNull();
|
||||
expect(screen.queryByRole('rowheader', { name: 'Master' })).toBeNull();
|
||||
expect(screen.queryByRole('switch')).toBeNull();
|
||||
await userEvent.click(screen.getByRole('button', { name: /add node/i }));
|
||||
expect(onAdd).toHaveBeenCalledOnce();
|
||||
view.rerender(list([{ id: 1, name: 'disabled edge', enable: false, status: 'online' }]));
|
||||
const rows = screen.getAllByRole('row');
|
||||
expect(rows[1].textContent).toContain('All nodes');
|
||||
expect(rows[1].textContent).toContain('1/2 reporting');
|
||||
expect(rows[2].textContent).toContain('Master');
|
||||
expect(rows[3].textContent).toContain('disabled edge');
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'unmatched' } });
|
||||
expect(screen.getAllByRole('row')).toHaveLength(3);
|
||||
expect(screen.getByText('1/2 reporting')).toBeTruthy();
|
||||
view.rerender(list([]));
|
||||
expect(screen.getAllByRole('row')).toHaveLength(2);
|
||||
expect(screen.queryByText(/totals use reporting nodes/)).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the column headings over an empty-state row until a remote is registered', () => {
|
||||
function list(nodes: NodeRecord[]) {
|
||||
return (
|
||||
<NodeList
|
||||
{...actions}
|
||||
nodes={nodes}
|
||||
master={{ counts }}
|
||||
fleet={counts}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const view = renderWithProviders(list([]));
|
||||
const table = within(screen.getByRole('table'));
|
||||
expect(table.getByRole('columnheader', { name: 'Status' })).toBeTruthy();
|
||||
expect(table.getByRole('cell', { name: 'Nothing here yet' })).toBeTruthy();
|
||||
view.rerender(list([{ id: 1, name: 'edge', enable: true, status: 'online' }]));
|
||||
expect(screen.queryByText('Nothing here yet')).toBeNull();
|
||||
expect(screen.getByRole('rowheader', { name: 'edge' })).toBeTruthy();
|
||||
});
|
||||
|
||||
it('expires only the stale host and keeps weighted RAM and live byte rates separate', () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const now = Date.now();
|
||||
renderWithProviders(
|
||||
<NodeList
|
||||
{...actions}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
nodesUpdatedAt={now}
|
||||
nodes={[
|
||||
{
|
||||
id: 1,
|
||||
name: 'edge',
|
||||
enable: true,
|
||||
status: 'online',
|
||||
telemetry: {
|
||||
sampledAt: now - 29_500,
|
||||
sampleAgeMillis: 29_500,
|
||||
memUsedBytes: 4 * 2 ** 30,
|
||||
memTotalBytes: 16 * 2 ** 30,
|
||||
netDown: 1024,
|
||||
tcpCount: 0,
|
||||
cpuPct: 20,
|
||||
logicalCores: 4,
|
||||
},
|
||||
},
|
||||
]}
|
||||
master={{
|
||||
counts,
|
||||
telemetry: {
|
||||
sampledAt: now,
|
||||
sampleAgeMillis: 0,
|
||||
memUsedBytes: 6 * 2 ** 30,
|
||||
memTotalBytes: 8 * 2 ** 30,
|
||||
cpuPct: 40,
|
||||
logicalCores: 8,
|
||||
netDown: 2048,
|
||||
tcpCount: 10,
|
||||
},
|
||||
}}
|
||||
fleet={counts}
|
||||
/>,
|
||||
);
|
||||
const fleet = () => within(screen.getByRole('row', { name: /All nodes/ }));
|
||||
expect(fleet().getByText(/10 GB \/ 24 GB · 41.7%/)).toBeTruthy();
|
||||
expect(fleet().getByText('30.0%')).toBeTruthy();
|
||||
expect(fleet().getByLabelText(/download 3.00 KB\/s/i)).toBeTruthy();
|
||||
act(() => vi.advanceTimersByTime(501));
|
||||
expect(fleet().getByText('1/2 reporting')).toBeTruthy();
|
||||
expect(fleet().getByText('40.0%')).toBeTruthy();
|
||||
expect(fleet().getByLabelText(/download 2.00 KB\/s/i)).toBeTruthy();
|
||||
expect(
|
||||
within(screen.getByRole('row', { name: /edge/ })).getByLabelText(/download —/i),
|
||||
).toBeTruthy();
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,200 @@
|
||||
import { useState } from 'react';
|
||||
import { fireEvent, screen, waitFor, within } from '@testing-library/react';
|
||||
import { expect, it, vi } from 'vitest';
|
||||
|
||||
import NodeFormModal from '@/pages/nodes/NodeFormModal';
|
||||
import type { NodeRecord, ProbeResult } from '@/schemas/node';
|
||||
import { Msg } from '@/utils';
|
||||
import { chooseSelectOption, renderWithProviders } from './test-utils';
|
||||
|
||||
const stored: NodeRecord = {
|
||||
id: 11,
|
||||
name: 'Primary',
|
||||
address: 'primary.example.test',
|
||||
port: 2053,
|
||||
status: 'online',
|
||||
enable: true,
|
||||
hasApiToken: true,
|
||||
};
|
||||
const other: NodeRecord = { ...stored, id: 22, name: 'Secondary', tlsVerifyMode: 'pin' };
|
||||
const unexpectedValue = 'unrelated-fixture';
|
||||
const apiTokenLabel = { selector: 'input' };
|
||||
|
||||
function setup() {
|
||||
const probe = vi.fn(async (payload: Partial<NodeRecord>) =>
|
||||
payload.apiToken === 'incorrect-fixture'
|
||||
? new Msg<ProbeResult>(false, 'Credential rejected')
|
||||
: new Msg<ProbeResult>(true, '', { status: 'online', latencyMs: 1 }),
|
||||
);
|
||||
const save = vi.fn(async (_payload: Partial<NodeRecord>) => new Msg(true));
|
||||
const fingerprint = vi.fn(
|
||||
async (_payload: Partial<NodeRecord>) => new Msg(true, '', 'fixture-pin'),
|
||||
);
|
||||
const inbounds = vi.fn(async (_payload: Partial<NodeRecord>) => new Msg(true, '', []));
|
||||
|
||||
function Page() {
|
||||
const [node, setNode] = useState<NodeRecord | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={() => {
|
||||
setNode(stored);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Edit primary
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setNode(other);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Edit secondary
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setNode(null);
|
||||
setOpen(true);
|
||||
}}
|
||||
>
|
||||
Add node
|
||||
</button>
|
||||
<NodeFormModal
|
||||
open={open}
|
||||
mode={node ? 'edit' : 'add'}
|
||||
node={node}
|
||||
testConnection={probe}
|
||||
fetchFingerprint={fingerprint}
|
||||
fetchInbounds={inbounds}
|
||||
save={save}
|
||||
onOpenChange={setOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const view = renderWithProviders(<Page />);
|
||||
return { ...view, probe, save, fingerprint, inbounds };
|
||||
}
|
||||
|
||||
function openForm(name: string) {
|
||||
fireEvent.click(screen.getByRole('button', { name }));
|
||||
return within(screen.getByRole('dialog'));
|
||||
}
|
||||
|
||||
it('keeps the stored token on first open even if a password input receives an unexpected value', async () => {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const { probe, save, unmount } = setup();
|
||||
const dialog = openForm('Edit primary');
|
||||
const unexpectedInput = dialog.queryByLabelText('API Token', apiTokenLabel);
|
||||
if (unexpectedInput) {
|
||||
fireEvent.change(unexpectedInput, { target: { value: unexpectedValue } });
|
||||
}
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
|
||||
await waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
|
||||
expect(probe.mock.calls[0]?.[0]).toMatchObject({ id: 11 });
|
||||
expect(probe.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save.mock.calls[0]?.[0]).toMatchObject({ id: 11 });
|
||||
expect(save.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it('ignores autofill in replacement mode, probes explicit edits, and clears them across opens', async () => {
|
||||
const { probe, save, fingerprint, inbounds } = setup();
|
||||
const dialog = openForm('Edit primary');
|
||||
fireEvent.click(dialog.getByRole('checkbox', { name: 'Replace API Token' }));
|
||||
const input = dialog.getByLabelText<HTMLInputElement>('API Token', apiTokenLabel);
|
||||
expect(input.value).toBe('');
|
||||
fireEvent.input(input, {
|
||||
target: { value: unexpectedValue },
|
||||
inputType: 'insertReplacementText',
|
||||
});
|
||||
expect(input.value).toBe('');
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
|
||||
await waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
|
||||
expect(probe.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
|
||||
|
||||
fireEvent.input(input, {
|
||||
target: { value: 'incorrect-fixture' },
|
||||
inputType: 'insertFromPaste',
|
||||
});
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Save' }));
|
||||
await dialog.findByText('Credential rejected');
|
||||
expect(probe.mock.calls[1]?.[0]).toMatchObject({ id: 11, apiToken: 'incorrect-fixture' });
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
const reopened = openForm('Edit primary');
|
||||
expect(reopened.queryByLabelText('API Token', apiTokenLabel)).toBeNull();
|
||||
expect(reopened.queryByText('Credential rejected')).toBeNull();
|
||||
fireEvent.click(reopened.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
const secondary = openForm('Edit secondary');
|
||||
fireEvent.click(secondary.getByRole('button', { name: 'Fetch' }));
|
||||
await waitFor(() => expect(fingerprint).toHaveBeenCalledTimes(1));
|
||||
expect(fingerprint.mock.calls[0]?.[0]).toMatchObject({ id: 22 });
|
||||
expect(fingerprint.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
|
||||
chooseSelectOption(secondary.getByLabelText('Inbound import').id, 'Selected inbounds');
|
||||
fireEvent.mouseDown(secondary.getByRole('combobox', { name: 'Inbounds' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Load inbounds from node' }));
|
||||
await waitFor(() => expect(inbounds).toHaveBeenCalledTimes(1));
|
||||
expect(inbounds.mock.calls[0]?.[0]).toMatchObject({ id: 22 });
|
||||
expect(inbounds.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
|
||||
});
|
||||
|
||||
it('updates the probe credential when undoing and redoing a replacement', async () => {
|
||||
const { probe } = setup();
|
||||
const dialog = openForm('Edit primary');
|
||||
fireEvent.click(dialog.getByRole('checkbox', { name: 'Replace API Token' }));
|
||||
const input = dialog.getByLabelText<HTMLInputElement>('API Token', apiTokenLabel);
|
||||
const replacement = 'replacement-fixture';
|
||||
fireEvent.input(input, { target: { value: replacement }, inputType: 'insertFromPaste' });
|
||||
fireEvent.input(input, { target: { value: '' }, inputType: 'historyUndo' });
|
||||
expect(input.value).toBe('');
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
|
||||
await waitFor(() => expect(probe).toHaveBeenCalledTimes(1));
|
||||
expect(probe.mock.calls[0]?.[0]).toMatchObject({ id: 11 });
|
||||
expect(probe.mock.calls[0]?.[0]).not.toHaveProperty('apiToken');
|
||||
|
||||
fireEvent.input(input, { target: { value: replacement }, inputType: 'historyRedo' });
|
||||
expect(input.value).toBe(replacement);
|
||||
fireEvent.click(dialog.getByRole('button', { name: 'Test Connection' }));
|
||||
await waitFor(() => expect(probe).toHaveBeenCalledTimes(2));
|
||||
expect(probe.mock.calls[1]?.[0]).toMatchObject({ id: 11, apiToken: replacement });
|
||||
});
|
||||
|
||||
it('requires an entered token for ordinary additions and allows mTLS additions without one', async () => {
|
||||
const { probe, save } = setup();
|
||||
const editing = openForm('Edit primary');
|
||||
fireEvent.click(editing.getByRole('checkbox', { name: 'Replace API Token' }));
|
||||
fireEvent.input(editing.getByLabelText('API Token', apiTokenLabel), {
|
||||
target: { value: 'explicit-fixture' },
|
||||
inputType: 'insertFromPaste',
|
||||
});
|
||||
fireEvent.click(editing.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(1));
|
||||
expect(save.mock.calls[0]?.[0]).toMatchObject({ id: 11, apiToken: 'explicit-fixture' });
|
||||
|
||||
const adding = openForm('Add node');
|
||||
const token = adding.getByLabelText<HTMLInputElement>('API Token', apiTokenLabel);
|
||||
expect(token.value).toBe('');
|
||||
fireEvent.change(adding.getByLabelText('Name'), { target: { value: 'New node' } });
|
||||
fireEvent.change(adding.getByLabelText('Address'), { target: { value: 'new.example.test' } });
|
||||
fireEvent.change(token, { target: { value: unexpectedValue } });
|
||||
fireEvent.click(adding.getByRole('button', { name: 'Save' }));
|
||||
await screen.findByText('Name, address, port and API token are required');
|
||||
expect(probe).toHaveBeenCalledTimes(1);
|
||||
chooseSelectOption(
|
||||
adding.getByLabelText('TLS verification').id,
|
||||
'Mutual TLS (client certificate)',
|
||||
);
|
||||
fireEvent.click(adding.getByRole('button', { name: 'Save' }));
|
||||
await waitFor(() => expect(save).toHaveBeenCalledTimes(2));
|
||||
expect(save.mock.calls[1]?.[0]).toMatchObject({ id: 0, tlsVerifyMode: 'mtls' });
|
||||
expect(save.mock.calls[1]?.[0]).not.toHaveProperty('apiToken');
|
||||
});
|
||||
@@ -18,11 +18,10 @@ const failing: NodeRecord = {
|
||||
lastError: 'dial tcp 10.0.0.2:2053: i/o timeout',
|
||||
};
|
||||
|
||||
function renderList(isMobile: boolean) {
|
||||
function renderList() {
|
||||
renderWithProviders(
|
||||
<NodeList
|
||||
nodes={[failing]}
|
||||
isMobile={isMobile}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
onAdd={noop}
|
||||
@@ -42,13 +41,13 @@ function renderList(isMobile: boolean) {
|
||||
// screen reader heard "exclamation-circle" and "switch" (s-ui#1293).
|
||||
describe('NodeList screen-reader names', () => {
|
||||
it('announces the node error from the status column', () => {
|
||||
renderList(false);
|
||||
renderList();
|
||||
|
||||
expect(screen.getByRole('img', { name: failing.lastError }).tagName).toBe('SPAN');
|
||||
});
|
||||
|
||||
it.each([false, true])('names the enable switch (mobile=%s)', (isMobile) => {
|
||||
renderList(isMobile);
|
||||
it('names the enable switch', () => {
|
||||
renderList();
|
||||
|
||||
expect(screen.getByRole('switch', { name: 'Enabled' }).getAttribute('aria-checked')).toBe(
|
||||
'true',
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { screen, within } from '@testing-library/react';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
@@ -9,10 +9,7 @@ import { renderWithProviders } from './test-utils';
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
function renderNode(
|
||||
counts: Pick<NodeRecord, 'onlineCount' | 'onlineTotalCount'>,
|
||||
isMobile = false,
|
||||
) {
|
||||
function renderNode(counts: Pick<NodeRecord, 'onlineCount' | 'onlineTotalCount'>) {
|
||||
const node: NodeRecord = {
|
||||
id: 1,
|
||||
name: 'edge',
|
||||
@@ -25,7 +22,6 @@ function renderNode(
|
||||
renderWithProviders(
|
||||
<NodeList
|
||||
nodes={[node]}
|
||||
isMobile={isMobile}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
onAdd={noop}
|
||||
@@ -67,14 +63,6 @@ describe('NodeList online total', () => {
|
||||
renderNode(counts);
|
||||
|
||||
expect(screen.getByText('7')).toBeTruthy();
|
||||
expect(screen.queryByText(/\d \/ \d/)).toBeNull();
|
||||
});
|
||||
|
||||
it('shows synced / total in the mobile stats dialog', async () => {
|
||||
renderNode({ onlineCount: 3, onlineTotalCount: 12 }, true);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: 'More Information' }));
|
||||
|
||||
expect(within(await screen.findByRole('dialog')).getByText('3 / 12 Online')).toBeTruthy();
|
||||
expect(screen.queryByText(/^\d+ \/ \d+$/)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -44,7 +44,6 @@ describe('NodeList re-render', () => {
|
||||
const noop = () => {};
|
||||
const props = {
|
||||
nodes,
|
||||
isMobile: false,
|
||||
latestVersion: '3.0.1',
|
||||
selectedIds: [] as number[],
|
||||
onSelectionChange: noop,
|
||||
|
||||
@@ -24,7 +24,6 @@ describe('NodeList desktop table row keys', () => {
|
||||
renderWithProviders(
|
||||
<NodeList
|
||||
nodes={sampleNodes()}
|
||||
isMobile={false}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
onAdd={noop}
|
||||
|
||||
@@ -21,7 +21,6 @@ function renderSubNode(fields: Partial<NodeRecord>) {
|
||||
renderWithProviders(
|
||||
<NodeList
|
||||
nodes={nodes}
|
||||
isMobile={false}
|
||||
selectedIds={[]}
|
||||
onSelectionChange={noop}
|
||||
onAdd={noop}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user