diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0613783c9..0a996453f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -127,13 +127,24 @@ jobs: - name: PostgreSQL client IP sync regressions run: | set -o pipefail - go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v | tee /tmp/postgres-client-ip-sync.log + go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner|Scheduler)?$' -count=1 -v | tee /tmp/postgres-client-ip-sync.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-ip-sync.log || true) - if [ "$passed" -ne 2 ]; then - echo "expected 2 passing PostgreSQL client IP sync tests, got $passed" >&2 + if [ "$passed" -ne 3 ]; then + echo "expected 3 passing PostgreSQL client IP sync tests, got $passed" >&2 exit 1 fi + - name: PostgreSQL IP reporter lock order and lifecycle + run: | + set -o pipefail + go test ./internal/web/service -run '^TestPostgres(NodeIPReporterClientLockOrder|FlatIPReporterLifecycleCommit|PolledAttributionSurvivesConcurrentPrune)$' -count=1 -v | tee /tmp/postgres-ip-reporter-locks.log + for test in NodeIPReporterClientLockOrder FlatIPReporterLifecycleCommit PolledAttributionSurvivesConcurrentPrune; do + if ! grep -q -- "^--- PASS: TestPostgres${test} " /tmp/postgres-ip-reporter-locks.log; then + echo "expected PostgreSQL reporter test TestPostgres${test} to pass" >&2 + exit 1 + fi + done + - name: PostgreSQL Xray traffic retry run: | set -o pipefail @@ -144,6 +155,39 @@ 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|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 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 global-traffic heartbeat regressions run: | set -o pipefail @@ -204,6 +248,16 @@ jobs: 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 @@ -214,6 +268,22 @@ jobs: exit 1 fi + - name: PostgreSQL node client reconciliation + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeFullReconciliation|NodeMerge(BatchesBaselinesForActiveClients|LetsSubscriptionTouchDuringClientReconciliationPostgres)$)' -count=1 -v | tee /tmp/postgres-node-client-reconciliation.log + passed=$(grep -c -- '^--- PASS: TestNodeFullReconciliation' /tmp/postgres-node-client-reconciliation.log || true) + if [ "$passed" -ne 4 ]; then + echo "expected 4 passing node client reconciliation tests, got $passed" >&2 + exit 1 + fi + for test in TestNodeMergeBatchesBaselinesForActiveClients TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres; do + if ! grep -q -- "^--- PASS: $test " /tmp/postgres-node-client-reconciliation.log; then + echo "expected PostgreSQL regression to pass: $test" >&2 + exit 1 + fi + done + - name: PostgreSQL node counter reset regressions run: | set -o pipefail @@ -224,6 +294,16 @@ jobs: exit 1 fi + - name: PostgreSQL node merge contention + run: | + set -o pipefail + go test ./internal/web/service -run '^TestNodeMerge(LetsSubscriptionTouchDuringClientReconciliationPostgres|BatchesBaselinesForActiveClients)$' -count=1 -v | tee /tmp/postgres-node-merge-contention.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-merge-contention.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected both PostgreSQL node merge contention tests to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL schema and migration tests run: | set -o pipefail diff --git a/docs/architecture.md b/docs/architecture.md index 06e27193c..33d3f3781 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -390,6 +390,19 @@ merged with GUID-based baselines to avoid double counting after resets. `model.NodeClientTraffic`, `model.ClientGlobalTraffic` (cross-master totals). A client reset is queued per hosting node in `model.NodePendingReset` (`service/node_reset_queue.go`) and replayed by the node sync until the node accepts it. + +Client mutations reserve node dispatch turns when their local transactions commit. The writer and +inbound mutex are released before dispatch waits. Conflicting inbounds are ordered, independent +inbounds can use any of four live slots on a node, and full deletion and reconciliation use an +exclusive node turn. Each live push waits up to four seconds for its turn and then receives up to +four seconds for the whole RPC batch. A saturated delta is left dirty for reconciliation. Full +deletions are stored in the transactional node outbox and retried until the direct peer confirms +deletion or absence. HTTP requests can also include validation, writer waits and multiple waves of +inbound work. A direct acknowledgment can report downstream work pending alongside these results. + +Node traffic polls run independently within the shared worker limit. The publisher sums the latest +valid speed sample from every eligible node. Display samples expire after two five-second windows +and leave the cumulative counter baseline available for the next poll. Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.TrafficReset`). Cross-panel totals are stored per master GUID and hosted email, separately from local diff --git a/docs/content/docs/en/help/troubleshooting.mdx b/docs/content/docs/en/help/troubleshooting.mdx index d9b72d373..014247621 100644 --- a/docs/content/docs/en/help/troubleshooting.mdx +++ b/docs/content/docs/en/help/troubleshooting.mdx @@ -13,6 +13,18 @@ A checklist for the most common issues. When in doubt, raise the log level - Make sure the **panel port isn't already in use** by another service. - Verify the database path is writable (default `/etc/x-ui/x-ui.db`). +## Panel restart takes too long + +The restart action acknowledges that a request was accepted. The service logs +successful completion once the panel and subscription listeners have both started. +A normal panel restart keeps the running Xray process. Each restart has a +75-second budget shared by both listener drains and the other shutdown and startup phases. + +If a phase fails or overruns that budget, the panel exits with an error so its +supervisor can restart it. This recovery can interrupt Xray sessions. On a +systemd installation, inspect `journalctl -u x-ui` for the phase and elapsed +time. Use a supervisor configured to restart the service after failures. + ## 502 / panel unreachable behind a proxy - Confirm the panel is actually listening on the upstream port (e.g. `2053`). 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 8c344b2ce..86194e023 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -336,10 +336,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 +347,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' @@ -681,21 +682,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. @@ -812,6 +814,16 @@ _openapi: (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables @@ -823,7 +835,8 @@ _openapi: preview is informational and does not reserve an allowance or guarantee node availability. heading: preview-client-auto-renewal-dates-without-saving-or-resetting-anything - - content: 'An omitted `flow` leaves every attached inbound on its own flow. Send + - content: >- + An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. @@ -834,9 +847,20 @@ _openapi: still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in - place.' + place. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + - content: >- + Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, @@ -849,9 +873,20 @@ _openapi: still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in - place.' + place. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1 - - content: 'The inbounds are applied concurrently and independently: one that + - content: >- + The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can @@ -859,9 +894,20 @@ _openapi: record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` - prefix and leaves the client already removed from every inbound.' + prefix and leaves the client already removed from every inbound. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + - content: >- + Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the @@ -871,23 +917,55 @@ _openapi: record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` - prefix and leaves the client already removed from every inbound.' + prefix and leaves the client already removed from every inbound. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1 - - content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound + - content: >- + A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still - attached and a `success:false` response can be partial.' + attached and a `success:false` response can be partial. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json - - content: 'The inbounds are applied concurrently and independently: one that + - content: >- + The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing - beyond the inbounds, so every error carries the prefix.' + beyond the inbounds, so every error carries the prefix. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client - content: The original credentials remain the primary device. Additional devices share their parent client email, traffic quota, expiry and enable @@ -909,6 +987,41 @@ _openapi: previously downloaded configuration loses access after the configuration is applied. heading: delete-an-additional-wireguard-device-and-release-its-address + - 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: 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 + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons + - 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: 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: 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 + - 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 + - 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: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running + - 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: 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 --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} diff --git a/docs/content/docs/en/reference/api/inbounds.mdx b/docs/content/docs/en/reference/api/inbounds.mdx index 165dc5fd8..3f0d9d5ca 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 @@ -148,6 +153,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 @@ -231,7 +240,11 @@ _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 --- {/* 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 +254,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file 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 4877ccf2d..870ef99e3 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2114,6 +2114,16 @@ ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2127,6 +2137,170 @@ ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2149,6 +2323,48 @@ ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2419,6 +2635,42 @@ ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -5615,6 +5867,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": { @@ -6901,6 +7190,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": [ @@ -10552,7 +10890,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "requestBody": { "required": true, "content": { @@ -10609,12 +10947,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client added" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10720,7 +11080,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10764,12 +11124,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10784,7 +11166,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10828,12 +11210,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10848,7 +11252,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10883,12 +11287,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10903,7 +11329,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10938,12 +11364,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10958,7 +11406,7 @@ ], "summary": "Attach an existing client to one or more additional inbounds. Body is JSON.", "operationId": "post_panel_api_clients_email_attach", - "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.", + "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11012,11 +11460,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11031,7 +11502,7 @@ ], "summary": "Detach a client from one or more inbounds without deleting the client.", "operationId": "post_panel_api_clients_email_detach", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11084,11 +11555,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11862,6 +12356,7 @@ ], "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.", "requestBody": { "required": true, "content": { @@ -11953,6 +12448,14 @@ "obj": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] } } @@ -11969,6 +12472,7 @@ ], "summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkEnable", + "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": { "required": true, "content": { @@ -11999,17 +12503,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12027,6 +12541,7 @@ ], "summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkDisable", + "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": { "required": true, "content": { @@ -12057,17 +12572,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12085,6 +12610,7 @@ ], "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.", "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.", "requestBody": { "required": true, "content": { @@ -12116,17 +12642,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12144,6 +12680,7 @@ ], "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.", "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": { "required": true, "content": { @@ -12195,17 +12732,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkCreateResult" + } } }, "example": { "success": true, "obj": { - "created": 2, + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "alice@example.com", - "reason": "email already in use" + "email": "", + "reason": "" } ] } @@ -12328,6 +12875,7 @@ ], "summary": "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 AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", + "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": { "required": true, "content": { @@ -12385,20 +12933,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkAttachResult" + } } }, "example": { "success": true, "obj": { "attached": [ - "alice", - "bob" + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } ], "skipped": [ - "bob" - ], - "errors": [] + "" + ] } } } @@ -12466,6 +13025,7 @@ ], "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.", "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": { "required": true, "content": { @@ -12520,18 +13080,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDetachResult" + } } }, "example": { "success": true, "obj": { "detached": [ - "alice", - "bob" + "" ], - "skipped": [], - "errors": [] + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] } } } @@ -13399,7 +13972,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": { @@ -13484,7 +14057,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": { @@ -19775,8 +20348,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", diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4877ccf2d..870ef99e3 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2114,6 +2114,16 @@ ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2127,6 +2137,170 @@ ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2149,6 +2323,48 @@ ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2419,6 +2635,42 @@ ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -5615,6 +5867,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": { @@ -6901,6 +7190,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": [ @@ -10552,7 +10890,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "requestBody": { "required": true, "content": { @@ -10609,12 +10947,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client added" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10720,7 +11080,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10764,12 +11124,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10784,7 +11166,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10828,12 +11210,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10848,7 +11252,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10883,12 +11287,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10903,7 +11329,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10938,12 +11364,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10958,7 +11406,7 @@ ], "summary": "Attach an existing client to one or more additional inbounds. Body is JSON.", "operationId": "post_panel_api_clients_email_attach", - "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.", + "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11012,11 +11460,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11031,7 +11502,7 @@ ], "summary": "Detach a client from one or more inbounds without deleting the client.", "operationId": "post_panel_api_clients_email_detach", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11084,11 +11555,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11862,6 +12356,7 @@ ], "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.", "requestBody": { "required": true, "content": { @@ -11953,6 +12448,14 @@ "obj": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] } } @@ -11969,6 +12472,7 @@ ], "summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkEnable", + "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": { "required": true, "content": { @@ -11999,17 +12503,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12027,6 +12541,7 @@ ], "summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkDisable", + "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": { "required": true, "content": { @@ -12057,17 +12572,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12085,6 +12610,7 @@ ], "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.", "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.", "requestBody": { "required": true, "content": { @@ -12116,17 +12642,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12144,6 +12680,7 @@ ], "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.", "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": { "required": true, "content": { @@ -12195,17 +12732,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkCreateResult" + } } }, "example": { "success": true, "obj": { - "created": 2, + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "alice@example.com", - "reason": "email already in use" + "email": "", + "reason": "" } ] } @@ -12328,6 +12875,7 @@ ], "summary": "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 AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", + "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": { "required": true, "content": { @@ -12385,20 +12933,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkAttachResult" + } } }, "example": { "success": true, "obj": { "attached": [ - "alice", - "bob" + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } ], "skipped": [ - "bob" - ], - "errors": [] + "" + ] } } } @@ -12466,6 +13025,7 @@ ], "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.", "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": { "required": true, "content": { @@ -12520,18 +13080,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDetachResult" + } } }, "example": { "success": true, "obj": { "detached": [ - "alice", - "bob" + "" ], - "skipped": [], - "errors": [] + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] } } } @@ -13399,7 +13972,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": { @@ -13484,7 +14057,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": { @@ -19775,8 +20348,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", diff --git a/frontend/scripts/build-openapi.mjs b/frontend/scripts/build-openapi.mjs index e2b4e5d2e..69e0688d5 100644 --- a/frontend/scripts/build-openapi.mjs +++ b/frontend/scripts/build-openapi.mjs @@ -266,7 +266,9 @@ function buildOperation(ep, tag) { ...(ep.responseSchemaArrayNullable ? { nullable: true } : {}), items: ref, } - : ref; + : ep.responseSchemaNullable + ? { oneOf: [ref, { type: 'object', nullable: true, enum: [null] }] } + : ref; if (successExample === undefined) { successExample = { success: true, obj: ep.responseSchemaArray ? [obj] : obj }; } diff --git a/frontend/src/api/websocketBridge.ts b/frontend/src/api/websocketBridge.ts index 9394398c8..b475a20a0 100644 --- a/frontend/src/api/websocketBridge.ts +++ b/frontend/src/api/websocketBridge.ts @@ -7,26 +7,27 @@ import { isRecentLocalInvalidate } from '@/api/invalidationTracker'; type Handler = (payload: unknown) => void; -let invalidateTimer: number | null = null; - export function useWebSocketBridge() { const queryClient = useQueryClient(); useEffect(() => { const client = getSharedWebSocketClient(); + const pendingInvalidations = new Set<'inbounds' | 'clients'>(); + let invalidateTimer: number | undefined; const onInvalidate: Handler = (payload) => { const p = payload as { type?: string } | undefined; if (!p || (p.type !== 'inbounds' && p.type !== 'clients')) return; - if (invalidateTimer != null) clearTimeout(invalidateTimer); + pendingInvalidations.add(p.type); + if (invalidateTimer !== undefined) return; invalidateTimer = window.setTimeout(() => { - invalidateTimer = null; - if (isRecentLocalInvalidate()) return; - if (p.type === 'inbounds') { - queryClient.invalidateQueries({ queryKey: ['inbounds'] }); - } else { - queryClient.invalidateQueries({ queryKey: ['clients'] }); + invalidateTimer = undefined; + if (!isRecentLocalInvalidate()) { + for (const type of pendingInvalidations) { + queryClient.invalidateQueries({ queryKey: keys[type].root() }); + } } + pendingInvalidations.clear(); }, 200); }; @@ -56,10 +57,7 @@ export function useWebSocketBridge() { client.off('outbounds', onOutbounds); client.off('nodes', onNodes); client.off('inbounds', onInbounds); - if (invalidateTimer != null) { - clearTimeout(invalidateTimer); - invalidateTimer = null; - } + clearTimeout(invalidateTimer); }; }, [queryClient]); } diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 081067ac9..b8e09aa02 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -509,13 +509,122 @@ export const EXAMPLES: Record = { "BulkAdjustResult": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] }, + "BulkAttachResult": { + "attached": [ + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] + }, + "BulkCreateReport": { + "email": "", + "reason": "" + }, + "BulkCreateResult": { + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, + "BulkDeleteReport": { + "email": "", + "reason": "" + }, + "BulkDeleteResult": { + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, + "BulkDetachResult": { + "detached": [ + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] + }, "BulkExternalLinksResult": { "added": 4, "errors": 0, "skipped": 0 }, + "BulkSetEnableReport": { + "email": "", + "reason": "" + }, + "BulkSetEnableResult": { + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, "Client": { "adTag": "0123456789abcdef0123456789abcdef", "allowedIPs": [ @@ -585,6 +694,21 @@ export const EXAMPLES: Record = { "flowOverride": "", "inboundId": 0 }, + "ClientNodeApplyOutcome": { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + }, + "ClientNodeApplyResponse": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + }, "ClientNodeUsage": { "down": 2097152, "nodeId": 7, @@ -1443,6 +1567,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, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index e5b7085f6..378fc8b16 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2088,6 +2088,16 @@ export const SCHEMAS: Record = { ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2101,6 +2111,170 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2123,6 +2297,48 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2393,6 +2609,42 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -5589,6 +5841,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": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 5bf30b7ce..4d2bca454 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -499,15 +499,69 @@ export interface BulkAdjustReport { export interface BulkAdjustResult { adjusted: number; externalLinks?: BulkExternalLinksResult | null; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; skipped?: BulkAdjustReport[]; } +export interface BulkAttachResult { + attached: string[]; + errors: string[]; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped: string[]; +} + +export interface BulkCreateReport { + email: string; + reason: string; +} + +export interface BulkCreateResult { + created: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkCreateReport[]; +} + +export interface BulkDeleteReport { + email: string; + reason: string; +} + +export interface BulkDeleteResult { + deleted: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkDeleteReport[]; +} + +export interface BulkDetachResult { + detached: string[]; + errors: string[]; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped: string[]; +} + export interface BulkExternalLinksResult { added: number; errors: number; skipped: number; } +export interface BulkSetEnableReport { + email: string; + reason: string; +} + +export interface BulkSetEnableResult { + changed: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkSetEnableReport[]; +} + export interface Client { adTag?: string; allowedIPs?: string[]; @@ -563,6 +617,17 @@ export interface ClientInbound { inboundId: number; } +export interface ClientNodeApplyOutcome { + nodeId: number; + reason?: string; + status: string; +} + +export interface ClientNodeApplyResponse { + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; +} + export interface ClientNodeUsage { down: number; nodeId: number; @@ -1253,6 +1318,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; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 91489537e..de23c7e02 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -522,10 +522,58 @@ export type BulkAdjustReport = z.infer; export const BulkAdjustResultSchema = z.object({ adjusted: z.number().int(), externalLinks: z.lazy(() => BulkExternalLinksResultSchema).nullable().optional(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), skipped: z.array(z.lazy(() => BulkAdjustReportSchema)).optional(), }); export type BulkAdjustResult = z.infer; +export const BulkAttachResultSchema = z.object({ + attached: z.array(z.string()), + errors: z.array(z.string()), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.string()), +}); +export type BulkAttachResult = z.infer; + +export const BulkCreateReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkCreateReport = z.infer; + +export const BulkCreateResultSchema = z.object({ + created: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkCreateReportSchema)).optional(), +}); +export type BulkCreateResult = z.infer; + +export const BulkDeleteReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkDeleteReport = z.infer; + +export const BulkDeleteResultSchema = z.object({ + deleted: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkDeleteReportSchema)).optional(), +}); +export type BulkDeleteResult = z.infer; + +export const BulkDetachResultSchema = z.object({ + detached: z.array(z.string()), + errors: z.array(z.string()), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.string()), +}); +export type BulkDetachResult = z.infer; + export const BulkExternalLinksResultSchema = z.object({ added: z.number().int(), errors: z.number().int(), @@ -533,6 +581,20 @@ export const BulkExternalLinksResultSchema = z.object({ }); export type BulkExternalLinksResult = z.infer; +export const BulkSetEnableReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkSetEnableReport = z.infer; + +export const BulkSetEnableResultSchema = z.object({ + changed: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkSetEnableReportSchema)).optional(), +}); +export type BulkSetEnableResult = z.infer; + export const ClientSchema = z.object({ adTag: z.string().optional(), allowedIPs: z.array(z.string()).optional(), @@ -591,6 +653,19 @@ export const ClientInboundSchema = z.object({ }); export type ClientInbound = z.infer; +export const ClientNodeApplyOutcomeSchema = z.object({ + nodeId: z.number().int(), + reason: z.string().optional(), + status: z.string(), +}); +export type ClientNodeApplyOutcome = z.infer; + +export const ClientNodeApplyResponseSchema = z.object({ + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), +}); +export type ClientNodeApplyResponse = z.infer; + export const ClientNodeUsageSchema = z.object({ down: z.number().int(), nodeId: z.number().int(), @@ -1336,6 +1411,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(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8eb435b29..91080469e 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -45,6 +45,7 @@ export interface Endpoint { requestSchema?: Record; bodyRequiredOneOf?: string[]; responseSchema?: string; + responseSchemaNullable?: boolean; responseSchemaArray?: boolean; responseSchemaArrayNullable?: boolean; responseObjectSchema?: Record; @@ -65,6 +66,17 @@ export interface Section { endpoints: Endpoint[]; } +const clientNodeApplyResponse = { + responseSchema: 'ClientNodeApplyResponse', + responseSchemaNullable: true, +} satisfies Partial; + +const clientNodeApplyDescription = + '\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.'; + +const bulkClientNodeApplyDescription = + '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.'; + // /inbounds/update replaces the whole row, so it takes the same payload as /add. const inboundBody = '{\n "enable": true,\n "remark": "VLESS-443",\n "listen": "",\n "port": 443,\n "protocol": "vless",\n "expiryTime": 0,\n "total": 0,\n "settings": {\n "clients": [{ "id": "...", "email": "user1" }],\n "decryption": "none"\n },\n "streamSettings": {\n "network": "tcp",\n "security": "reality",\n "realitySettings": { "show": false, "dest": "..." }\n },\n "sniffing": {\n "enabled": true,\n "destOverride": ["http", "tls"]\n }\n}'; @@ -291,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', @@ -1309,7 +1331,8 @@ export const sections: readonly Section[] = [ summary: 'Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.', description: - 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.', + 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.' + + clientNodeApplyDescription, params: [ { name: 'client', @@ -1325,7 +1348,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "tgId": 0,\n "limitIp": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [3, 5]\n}', - response: '{\n "success": true,\n "msg": "Client added"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1379,7 +1402,8 @@ export const sections: readonly Section[] = [ summary: 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' + + clientNodeApplyDescription, params: [ { name: 'email', @@ -1389,7 +1413,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', - response: '{\n "success": true,\n "msg": "Client updated"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1397,7 +1421,8 @@ export const sections: readonly Section[] = [ summary: 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' + + clientNodeApplyDescription, params: [ { name: 'email', @@ -1407,7 +1432,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', - response: '{\n "success": true,\n "msg": "Client updated"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1415,7 +1440,8 @@ export const sections: readonly Section[] = [ summary: 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1426,7 +1452,7 @@ export const sections: readonly Section[] = [ optional: true, }, ], - response: '{\n "success": true,\n "msg": "Client deleted"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1434,7 +1460,8 @@ export const sections: readonly Section[] = [ summary: 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'query', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1445,14 +1472,15 @@ export const sections: readonly Section[] = [ optional: true, }, ], - response: '{\n "success": true,\n "msg": "Client deleted"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', path: '/panel/api/clients/:email/attach', summary: 'Attach an existing client to one or more additional inbounds. Body is JSON.', description: - 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.', + 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1463,14 +1491,15 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "inboundIds": [7, 9]\n}', - response: '{\n "success": true\n}', + ...clientNodeApplyResponse, }, { method: 'POST', path: '/panel/api/clients/:email/detach', summary: 'Detach a client from one or more inbounds without deleting the client.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.', + 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1481,7 +1510,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "inboundIds": [5]\n}', - response: '{\n "success": true\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1631,6 +1660,7 @@ 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.', requestSchema: { @@ -1678,38 +1708,38 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkEnable', + description: bulkClientNodeApplyDescription, summary: 'Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.', body: '{\n "emails": ["alice", "bob"]\n}', - response: - '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkSetEnableResult', }, { method: 'POST', path: '/panel/api/clients/bulkDisable', + description: bulkClientNodeApplyDescription, summary: 'Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.', body: '{\n "emails": ["alice", "bob"]\n}', - response: - '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkSetEnableResult', }, { 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}', - response: - '{\n "success": true,\n "obj": {\n "deleted": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkDeleteResult', }, { method: 'POST', 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]', - response: - '{\n "success": true,\n "obj": {\n "created": 2,\n "skipped": [\n { "email": "alice@example.com", "reason": "email already in use" }\n ]\n }\n}', + responseSchema: 'BulkCreateResult', }, { method: 'POST', @@ -1730,6 +1760,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkAttach', + description: bulkClientNodeApplyDescription, summary: '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 AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.', params: [ @@ -1755,8 +1786,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', - response: - '{\n "success": true,\n "obj": {\n "attached": ["alice", "bob"],\n "skipped": ["bob"],\n "errors": []\n }\n}', + responseSchema: 'BulkAttachResult', }, { method: 'GET', @@ -1776,6 +1806,7 @@ export const sections: readonly Section[] = [ { 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.", params: [ @@ -1793,8 +1824,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', - response: - '{\n "success": true,\n "obj": {\n "detached": ["alice", "bob"],\n "skipped": [],\n "errors": []\n }\n}', + responseSchema: 'BulkDetachResult', }, { method: 'POST', @@ -1944,7 +1974,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}', }, @@ -1960,7 +1990,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}', }, 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/inbounds/ClientRollups.stories.tsx b/frontend/src/pages/inbounds/ClientRollups.stories.tsx new file mode 100644 index 000000000..06b74132d --- /dev/null +++ b/frontend/src/pages/inbounds/ClientRollups.stories.tsx @@ -0,0 +1,115 @@ +import { useState } from 'react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect } from 'storybook/test'; + +import { keys } from '@/api/queryKeys'; + +import { useInbounds } from './useInbounds'; + +const meta = { title: 'Inbounds/Client rollup performance' } satisfies Meta; +export default meta; + +function Rollups() { + const { dbInbounds, clientCount, applyTrafficEvent } = useInbounds(); + const [input, setInput] = useState(''); + return ( + <> + +

+ {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..6c062533f 100644 --- a/frontend/src/pages/inbounds/InboundsPage.tsx +++ b/frontend/src/pages/inbounds/InboundsPage.tsx @@ -89,6 +89,7 @@ export default function InboundsPage() { fetchError, dbInbounds, clientCount, + clientCountsPending, onlineClients, lastOnlineMap, inboundSpeed, @@ -558,7 +559,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'), @@ -796,6 +798,7 @@ export default function InboundsPage() { {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..9311889c3 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)} @@ -259,8 +280,6 @@ export default function IndexPage() { )} data={history.series.cpu} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -278,8 +297,6 @@ export default function IndexPage() { )} data={history.series.mem} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -298,8 +315,6 @@ export default function IndexPage() { )} data={history.series.swap} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} /> } @@ -317,8 +332,6 @@ export default function IndexPage() { )} data={history.series.diskUsage} isMobile={isMobile} - range={historyRange} - onRangeChange={setHistoryRange} />
@@ -329,8 +342,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 ( -