diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b659a53b..ce19f2ba1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2b4051a47..ee7269b7d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 diff --git a/DockerInit.sh b/DockerInit.sh index 52b363eef..3324a5ab0 100755 --- a/DockerInit.sh +++ b/DockerInit.sh @@ -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 ../../ diff --git a/README.ar_EG.md b/README.ar_EG.md index 5c0baa984..d12246fc2 100644 --- a/README.ar_EG.md +++ b/README.ar_EG.md @@ -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 محدثة تلقائيًا بناءً على بيانات النطاقات والعناوين المحظورة في روسيا._ ## أدوات المجتمع diff --git a/README.es_ES.md b/README.es_ES.md index 9701d2856..fae96ea9c 100644 --- a/README.es_ES.md +++ b/README.es_ES.md @@ -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 diff --git a/README.fa_IR.md b/README.fa_IR.md index e59fb0af5..a16b001bf 100644 --- a/README.fa_IR.md +++ b/README.fa_IR.md @@ -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 به‌روزرسانی شده خودکار بر اساس داده‌های دامنه‌ها و آدرس‌های مسدود شده در روسیه است._ ## ابزارهای جامعه diff --git a/README.md b/README.md index 43b47f079..15c3c069a 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/README.ru_RU.md b/README.ru_RU.md index fa6aa0979..0fa8967c1 100644 --- a/README.ru_RU.md +++ b/README.ru_RU.md @@ -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 на основе данных о заблокированных доменах и адресах в России._ ## Инструменты сообщества diff --git a/README.tr_TR.md b/README.tr_TR.md index 5daf90acd..52437f365 100644 --- a/README.tr_TR.md +++ b/README.tr_TR.md @@ -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ı diff --git a/README.zh_CN.md b/README.zh_CN.md index f03cb0d25..e1ee03c50 100644 --- a/README.zh_CN.md +++ b/README.zh_CN.md @@ -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 路由规则。_ ## 社区工具 diff --git a/database_cli.go b/database_cli.go new file mode 100644 index 000000000..7358ec4f5 --- /dev/null +++ b/database_cli.go @@ -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) + }) +} diff --git a/database_cli_test.go b/database_cli_test.go new file mode 100644 index 000000000..be139fcf1 --- /dev/null +++ b/database_cli_test.go @@ -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) + } +} diff --git a/docs/content/docs/en/operations/system-monitoring.mdx b/docs/content/docs/en/operations/system-monitoring.mdx index d80b2791f..83c0b2ac2 100644 --- a/docs/content/docs/en/operations/system-monitoring.mdx +++ b/docs/content/docs/en/operations/system-monitoring.mdx @@ -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. diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 725bcacf2..bd82d8b12 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -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} - + ); } \ No newline at end of file diff --git a/docs/content/docs/en/reference/api/inbounds.mdx b/docs/content/docs/en/reference/api/inbounds.mdx index 165dc5fd8..6d52c35bc 100644 --- a/docs/content/docs/en/reference/api/inbounds.mdx +++ b/docs/content/docs/en/reference/api/inbounds.mdx @@ -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} - + ); } \ No newline at end of file diff --git a/docs/content/docs/en/reference/api/nodes.mdx b/docs/content/docs/en/reference/api/nodes.mdx index fb6e627e3..afc8cc506 100644 --- a/docs/content/docs/en/reference/api/nodes.mdx +++ b/docs/content/docs/en/reference/api/nodes.mdx @@ -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} - + ); } \ No newline at end of file diff --git a/docs/content/docs/en/reference/database.mdx b/docs/content/docs/en/reference/database.mdx index 7471bb951..aaa15d18f 100644 --- a/docs/content/docs/en/reference/database.mdx +++ b/docs/content/docs/en/reference/database.mdx @@ -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. diff --git a/docs/content/docs/fa/operations/system-monitoring.mdx b/docs/content/docs/fa/operations/system-monitoring.mdx index 2082e9c59..2e3d46d0f 100644 --- a/docs/content/docs/fa/operations/system-monitoring.mdx +++ b/docs/content/docs/fa/operations/system-monitoring.mdx @@ -8,7 +8,7 @@ icon: ChartNoAxesCombined ## انتخاب بازهٔ نمودار -هر نمودار نمای کلی یک سلکت بازهٔ زمانی در گوشهٔ بالای سمت راست دارد. مقدار پیش‌فرض **2m** است. گزینه‌ها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. تغییر بازه در هر نمودار، بازهٔ همهٔ نمودارهای نمای کلی را تغییر می‌دهد. +از گزینهٔ **بازهٔ زمانی** کنار **شاخص‌های Xray** برای تغییر بازهٔ همهٔ نمودارهای نمای کلی استفاده کنید. گزینه‌ها **2m**، **5m**، **30m**، **1h**، **6h** و **12h** هستند. مقدار پیش‌فرض **2m** است. مرورگر انتخاب شما را برای این پنل پس از بارگیری مجدد صفحه و راه‌اندازی دوبارهٔ پنل حفظ می‌کند. تعداد نقطه‌های نمودار حداکثر ۶۰ نقطه است. بازه‌های کوتاه‌تر از نمونه‌های دقیق‌تر و بازه‌های بلندتر از میانگین نمونه‌ها استفاده می‌کنند. در بازهٔ **2m** نمودارها زنده‌اند: هر بار دریافت وضعیت، یعنی هر ۲ ثانیه، یک نقطه اضافه می‌کند. بازه‌های بلندتر از تاریخچهٔ ذخیره‌شده در سرور خوانده می‌شوند و به‌ازای هر نقطه یک بار، و حداکثر دقیقه‌ای یک بار، به‌روزرسانی می‌شوند. diff --git a/docs/public/openapi.json b/docs/public/openapi.json index fee39fb9a..2f5c4c0cd 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2130,6 +2130,10 @@ "$ref": "#/components/schemas/BulkAdjustReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2255,6 +2259,10 @@ "$ref": "#/components/schemas/BulkDeleteReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2611,6 +2619,24 @@ ], "type": "object" }, + "ClientEmailSuggestions": { + "properties": { + "emails": { + "example": [ + "alice@example.com", + "bob@example.com" + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "emails" + ], + "type": "object" + }, "ClientInbound": { "properties": { "clientId": { @@ -3406,6 +3432,124 @@ ], "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": { @@ -3606,6 +3750,104 @@ ], "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": { @@ -4298,6 +4540,31 @@ ], "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": { @@ -4755,6 +5022,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4916,6 +5191,43 @@ ], "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": { @@ -4938,6 +5250,40 @@ ], "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": { @@ -5028,6 +5374,33 @@ ], "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": { @@ -5071,6 +5444,106 @@ ], "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": { @@ -5302,6 +5775,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -5867,6 +6348,43 @@ ], "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": { @@ -6168,6 +6686,12 @@ "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" @@ -7153,6 +7677,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "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.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ @@ -7345,6 +7918,104 @@ } } }, + "/panel/api/inbounds/{id}/info": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "Load inbound information and the first compatible client or a page of up to 50 tunnel peers.", + "operationId": "get_panel_api_inbounds_id_info", + "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.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Inbound ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/InboundInfoPage" + } + } + }, + "example": { + "success": true, + "obj": { + "inbound": null, + "peerOffset": 50, + "totalPeers": 120 + } + } + } + } + } + } + } + }, + "/panel/api/inbounds/{id}/peerExport": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "Stream the source pages for a WireGuard or AmneziaWG peer export.", + "operationId": "get_panel_api_inbounds_id_peerExport", + "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.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Inbound ID.", + "schema": { + "type": "integer" + } + } + ], + "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." + } + } + } + }, "/panel/api/inbounds/add": { "post": { "tags": [ @@ -8184,6 +8855,7 @@ "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, @@ -10338,6 +11010,58 @@ } } }, + "/panel/api/clients/userSuggestions": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Return up to 50 client emails for the routing rule user picker.", + "operationId": "get_panel_api_clients_userSuggestions", + "parameters": [ + { + "name": "search", + "in": "query", + "required": false, + "description": "Optional case-insensitive substring. Percent and underscore are literal.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/ClientEmailSuggestions" + } + } + }, + "example": { + "success": true, + "obj": { + "emails": [ + "alice@example.com", + "bob@example.com" + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/list/paged": { "get": { "tags": [ @@ -12270,15 +12994,24 @@ ], "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.", "operationId": "post_panel_api_clients_bulkAdjust", - "description": "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.", + "description": "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. 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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "emails" + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group" + ] + } ], "properties": { "emails": { @@ -12288,6 +13021,13 @@ }, "minItems": 1 }, + "group": { + "type": "string", + "minLength": 1 + }, + "scopeToken": { + "type": "string" + }, "addDays": { "type": "integer" }, @@ -12370,7 +13110,8 @@ "status": "pending" } ], - "skipped": [] + "skipped": [], + "skippedCount": 0 } } } @@ -12522,15 +13263,45 @@ "tags": [ "Clients" ], - "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.", + "summary": "Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters.", "operationId": "post_panel_api_clients_bulkDel", - "description": "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.", + "description": "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. 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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "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" + } + } }, "example": { "emails": [ @@ -12578,7 +13349,8 @@ "email": "", "reason": "" } - ] + ], + "skippedCount": 0 } } } @@ -12592,7 +13364,7 @@ "tags": [ "Clients" ], - "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.", + "summary": "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.", "operationId": "post_panel_api_clients_bulkCreate", "description": "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.", "requestBody": { @@ -12600,33 +13372,76 @@ "content": { "application/json": { "schema": { - "type": "object" + "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." + } + } + } }, "example": [ { "client": { "email": "alice@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 2, - "enable": true + "limitHwid": 2 }, "inboundIds": [ 7 - ] + ], + "subIdPrefix": "team" }, { "client": { "email": "bob@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 0, - "enable": true + "limitHwid": 0 }, "inboundIds": [ 7, 9 - ] + ], + "subIdPrefix": "team" } ] } @@ -12682,21 +13497,58 @@ "tags": [ "Clients" ], - "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.", + "summary": "Move clients into a group and update every owning inbound's settings in the same transaction.", "operationId": "post_panel_api_clients_groups_bulkAdd", + "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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "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" + } + } }, "example": { - "emails": [ - "alice", - "bob" - ], - "group": "customer-a" + "group": "customer-a", + "inboundId": 7 } } } @@ -12735,14 +13587,43 @@ "tags": [ "Clients" ], - "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.", + "summary": "Clear group membership and preserve the clients. Use either emails or a selection scoped to the named group.", "operationId": "post_panel_api_clients_groups_bulkRemove", + "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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "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" + } + } }, "example": { "emails": [ @@ -12932,12 +13813,150 @@ } } }, + "/panel/api/clients/detachCandidates": { + "get": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "get_panel_api_clients_detachCandidates", + "parameters": [ + { + "name": "inboundId", + "in": "query", + "required": true, + "description": "Source inbound ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "1-indexed page, defaults to 1.", + "schema": { + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Email or comment substring.", + "schema": { + "type": "string" + } + }, + { + "name": "scopeToken", + "in": "query", + "required": false, + "description": "Token from the freeze endpoint.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachCandidatePage" + } + } + }, + "example": { + "success": true, + "obj": { + "attached": 0, + "items": [ + { + "comment": "", + "email": "", + "enable": false, + "id": 0, + "inScope": false + } + ], + "total": 0 + } + } + } + } + } + } + } + }, + "/panel/api/clients/detachCandidates/freeze": { + "post": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "post_panel_api_clients_detachCandidates_freeze", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "inboundId": 7 + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachScopeSummary" + } + } + }, + "example": { + "success": true, + "obj": { + "scopeToken": "", + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkDetach": { "post": { "tags": [ "Clients" ], - "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.", + "summary": "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.", "operationId": "post_panel_api_clients_bulkDetach", "description": "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.", "requestBody": { @@ -12952,7 +13971,15 @@ "items": { "type": "string" }, - "description": "Emails of existing clients to detach." + "description": "Emails of existing clients to detach. Use either emails or selection." + }, + "selection": { + "type": "object", + "description": "Explicit IDs or a frozen scope with exclusions." + }, + "requestId": { + "type": "string", + "description": "UUID required for scoped requests. Retries are idempotent while job history is retained." }, "inboundIds": { "type": "array", @@ -12963,7 +13990,6 @@ } }, "required": [ - "emails", "inboundIds" ] }, @@ -13027,6 +14053,59 @@ } } }, + "/panel/api/clients/bulkDetach/{id}": { + "get": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "get_panel_api_clients_bulkDetach_id", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Job ID returned by bulkDetach.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachJobStatus" + } + } + }, + "example": { + "success": true, + "obj": { + "error": "", + "processed": 0, + "result": null, + "running": false, + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkResetTraffic": { "post": { "tags": [ @@ -13192,6 +14271,164 @@ } } }, + "/panel/api/clients/groups/clientPage": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Page through group candidates, members or subscription IDs. Pages are one-based with a fixed size of 100 and an exact total.", + "operationId": "get_panel_api_clients_groups_clientPage", + "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.", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + }, + { + "name": "mode", + "in": "query", + "required": true, + "description": "", + "schema": { + "type": "string", + "enum": [ + "add", + "remove", + "links" + ] + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer", + "default": 1 + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "freeze", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "boolean" + } + }, + { + "name": "scopeSearch", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "maxId", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/GroupClientPage" + } + } + }, + "example": { + "success": true, + "obj": { + "items": [ + { + "comment": "Example client", + "email": "alice", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true, + "subId": "example-sub-id" + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + } + } + } + } + } + } + } + }, + "/panel/api/clients/groups/subLinks/export": { + "get": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "get_panel_api_clients_groups_subLinks_export", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Complete subscription link export.", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Missing group or subscriptions disabled." + } + } + } + }, "/panel/api/clients/groups/{name}/emails": { "get": { "tags": [ @@ -13886,7 +15123,7 @@ "tags": [ "Clients" ], - "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.", + "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. An empty list means the node reported no online clients. An absent GUID means there is no usable report.", "operationId": "post_panel_api_clients_onlinesByGuid", "responses": { "200": { @@ -13971,7 +15208,7 @@ "tags": [ "Clients" ], - "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.", + "summary": "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.", "operationId": "post_panel_api_clients_activeInbounds", "responses": { "200": { @@ -14404,6 +15641,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14423,6 +15661,69 @@ } } }, + "/panel/api/nodes/overview": { + "get": { + "tags": [ + "Nodes" + ], + "summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.", + "operationId": "get_panel_api_nodes_overview", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeOverview" + } + } + }, + "example": { + "success": true, + "obj": { + "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 + ] + } + } + } + } + } + } + } + }, "/panel/api/nodes/mtls/ca": { "post": { "tags": [ @@ -14610,6 +15911,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14765,6 +16067,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -20262,8 +21565,10 @@ "type": "array", "items": { "type": "string" - } - } + }, + "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": { "type": "object", @@ -20566,6 +21871,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 7115dcb48..98b7f27d4 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -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", diff --git a/frontend/package.json b/frontend/package.json index 43ba4ce0b..563197a70 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -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", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index fee39fb9a..2f5c4c0cd 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2130,6 +2130,10 @@ "$ref": "#/components/schemas/BulkAdjustReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2255,6 +2259,10 @@ "$ref": "#/components/schemas/BulkDeleteReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2611,6 +2619,24 @@ ], "type": "object" }, + "ClientEmailSuggestions": { + "properties": { + "emails": { + "example": [ + "alice@example.com", + "bob@example.com" + ], + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "emails" + ], + "type": "object" + }, "ClientInbound": { "properties": { "clientId": { @@ -3406,6 +3432,124 @@ ], "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": { @@ -3606,6 +3750,104 @@ ], "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": { @@ -4298,6 +4540,31 @@ ], "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": { @@ -4755,6 +5022,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4916,6 +5191,43 @@ ], "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": { @@ -4938,6 +5250,40 @@ ], "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": { @@ -5028,6 +5374,33 @@ ], "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": { @@ -5071,6 +5444,106 @@ ], "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": { @@ -5302,6 +5775,14 @@ "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "example": "verify", "type": "string" @@ -5867,6 +6348,43 @@ ], "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": { @@ -6168,6 +6686,12 @@ "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" @@ -7153,6 +7677,55 @@ } } }, + "/panel/api/inbounds/catalog": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "List inbound metadata for the authenticated user. Returns id, tag, remark, listen, protocol, and port for remote ID lookup and reconciliation.", + "operationId": "get_panel_api_inbounds_catalog", + "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.", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "type": "array", + "items": { + "$ref": "#/components/schemas/RemoteInboundOption" + } + } + } + }, + "example": { + "success": true, + "obj": [ + { + "id": 7, + "listen": "127.0.0.1", + "port": 443, + "protocol": "vless", + "remark": "VLESS-443", + "tag": "in-443" + } + ] + } + } + } + } + } + } + }, "/panel/api/inbounds/options": { "get": { "tags": [ @@ -7345,6 +7918,104 @@ } } }, + "/panel/api/inbounds/{id}/info": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "Load inbound information and the first compatible client or a page of up to 50 tunnel peers.", + "operationId": "get_panel_api_inbounds_id_info", + "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.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Inbound ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer", + "default": 1 + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/InboundInfoPage" + } + } + }, + "example": { + "success": true, + "obj": { + "inbound": null, + "peerOffset": 50, + "totalPeers": 120 + } + } + } + } + } + } + } + }, + "/panel/api/inbounds/{id}/peerExport": { + "get": { + "tags": [ + "Inbounds" + ], + "summary": "Stream the source pages for a WireGuard or AmneziaWG peer export.", + "operationId": "get_panel_api_inbounds_id_peerExport", + "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.", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Inbound ID.", + "schema": { + "type": "integer" + } + } + ], + "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." + } + } + } + }, "/panel/api/inbounds/add": { "post": { "tags": [ @@ -8184,6 +8855,7 @@ "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, @@ -10338,6 +11010,58 @@ } } }, + "/panel/api/clients/userSuggestions": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Return up to 50 client emails for the routing rule user picker.", + "operationId": "get_panel_api_clients_userSuggestions", + "parameters": [ + { + "name": "search", + "in": "query", + "required": false, + "description": "Optional case-insensitive substring. Percent and underscore are literal.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/ClientEmailSuggestions" + } + } + }, + "example": { + "success": true, + "obj": { + "emails": [ + "alice@example.com", + "bob@example.com" + ] + } + } + } + } + } + } + } + }, "/panel/api/clients/list/paged": { "get": { "tags": [ @@ -12270,15 +12994,24 @@ ], "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.", "operationId": "post_panel_api_clients_bulkAdjust", - "description": "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.", + "description": "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. 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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", - "required": [ - "emails" + "oneOf": [ + { + "required": [ + "emails" + ] + }, + { + "required": [ + "group" + ] + } ], "properties": { "emails": { @@ -12288,6 +13021,13 @@ }, "minItems": 1 }, + "group": { + "type": "string", + "minLength": 1 + }, + "scopeToken": { + "type": "string" + }, "addDays": { "type": "integer" }, @@ -12370,7 +13110,8 @@ "status": "pending" } ], - "skipped": [] + "skipped": [], + "skippedCount": 0 } } } @@ -12522,15 +13263,45 @@ "tags": [ "Clients" ], - "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.", + "summary": "Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters.", "operationId": "post_panel_api_clients_bulkDel", - "description": "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.", + "description": "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. 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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "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" + } + } }, "example": { "emails": [ @@ -12578,7 +13349,8 @@ "email": "", "reason": "" } - ] + ], + "skippedCount": 0 } } } @@ -12592,7 +13364,7 @@ "tags": [ "Clients" ], - "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.", + "summary": "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.", "operationId": "post_panel_api_clients_bulkCreate", "description": "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.", "requestBody": { @@ -12600,33 +13372,76 @@ "content": { "application/json": { "schema": { - "type": "object" + "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." + } + } + } }, "example": [ { "client": { "email": "alice@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 2, - "enable": true + "limitHwid": 2 }, "inboundIds": [ 7 - ] + ], + "subIdPrefix": "team" }, { "client": { "email": "bob@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 0, - "enable": true + "limitHwid": 0 }, "inboundIds": [ 7, 9 - ] + ], + "subIdPrefix": "team" } ] } @@ -12682,21 +13497,58 @@ "tags": [ "Clients" ], - "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.", + "summary": "Move clients into a group and update every owning inbound's settings in the same transaction.", "operationId": "post_panel_api_clients_groups_bulkAdd", + "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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "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" + } + } }, "example": { - "emails": [ - "alice", - "bob" - ], - "group": "customer-a" + "group": "customer-a", + "inboundId": 7 } } } @@ -12735,14 +13587,43 @@ "tags": [ "Clients" ], - "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.", + "summary": "Clear group membership and preserve the clients. Use either emails or a selection scoped to the named group.", "operationId": "post_panel_api_clients_groups_bulkRemove", + "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.", "requestBody": { "required": true, "content": { "application/json": { "schema": { - "type": "object" + "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" + } + } }, "example": { "emails": [ @@ -12932,12 +13813,150 @@ } } }, + "/panel/api/clients/detachCandidates": { + "get": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "get_panel_api_clients_detachCandidates", + "parameters": [ + { + "name": "inboundId", + "in": "query", + "required": true, + "description": "Source inbound ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "1-indexed page, defaults to 1.", + "schema": { + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Email or comment substring.", + "schema": { + "type": "string" + } + }, + { + "name": "scopeToken", + "in": "query", + "required": false, + "description": "Token from the freeze endpoint.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachCandidatePage" + } + } + }, + "example": { + "success": true, + "obj": { + "attached": 0, + "items": [ + { + "comment": "", + "email": "", + "enable": false, + "id": 0, + "inScope": false + } + ], + "total": 0 + } + } + } + } + } + } + } + }, + "/panel/api/clients/detachCandidates/freeze": { + "post": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "post_panel_api_clients_detachCandidates_freeze", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "inboundId": 7 + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachScopeSummary" + } + } + }, + "example": { + "success": true, + "obj": { + "scopeToken": "", + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkDetach": { "post": { "tags": [ "Clients" ], - "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.", + "summary": "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.", "operationId": "post_panel_api_clients_bulkDetach", "description": "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.", "requestBody": { @@ -12952,7 +13971,15 @@ "items": { "type": "string" }, - "description": "Emails of existing clients to detach." + "description": "Emails of existing clients to detach. Use either emails or selection." + }, + "selection": { + "type": "object", + "description": "Explicit IDs or a frozen scope with exclusions." + }, + "requestId": { + "type": "string", + "description": "UUID required for scoped requests. Retries are idempotent while job history is retained." }, "inboundIds": { "type": "array", @@ -12963,7 +13990,6 @@ } }, "required": [ - "emails", "inboundIds" ] }, @@ -13027,6 +14053,59 @@ } } }, + "/panel/api/clients/bulkDetach/{id}": { + "get": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "get_panel_api_clients_bulkDetach_id", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Job ID returned by bulkDetach.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachJobStatus" + } + } + }, + "example": { + "success": true, + "obj": { + "error": "", + "processed": 0, + "result": null, + "running": false, + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkResetTraffic": { "post": { "tags": [ @@ -13192,6 +14271,164 @@ } } }, + "/panel/api/clients/groups/clientPage": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Page through group candidates, members or subscription IDs. Pages are one-based with a fixed size of 100 and an exact total.", + "operationId": "get_panel_api_clients_groups_clientPage", + "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.", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + }, + { + "name": "mode", + "in": "query", + "required": true, + "description": "", + "schema": { + "type": "string", + "enum": [ + "add", + "remove", + "links" + ] + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer", + "default": 1 + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "freeze", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "boolean" + } + }, + { + "name": "scopeSearch", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "string" + } + }, + { + "name": "maxId", + "in": "query", + "required": false, + "description": "", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/GroupClientPage" + } + } + }, + "example": { + "success": true, + "obj": { + "items": [ + { + "comment": "Example client", + "email": "alice", + "enable": true, + "group": "staff", + "id": 1, + "inScope": true, + "subId": "example-sub-id" + } + ], + "maxId": 0, + "scopeToken": "", + "total": 120 + } + } + } + } + } + } + } + }, + "/panel/api/clients/groups/subLinks/export": { + "get": { + "tags": [ + "Clients" + ], + "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.", + "operationId": "get_panel_api_clients_groups_subLinks_export", + "parameters": [ + { + "name": "group", + "in": "query", + "required": true, + "description": "Group name.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Complete subscription link export.", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + }, + "400": { + "description": "Missing group or subscriptions disabled." + } + } + } + }, "/panel/api/clients/groups/{name}/emails": { "get": { "tags": [ @@ -13886,7 +15123,7 @@ "tags": [ "Clients" ], - "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.", + "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. An empty list means the node reported no online clients. An absent GUID means there is no usable report.", "operationId": "post_panel_api_clients_onlinesByGuid", "responses": { "200": { @@ -13971,7 +15208,7 @@ "tags": [ "Clients" ], - "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.", + "summary": "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.", "operationId": "post_panel_api_clients_activeInbounds", "responses": { "200": { @@ -14404,6 +15641,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14423,6 +15661,69 @@ } } }, + "/panel/api/nodes/overview": { + "get": { + "tags": [ + "Nodes" + ], + "summary": "Read the local panel, unique fleet client counts and sampled remote host telemetry.", + "operationId": "get_panel_api_nodes_overview", + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/NodeOverview" + } + } + }, + "example": { + "success": true, + "obj": { + "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 + ] + } + } + } + } + } + } + } + }, "/panel/api/nodes/mtls/ca": { "post": { "tags": [ @@ -14610,6 +15911,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -14765,6 +16067,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -20262,8 +21565,10 @@ "type": "array", "items": { "type": "string" - } - } + }, + "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": { "type": "object", @@ -20566,6 +21871,7 @@ "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ diff --git a/frontend/src/api/groupClients.ts b/frontend/src/api/groupClients.ts new file mode 100644 index 000000000..487c5a213 --- /dev/null +++ b/frontend/src/api/groupClients.ts @@ -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(), + ); +} diff --git a/frontend/src/api/inboundInfo.ts b/frontend/src/api/inboundInfo.ts new file mode 100644 index 000000000..6eb41cd6c --- /dev/null +++ b/frontend/src/api/inboundInfo.ts @@ -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`); +} diff --git a/frontend/src/api/queries/useClientOptions.ts b/frontend/src/api/queries/useClientOptions.ts index 26968a724..861d9f2d3 100644 --- a/frontend/src/api/queries/useClientOptions.ts +++ b/frontend/src/api/queries/useClientOptions.ts @@ -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 { - 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((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 { + 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, }); } diff --git a/frontend/src/api/queries/useNodesQuery.ts b/frontend/src/api/queries/useNodesQuery.ts index 23d5db507..7273fb719 100644 --- a/frontend/src/api/queries/useNodesQuery.ts +++ b/frontend/src/api/queries/useNodesQuery.ts @@ -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; diff --git a/frontend/src/api/queryKeys.ts b/frontend/src/api/queryKeys.ts index c03d796ad..be9441760 100644 --- a/frontend/src/api/queryKeys.ts +++ b/frontend/src/api/queryKeys.ts @@ -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, diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 310051ae7..c8ca0d3d9 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -517,7 +517,8 @@ export const EXAMPLES: Record = { "status": "pending" } ], - "skipped": [] + "skipped": [], + "skippedCount": 0 }, "BulkAttachResult": { "attached": [ @@ -578,7 +579,8 @@ export const EXAMPLES: Record = { "email": "", "reason": "" } - ] + ], + "skippedCount": 0 }, "BulkDetachResult": { "detached": [ @@ -688,6 +690,12 @@ export const EXAMPLES: Record = { "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 = { "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 = { "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 = { "sortOrder": 0, "xver": 0 }, + "InboundInfoPage": { + "inbound": null, + "peerOffset": 50, + "totalPeers": 120 + }, "InboundOption": { "awgServer": null, "enable": true, @@ -1297,6 +1383,7 @@ export const EXAMPLES: Record = { "remark": "", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -1324,11 +1411,34 @@ export const EXAMPLES: Record = { "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 = { "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 = { 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 = { "remark": "Primary edge", "scheme": "https", "status": "online", + "telemetry": null, "tlsVerifyMode": "verify", "transitive": false, "unavailableMetrics": [ @@ -1567,6 +1725,14 @@ export const EXAMPLES: Record = { ], "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 = { "panelVersion": "", "publicIP": null, "resourceScope": "", + "sampleAgeMillis": 125, "swap": null, "tcpCount": 0, "udpCount": 0, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index 542b3178d..ebc2d304c 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2104,6 +2104,10 @@ export const SCHEMAS: Record = { "$ref": "#/components/schemas/BulkAdjustReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2229,6 +2233,10 @@ export const SCHEMAS: Record = { "$ref": "#/components/schemas/BulkDeleteReport" }, "type": "array" + }, + "skippedCount": { + "example": 0, + "type": "integer" } }, "required": [ @@ -2585,6 +2593,24 @@ export const SCHEMAS: Record = { ], "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 = { ], "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 = { ], "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 = { ], "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 = { "example": "online", "type": "string" }, + "telemetry": { + "allOf": [ + { + "$ref": "#/components/schemas/NodeTelemetry" + } + ], + "nullable": true + }, "tlsVerifyMode": { "enum": [ "verify", @@ -4890,6 +5165,43 @@ export const SCHEMAS: Record = { ], "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 = { ], "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 = { ], "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 = { ], "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 = { "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 = { ], "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 = { "resourceScope": { "type": "string" }, + "sampleAgeMillis": { + "example": 125, + "format": "int64", + "nullable": true, + "type": "integer" + }, "swap": {}, "tcpCount": { "type": "integer" diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 62b462e76..0a49bf41c 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -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; 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; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index f0a263118..9078e9286 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -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; @@ -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; @@ -645,6 +647,11 @@ export const ClientChangeLogSchema = z.object({ }); export type ClientChangeLog = z.infer; +export const ClientEmailSuggestionsSchema = z.object({ + emails: z.array(z.string()), +}); +export type ClientEmailSuggestions = z.infer; + 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; +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; + +export const DetachCandidatePageSchema = z.object({ + attached: z.number().int(), + items: z.array(z.lazy(() => DetachCandidateSchema)), + total: z.number().int(), +}); +export type DetachCandidatePage = z.infer; + +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; + +export const DetachScopeSummarySchema = z.object({ + scopeToken: z.string(), + total: z.number().int(), +}); +export type DetachScopeSummary = z.infer; + +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; + 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; +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; + +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; + +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; + export const HappLinkResultSchema = z.object({ encryptedLink: z.string(), }); @@ -1042,6 +1116,13 @@ export const InboundFallbackSchema = z.object({ }); export type InboundFallback = z.infer; +export const InboundInfoPageSchema = z.object({ + inbound: z.lazy(() => InboundSchema).nullable().optional(), + peerOffset: z.number().int(), + totalPeers: z.number().int(), +}); +export type InboundInfoPage = z.infer; + 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; +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; + 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; +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; + 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; +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; + 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; +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; + 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; +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; + 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(), diff --git a/frontend/src/hooks/useClients.ts b/frontend/src/hooks/useClients.ts index 364035edb..cabd40a1a 100644 --- a/frontend/src/hooks/useClients.ts +++ b/frontend/src/hooks/useClients.ts @@ -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> => { + mutationFn: async ( + payload: ({ emails: string[] } | GroupBulkScope) & { keepTraffic?: boolean }, + ): Promise> => { 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> => { + mutationFn: async ( + payload: ({ emails: string[] } | GroupBulkScope) & { + addDays: number; + addBytes: number; + flow?: string; + limitHwid?: number | null; + adTag?: string; + externalLinks?: ExternalLinkInput[]; + }, + ): Promise> => { 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); - 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], ); diff --git a/frontend/src/lib/xray/inbound-link.ts b/frontend/src/lib/xray/inbound-link.ts index c16688b7b..67a096e98 100644 --- a/frontend/src/lib/xray/inbound-link.ts +++ b/frontend/src/lib/xray/inbound-link.ts @@ -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://@: // ?publickey=&address=&mtu=# // 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, }), ), ); diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8e41e0bf9..973fe5c5a 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -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', diff --git a/frontend/src/pages/api-docs/websocket-events.ts b/frontend/src/pages/api-docs/websocket-events.ts index 98ce384f8..681e4f938 100644 --- a/frontend/src/pages/api-docs/websocket-events.ts +++ b/frontend/src/pages/api-docs/websocket-events.ts @@ -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: [ diff --git a/frontend/src/pages/clients/ClientBulkAddModal.tsx b/frontend/src/pages/clients/ClientBulkAddModal.tsx index 79aef46a6..2c6df7ec7 100644 --- a/frontend/src/pages/clients/ClientBulkAddModal.tsx +++ b/frontend/src/pages/clients/ClientBulkAddModal.tsx @@ -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( diff --git a/frontend/src/pages/clients/ClientBulkAdjustModal.tsx b/frontend/src/pages/clients/ClientBulkAdjustModal.tsx index 43028383d..5850b104e 100644 --- a/frontend/src/pages/clients/ClientBulkAdjustModal.tsx +++ b/frontend/src/pages/clients/ClientBulkAdjustModal.tsx @@ -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, diff --git a/frontend/src/pages/clients/SubLinksModal.tsx b/frontend/src/pages/clients/SubLinksModal.tsx index 83b8064db..249cb7870 100644 --- a/frontend/src/pages/clients/SubLinksModal.tsx +++ b/frontend/src/pages/clients/SubLinksModal.tsx @@ -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(() => { 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} @@ -158,18 +206,19 @@ export default function SubLinksModal({
@@ -187,7 +236,7 @@ export default function SubLinksModal({ style={{ marginBottom: 12 }} /> )} - {enabled && rows.length === 0 && ( + {enabled && !total && !groupPage.isFetching && !groupPage.isError && ( )} - {rows.length > 0 && ( + {groupPage.isError && ( + + )} + {enabled && (total > 0 || groupPage.isFetching) && ( 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 }} /> )} diff --git a/frontend/src/pages/groups/GroupAddClientsModal.tsx b/frontend/src/pages/groups/GroupAddClientsModal.tsx deleted file mode 100644 index 5655cd38a..000000000 --- a/frontend/src/pages/groups/GroupAddClientsModal.tsx +++ /dev/null @@ -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([]); - const [search, setSearch] = useState(''); - - const rows = useMemo( - () => - (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 = 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 ? ( - {g} - ) : ( - — - ), - }, - { - title: t('enable'), - dataIndex: 'enable', - key: 'enable', - width: 90, - render: (enabled: boolean) => - enabled ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [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 ( - - {messageContextHolder} - - {t('pages.groups.addToGroupDesc')} - - - - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} - /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: rows.length, - })} - - - {rows.length === 0 ? ( - - ) : ( - - size="small" - rowKey="email" - columns={columns} - dataSource={filteredRows} - pagination={false} - scroll={{ y: 320 }} - rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - preserveSelectedRowKeys: true, - }} - /> - )} - - - ); -} diff --git a/frontend/src/pages/groups/GroupClientsModal.tsx b/frontend/src/pages/groups/GroupClientsModal.tsx new file mode 100644 index 000000000..3fcf59aa4 --- /dev/null +++ b/frontend/src/pages/groups/GroupClientsModal.tsx @@ -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()); + 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 = [ + { 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 ? {label} : '—'), + }, + ] + : []), + { + title: t('enable'), + dataIndex: 'enable', + width: 100, + render: (enabled: boolean) => ( + + {t(enabled ? 'enable' : 'pages.inbounds.attachClientsStatusDisabled')} + + ), + }, + ]; + + return ( + { + 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} + + {t(add ? 'pages.groups.addToGroupDesc' : 'pages.groups.removeFromGroupDesc')} + + + { + setSearch(event.target.value); + setPage(1); + }} + maxLength={256} + placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} + aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')} + style={{ maxWidth: 320 }} + /> + + + + + {frozen && choices.size > 0 && ( + + )} + + {t('pages.inbounds.attachClientsSelectedCount', { + selected, + total: frozen?.count ?? query.data?.total ?? 0, + })} + + + {query.isError && ( + + )} + {!loading && !query.isError && !search && query.data?.total === 0 && ( + + )} + + 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), + }), + }} + /> + + + ); +} diff --git a/frontend/src/pages/groups/GroupRemoveClientsModal.tsx b/frontend/src/pages/groups/GroupRemoveClientsModal.tsx deleted file mode 100644 index c462c8a49..000000000 --- a/frontend/src/pages/groups/GroupRemoveClientsModal.tsx +++ /dev/null @@ -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([]); - const [search, setSearch] = useState(''); - - const rows = useMemo( - () => - (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 = 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 ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [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 ( - - {messageContextHolder} - - {t('pages.groups.removeFromGroupDesc')} - - - - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - aria-label={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} - /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: rows.length, - })} - - - - size="small" - rowKey="email" - columns={columns} - dataSource={filteredRows} - pagination={false} - scroll={{ y: 280 }} - rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - preserveSelectedRowKeys: true, - }} - /> - - - ); -} diff --git a/frontend/src/pages/groups/GroupsPage.stories.tsx b/frontend/src/pages/groups/GroupsPage.stories.tsx new file mode 100644 index 000000000..4aad951a6 --- /dev/null +++ b/frontend/src/pages/groups/GroupsPage.stories.tsx @@ -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 }[] = []; +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 ( + + + + + + setInboundOpen(false)} + /> + + + + ); +} + +function response(obj: unknown) { + return Promise.resolve(Response.json({ success: true, msg: '', obj })); +} + +const meta = { + title: 'Pages/Groups/Client management', + component: GroupsPage, + render: () => , +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +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) + : 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, 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' }); + }, +}; diff --git a/frontend/src/pages/groups/GroupsPage.tsx b/frontend/src/pages/groups/GroupsPage.tsx index 407785f70..eba2eb841 100644 --- a/frontend/src/pages/groups/GroupsPage.tsx +++ b/frontend/src/pages/groups/GroupsPage.tsx @@ -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 { return validated.obj ?? []; } -async function fetchEmailsForGroup(name: string): Promise { - const msg = await HttpUtil.get( - `/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([]); + const [adjustScope, setAdjustScope] = useState<(GroupBulkScope & { count: number }) | null>(null); + const scopeRequest = useRef(0); const [groupForAction, setGroupForAction] = useState(null); - const allClientsQuery = useQuery({ - 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() { /> - - - + {subLinksOpen && groupForAction && ( + + + + )} - - { - 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 && ( + + { + const { group, scopeToken } = adjustScope; + const msg = await bulkAdjust( + { group, scopeToken }, + addDays, + addBytes, + flow, + limitHwid, + adTag, + externalLinks, ); - return obj; - } - return null; - }} - /> - + if (!msg?.success || !msg.obj) return null; + messageApi.success( + t('pages.groups.adjustSuccess', { count: msg.obj.adjusted, name: group }), + ); + return msg.obj; + }} + /> + + )} - - 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; - }} - /> - - - - 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; - }} - /> - + {(addClientsOpen || removeClientsOpen) && groupForAction && ( + + { + 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; + }} + /> + + )} ); diff --git a/frontend/src/pages/hosts/HostAddressSelect.css b/frontend/src/pages/hosts/HostAddressSelect.css new file mode 100644 index 000000000..e6f29a6d3 --- /dev/null +++ b/frontend/src/pages/hosts/HostAddressSelect.css @@ -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%; +} diff --git a/frontend/src/pages/hosts/HostAddressSelect.tsx b/frontend/src/pages/hosts/HostAddressSelect.tsx new file mode 100644 index 000000000..823dd5b9f --- /dev/null +++ b/frontend/src/pages/hosts/HostAddressSelect.tsx @@ -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>, + '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()); + const focusAfterEdit = useRef(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) { + 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) { + 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 ( +
+ {messageContext} + + {...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 ? ( + setEditing({ address, draft: event.target.value })} + onKeyDown={editKeyDown} + onMouseDown={(event) => event.stopPropagation()} + onBlur={() => commitEdit(false)} + /> + ) : ( + + + + + ), + }); + }} + /> +
+ ); +} diff --git a/frontend/src/pages/hosts/HostFormModal.tsx b/frontend/src/pages/hosts/HostFormModal.tsx index d2237dbb1..193bd8f57 100644 --- a/frontend/src/pages/hosts/HostFormModal.tsx +++ b/frontend/src/pages/hosts/HostFormModal.tsx @@ -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 & { @@ -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 ; +} + +function HostFormSession({ open, mode, host, @@ -111,9 +121,18 @@ export default function HostFormModal({ }: HostFormModalProps) { const { t } = useTranslation(); const { isMobile } = useMediaQuery(); - const methods = useForm({ defaultValues: defaultsFor(host) }); + const methods = useForm({ 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({ { + 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) }} > - setInput(event.target.value)} /> + +

+ {clientCount[30] + ? 'Rollups ready' + : dbInbounds.length + ? 'Calculating rollups' + : 'Waiting for inbounds'} +

+ +
Last inbound online: {clientCount[30]?.online.length ?? '…'}
+
First inbound online: {clientCount[1]?.online.length ?? '…'}
+ + ); +} + +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 ( + + + + + ); +} + +export const LargeDeployment: StoryObj = { + render: () => , + 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), + }); + }, +}; diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx index 7ffaf5de0..568a59c5b 100644 --- a/frontend/src/pages/inbounds/InboundsPage.tsx +++ b/frontend/src/pages/inbounds/InboundsPage.tsx @@ -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(null); - const [infoOpen, setInfoOpen] = useState(false); - const [infoDbInbound, setInfoDbInbound] = useState(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(null); @@ -173,7 +169,7 @@ export default function InboundsPage() { const [detachSource, setDetachSource] = useState(null); const [groupOpen, setGroupOpen] = useState(false); - const [groupSource, setGroupSource] = useState(null); + const [groupSourceID, setGroupSourceID] = useState(null); const [cloneOpen, setCloneOpen] = useState(false); const [cloneSource, setCloneSource] = useState(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() { - - setInfoOpen(false)} - dbInbound={infoDbInbound} - clientIndex={infoClientIndex} - expireDiff={expireDiff} - trafficDiff={trafficDiff} - ipLimitEnable={ipLimitEnable} - tgBotEnable={tgBotEnable} - subSettings={subSettings} - hosts={hosts} - lastOnlineMap={lastOnlineMap} - nodeAddress={infoNodeAddress} - /> - + {infoTarget && ( + + 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} + /> + + )} - - setGroupOpen(false)} - onAdded={refresh} - source={groupSource} - /> - + {groupSourceID !== null && ( + + setGroupOpen(false)} + onAdded={refresh} + inboundId={groupSourceID} + count={clientCount[groupSourceID]?.clients ?? 0} + /> + + )} 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([]); - - 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 ( { - 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 }; }} /> ); diff --git a/frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx b/frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx new file mode 100644 index 000000000..6273d36da --- /dev/null +++ b/frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx @@ -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 {}} />; +} + +const meta = { title: 'Inbounds/Detach Clients', component: Fixture } satisfies Meta< + typeof Fixture +>; +export default meta; +type Story = StoryObj; + +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 (url: string, params?: unknown) => { + if (url.endsWith('/fixture-job')) { + return new Msg(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(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 (url: string, payload?: unknown) => { + if (url.endsWith('/freeze')) { + return new Msg(true, '', { scopeToken: 'fixture-scope', total: population } as T); + } + submitted = payload; + return new Msg(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); diff --git a/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx b/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx index bbf3b5e19..8f091b1f1 100644 --- a/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx +++ b/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx @@ -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 ; +} + +function DetachClientPicker({ + id, + tag, onClose, onDetached, -}: DetachClientsModalProps) { +}: Pick & { id: number; tag: string }) { const { t } = useTranslation(); - const [messageApi, messageContextHolder] = message.useMessage(); - const [saving, setSaving] = useState(false); - const [clientRows, setClientRows] = useState([]); - const [selectedEmails, setSelectedEmails] = useState([]); + const [messages, holder] = message.useMessage(); const [search, setSearch] = useState(''); + const [page, setPage] = useState(1); + const [rows, setRows] = useState(); + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(''); + const [retry, setRetry] = useState(0); + const [busy, setBusy] = useState<'freeze' | 'submit'>(); + const [frozen, setFrozen] = useState(); + const [choices, setChoices] = useState(new Map()); + const [exclusionPage, setExclusionPage] = useState(1); + const [jobId, setJobId] = useState(); + const [progress, setProgress] = useState(); + const action = useRef(undefined); + const requestId = useRef(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(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( + 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) { + setChoices(next); + setExclusionPage((current) => Math.min(current, Math.max(1, Math.ceil(next.size / 10)))); + requestId.current = undefined; + } - const columns: ColumnsType = 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 ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [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( + 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( + 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 = [ + { 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 ? ( + {t('enable')} + ) : ( + {t('pages.inbounds.attachClientsStatusDisabled')} + ), + }, + ]; + const selectedKeys = pageRows + .filter((row) => (frozen ? row.inScope && !choices.has(row.id) : choices.has(row.id))) + .map((row) => row.id); + return ( { + 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} - - {t('pages.inbounds.detachClientsDesc', { count: clientRows.length })} - - + {holder} {t('pages.inbounds.detachClientsSelectLabel')} - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} + {rows && ( + + {t('pages.inbounds.detachClientsDesc', { count: rows.attached })} + + )} + { + reloadPage(); + setPage(1); + setSearch(event.target.value); + }} + placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} + /> + {loadError && ( + { + reloadPage(); + setRetry(retry + 1); + }} + > + {t('refresh')} + + } /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: clientRows.length, - })} + )} + + + + + + {t('pages.inbounds.selectedCount', { count: selected })} + {frozen && choices.size > 0 && ( +
+ + {t('pages.inbounds.attachExcludedClients')} ({choices.size}) + + {Array.from(choices) + .slice((exclusionPage - 1) * 10, exclusionPage * 10) + .map(([clientId, email]) => ( + + ))} + +
+ )} + {progress && ( + + )} 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: ( + + {t('pages.inbounds.detachClientsSelectLabel')} + + ), + selectedRowKeys: selectedKeys, + getCheckboxProps: (row) => ({ + disabled: locked || Boolean(frozen && !row.inScope), + 'aria-label': row.email, + }), + onChange: pickPage, + }} + /> + { + reloadPage(); + setPage(next); }} />
diff --git a/frontend/src/pages/inbounds/info/InboundInfoModal.css b/frontend/src/pages/inbounds/info/InboundInfoModal.css index 8f4babdf2..12a6d2936 100644 --- a/frontend/src/pages/inbounds/info/InboundInfoModal.css +++ b/frontend/src/pages/inbounds/info/InboundInfoModal.css @@ -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); +} diff --git a/frontend/src/pages/inbounds/info/InboundInfoModal.tsx b/frontend/src/pages/inbounds/info/InboundInfoModal.tsx index 0315aa3a1..eef981ff0 100644 --- a/frontend/src/pages/inbounds/info/InboundInfoModal.tsx +++ b/frontend/src/pages/inbounds/info/InboundInfoModal.tsx @@ -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(null); const [clientStats, setClientStats] = useState(null); const [links, setLinks] = useState<{ remark?: string; link: string }[]>([]); - const [wireguardConfigs, setWireguardConfigs] = useState([]); - const [wireguardLinks, setWireguardLinks] = useState([]); - const [amneziawgConfigs, setAmneziawgConfigs] = useState([]); - const [amneziawgLinks, setAmneziawgLinks] = useState([]); + const [peerConfigs, setPeerConfigs] = useState([]); + const [peerLinks, setPeerLinks] = useState([]); 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[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[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} +
); } @@ -1154,18 +1089,28 @@ export default function InboundInfoModal({
- {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) => ( - - {t('pages.inbounds.info.peerNumber', { n: idx + 1 })} + }, + idx, + ) => ( + + + {t('pages.inbounds.info.peerNumber', { n: peerOffset + idx + 1 })} +
{t('pages.xray.wireguard.secretKey')}
@@ -1182,13 +1127,13 @@ export default function InboundInfoModal({
PSK
- {peer.psk} + {peer.psk ?? peer.preSharedKey}
{t('pages.xray.wireguard.allowedIPs')}
- {(peer.allowedIPs || []).map((ip, j) => ( + {(Array.isArray(peer.allowedIPs) ? peer.allowedIPs : []).map((ip, j) => ( {ip} @@ -1202,13 +1147,13 @@ export default function InboundInfoModal({
- {(wireguardConfigs[idx] ?? []).map( + {(peerConfigs[idx] ?? []).map( (cfg, j, all) => cfg && (
- - {t('pages.inbounds.info.peerNumberConfig', { n: idx + 1 })} + + {t('pages.inbounds.info.peerNumberConfig', { n: peerOffset + idx + 1 })}
), )} - {(wireguardLinks[idx] ?? []).map( + {(peerLinks[idx] ?? []).map( (link, j) => link && (
- Peer {idx + 1} link + Peer {peerOffset + idx + 1} link
@@ -1291,12 +1239,12 @@ export default function InboundInfoModal({
), )} - {(amneziawgLinks[idx] ?? []).map( + {(peerLinks[idx] ?? []).map( (link, j) => link && (
- Peer {idx + 1} link + Peer {peerOffset + idx + 1} link + )} + + ) : null; + const feedback = ( + <> + {holder} + {info.isPending && } + {info.isError && ( + void info.refetch()}>{t('refresh')}} + /> + )} + + ); + return ( + + ); +} diff --git a/frontend/src/pages/inbounds/info/peerExport.ts b/frontend/src/pages/inbounds/info/peerExport.ts new file mode 100644 index 000000000..75c8a2b22 --- /dev/null +++ b/frontend/src/pages/inbounds/info/peerExport.ts @@ -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; + +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({ + 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((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); +} diff --git a/frontend/src/pages/inbounds/info/peerLinks.ts b/frontend/src/pages/inbounds/info/peerLinks.ts new file mode 100644 index 000000000..a8fb1bd98 --- /dev/null +++ b/frontend/src/pages/inbounds/info/peerLinks.ts @@ -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: [] }; + } +} diff --git a/frontend/src/pages/inbounds/info/types.ts b/frontend/src/pages/inbounds/info/types.ts index 779bafeb9..2556e0516 100644 --- a/frontend/src/pages/inbounds/info/types.ts +++ b/frontend/src/pages/inbounds/info/types.ts @@ -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; diff --git a/frontend/src/pages/inbounds/list/InboundList.tsx b/frontend/src/pages/inbounds/list/InboundList.tsx index bad9144a0..35dd20002 100644 --- a/frontend/src/pages/inbounds/list/InboundList.tsx +++ b/frontend/src/pages/inbounds/list/InboundList.tsx @@ -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, diff --git a/frontend/src/pages/inbounds/list/InboundStatsModal.tsx b/frontend/src/pages/inbounds/list/InboundStatsModal.tsx index 27f638262..6a3916ab1 100644 --- a/frontend/src/pages/inbounds/list/InboundStatsModal.tsx +++ b/frontend/src/pages/inbounds/list/InboundStatsModal.tsx @@ -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({ {clientCount[record.id].clients} + {clientCount[record.id].onlineAttribution && + clientCount[record.id].online.length === 0 && ( + + {t('online')}: {onlineStatusLabel(clientCount[record.id], t)} + + )} {clientCount[record.id].online.length > 0 && ( {clientCount[record.id].online.length} {t('online')} + {clientCount[record.id].onlineAttribution === 'node' && + ` (${t('pages.inbounds.node')})`} )} {clientCount[record.id].depleted.length > 0 && ( diff --git a/frontend/src/pages/inbounds/list/onlineStatusLabel.ts b/frontend/src/pages/inbounds/list/onlineStatusLabel.ts new file mode 100644 index 000000000..8a9f26ba7 --- /dev/null +++ b/frontend/src/pages/inbounds/list/onlineStatusLabel.ts @@ -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'); + } +} diff --git a/frontend/src/pages/inbounds/list/types.ts b/frontend/src/pages/inbounds/list/types.ts index ab76e334e..a9ac39f45 100644 --- a/frontend/src/pages/inbounds/list/types.ts +++ b/frontend/src/pages/inbounds/list/types.ts @@ -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; + clientCountsPending: boolean; onlineClients: string[]; lastOnlineMap: Record; inboundSpeed: Record; diff --git a/frontend/src/pages/inbounds/list/useInboundColumns.tsx b/frontend/src/pages/inbounds/list/useInboundColumns.tsx index 1d2a7c8bb..63e42b33a 100644 --- a/frontend/src/pages/inbounds/list/useInboundColumns.tsx +++ b/frontend/src/pages/inbounds/list/useInboundColumns.tsx @@ -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 = ( + + {emails.length} + {suffix && ` ${suffix}`} + + ); + if (!emails.length) return badge; + return ( + + {emails.map((email) => ( +
{email}
+ ))} +
+ ) : null + } + > + {badge} + + ); +} + interface UseInboundColumnsParams { hasAnyRemark: boolean; hasAnySubSortIndex: boolean; @@ -34,6 +78,7 @@ interface UseInboundColumnsParams { nodesById: Map; hostRemarksByInboundId: Map; clientCount: Record; + clientCountsPending: boolean; inboundSpeed: Record; 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 ( <> {cc.clients} - {cc.active.length > 0 ? ( - - {cc.active.map((e) => ( -
{e}
- ))} -
- } - > - - {cc.active.length} - - - ) : ( - - 0 - - )} + {cc.deactive.length > 0 && ( - - {cc.deactive.map((e) => ( -
{e}
- ))} -
- } - > - - {cc.deactive.length} - - + )} {cc.depleted.length > 0 && ( - - {cc.depleted.map((e) => ( -
{e}
- ))} - - } - > - - {cc.depleted.length} - -
+ + )} + {cc.onlineAttribution && cc.online.length === 0 && ( + + {t('online')}: {onlineStatusLabel(cc, t)} + )} {cc.online.length > 0 && ( - - {cc.online.map((e) => ( -
{e}
- ))} - - } - > - - {cc.online.length} - -
+ )} ); @@ -477,6 +461,7 @@ export function useInboundColumns({ nodesById, hostRemarksByInboundId, clientCount, + clientCountsPending, inboundSpeed, subEnable, expireDiff, diff --git a/frontend/src/pages/inbounds/useInbounds.ts b/frontend/src/pages/inbounds/useInbounds.ts index b69de541a..4cc55c11a 100644 --- a/frontend/src/pages/inbounds/useInbounds.ts +++ b/frontend/src/pages/inbounds/useInbounds.ts @@ -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; } +interface CachedClientRollup { + base: ClientRollup; + refreshAt: number; + online?: { emails?: Set; result: ClientRollup }; +} + +const EMPTY_ONLINE: string[] = []; +const EMPTY_ROLLUPS: Record = {}; + const TRACKED_PROTOCOLS: readonly string[] = [ Protocols.VMESS, Protocols.VLESS, @@ -101,12 +111,12 @@ async function fetchOnlineClientsByGuid(): Promise> { // 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> { +async function fetchActiveInboundsByNode(): Promise> { 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) + ? (validated.obj as Record) : {}; } @@ -119,16 +129,41 @@ function toGuidOnlineMap(data: Record): Map>, b: Map>): 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, +): Map | null> { + const map = new Map | 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 | null>( + previous: Map, + next: Map, +): Map { + 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> { @@ -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([]); + const [inboundGeneration, setInboundGeneration] = useState(0); const dbInboundsRef = useRef([]); 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>>(() => 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>>(() => new Map()); + // An explicit empty set is an idle node. A missing set has no usable activity sample. + const [activeByGuid, setActiveByGuid] = useState | null>>( + () => new Map(), + ); + const onlinePending = onlinesByGuidQuery.isPending || activeInboundsQuery.isPending; const [lastOnlineMap, setLastOnlineMap] = useState>({}); 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(); - 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(), 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; + }>(); + useEffect(() => { + if (!largeList) return; const counts: Record = {}; - 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; + 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 = {}; + 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(); 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(); if (activeInboundsQuery.data && activeInboundsQuery.data !== syncedActiveInbounds) { setSyncedActiveInbounds(activeInboundsQuery.data); - setActiveByGuid(toGuidOnlineMap(activeInboundsQuery.data)); + setActiveByGuid(toActiveInboundMap(activeInboundsQuery.data)); } const [syncedLastOnline, setSyncedLastOnline] = useState(); @@ -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; - activeInbounds?: Record; + activeInbounds?: Record; lastOnlineMap?: Record; }; 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, diff --git a/frontend/src/pages/index/ConnectionsCard.tsx b/frontend/src/pages/index/ConnectionsCard.tsx index 128e9b4ab..35d4d3140 100644 --- a/frontend/src/pages/index/ConnectionsCard.tsx +++ b/frontend/src/pages/index/ConnectionsCard.tsx @@ -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({ -
- -
diff --git a/frontend/src/pages/index/IndexPage.css b/frontend/src/pages/index/IndexPage.css index 22f689698..7e07bab85 100644 --- a/frontend/src/pages/index/IndexPage.css +++ b/frontend/src/pages/index/IndexPage.css @@ -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 { diff --git a/frontend/src/pages/index/IndexPage.tsx b/frontend/src/pages/index/IndexPage.tsx index 63fda3f39..98760a2e1 100644 --- a/frontend/src/pages/index/IndexPage.tsx +++ b/frontend/src/pages/index/IndexPage.tsx @@ -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(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} /> } @@ -278,8 +301,6 @@ export default function IndexPage() { )} data={history.series.mem} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -298,8 +319,6 @@ export default function IndexPage() { )} data={history.series.swap} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -317,8 +336,6 @@ export default function IndexPage() { )} data={history.series.diskUsage} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} />
@@ -329,8 +346,6 @@ export default function IndexPage() { down={history.series.netDown} labels={history.labels} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} />
diff --git a/frontend/src/pages/index/OverviewActionBar.tsx b/frontend/src/pages/index/OverviewActionBar.tsx index 9a5dbab7f..b7de16cab 100644 --- a/frontend/src/pages/index/OverviewActionBar.tsx +++ b/frontend/src/pages/index/OverviewActionBar.tsx @@ -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; 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: , - text: t('pages.index.xrayMetricsTitle'), - onClick: onOpenXrayMetrics, - }, ], ]; @@ -241,6 +240,18 @@ export default function OverviewActionBar({ ))}
))} +
+ + +
); diff --git a/frontend/src/pages/index/OverviewRangeSelect.tsx b/frontend/src/pages/index/OverviewRangeSelect.tsx index a9878cee2..cfc25467c 100644 --- a/frontend/src/pages/index/OverviewRangeSelect.tsx +++ b/frontend/src/pages/index/OverviewRangeSelect.tsx @@ -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 ( - } + aria-label={t('search')} + placeholder={t('pages.nodes.fleet.searchNodes')} + allowClear + value={search} + onChange={(event) => setSearch(event.target.value)} + /> + { + setPickerOpen(next); + if (!next) setSearch(''); + }} + showSearch={{ searchValue: search, onSearch: setSearch, filterOption: false }} + notFoundContent={{status}} + popupRender={(menu) => ( + <> + {menu} + {showStatusInMenu && status && ( +
+ {status} +
+ )} + + )} + options={options} + /> + + ); +} + 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({ - csv(typeof value === 'string' ? value : ''), - output: (value) => (Array.isArray(value) ? value.join(',') : ''), - }} - > -