feat(groups): assign host rules from client groups (#7064)

Host rules could only be given to clients one by one, so giving a set of customers their own endpoints meant editing every client. A client group can now carry host rules, chosen when the group is created, from its edit dialog or from a quick-assign action on the Groups page.

A subscription resolves a client's hosts in this order: the client's own host rules, then the host rules of its group, then the inbound's default pool. A group whose bound rules are all disabled or excluded from the requested format renders nothing for that inbound instead of falling back to the default pool. Binding a rule to a group narrows what its members get; other clients still see that rule in the default pool.

Group names are now matched case-insensitively. On upgrade, labels that differ only in case (VIP and vip) are merged into one group, the first by name order.

Adds POST /panel/api/clients/groups/:name/hosts and an optional hostGroupIds on group create and rename.
This commit is contained in:
Nethmina Yasas
2026-11-25 17:51:43 +05:30
committed by GitHub
parent 4013219698
commit e95d17a7db
46 changed files with 2222 additions and 285 deletions
+3 -3
View File
@@ -156,12 +156,12 @@ jobs:
- name: PostgreSQL schema and migration tests
run: |
set -o pipefail
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres|TestMigrate_LegacyBooleanVerifyPeerCertByNameIsBlanked_Postgres|TestClientKeepAlivePostgresMigrationPreservesLegacyScalars|TestPostgresModelSettled_TracksSchemaPresence)$' -count=1 -v | tee /tmp/postgres-schema.log
go test ./internal/database -run '^(TestHostAutoMigrateCreatesColumns_Postgres|TestMigrate_Postgres|TestClientWeeklyRenewMigration_Postgres|TestMigrate_LegacyBooleanVerifyPeerCertByNameIsBlanked_Postgres|TestClientKeepAlivePostgresMigrationPreservesLegacyScalars|TestPostgresModelSettled_TracksSchemaPresence|TestEnsureClientGroupRows_Postgres)$' -count=1 -v | tee /tmp/postgres-schema.log
# All must pass. Counting, not SKIP-matching: renaming a test would
# otherwise leave this step green while testing nothing.
passed=$(grep -c -- '^--- PASS' /tmp/postgres-schema.log || true)
if [ "$passed" -lt 6 ]; then
echo "expected at least 6 passing PostgreSQL schema tests, got $passed" >&2
if [ "$passed" -lt 7 ]; then
echo "expected at least 7 passing PostgreSQL schema tests, got $passed" >&2
exit 1
fi
+45 -28
View File
@@ -228,27 +228,36 @@ _openapi:
clients.
url: '#zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-its-quota-had-disabled-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-a-client-disabled-by-hand-stays-disabled-returns-the-count-of-successfully-reset-clients'
- depth: 2
title: List all client groups with their member counts. Merges persisted groups
(rows in client_groups, including empty placeholders) with the distinct
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: '#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive'
title: List all client groups with their member counts and the host groups bound
to each. Merges persisted groups (rows in client_groups, including empty
placeholders) with the distinct group_name values currently set on
clients. Sorted alphabetically (case-insensitive).
url: '#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive'
- depth: 2
title: Replace the host groups attached to a client group. Clients in this group
receive the bound host groups instead of the inbound default host pool;
other clients are unaffected. An empty array clears the bindings.
Returns the saved host group IDs.
url: '#replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids'
- depth: 2
title: Return just the email list of clients that currently belong to the given
group. Useful for fanning a single bulk action over an entire group
without round-tripping the full client list.
url: '#return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list'
- depth: 2
title: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: '#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists'
title: Create a new group, optionally with host rules bound to it. The group
becomes selectable in client forms and the filter drawer even before any
client is added to it. Host group IDs are validated before the group is
created. Errors if a group with the same name already exists.
url: '#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists'
- depth: 2
title: Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: '#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated'
title: Rename a group and optionally replace its host rules in one transaction.
The new name is applied to the client_groups row AND propagated to every
matching client (both clients.group_name and the client entry inside
every owning inbound's settings JSON). Omit hostGroupIds to leave the
bindings unchanged; send an empty array to clear them. Returns the
number of clients whose label was updated.
url: '#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated'
- depth: 2
title: Remove a group. Deletes the client_groups row and clears the group label
from every matching client (both clients.group_name and the inbound
@@ -562,24 +571,32 @@ _openapi:
disabled by hand stays disabled. Returns the count of successfully
reset clients.
id: zero-updown-counters-for-many-clients-in-one-call-loops-the-single-reset-path-so-each-client-its-quota-had-disabled-is-re-enabled-across-its-attached-inbounds-and-pushed-to-xrayremote-nodes-a-client-disabled-by-hand-stays-disabled-returns-the-count-of-successfully-reset-clients
- content: List all client groups with their member counts. Merges persisted
groups (rows in client_groups, including empty placeholders) with the
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: List all client groups with their member counts and the host groups
bound to each. Merges persisted groups (rows in client_groups,
including empty placeholders) with the distinct group_name values
currently set on clients. Sorted alphabetically (case-insensitive).
id: list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: Replace the host groups attached to a client group. Clients in this
group receive the bound host groups instead of the inbound default
host pool; other clients are unaffected. An empty array clears the
bindings. Returns the saved host group IDs.
id: replace-the-host-groups-attached-to-a-client-group-clients-in-this-group-receive-the-bound-host-groups-instead-of-the-inbound-default-host-pool-other-clients-are-unaffected-an-empty-array-clears-the-bindings-returns-the-saved-host-group-ids
- content: Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
group without round-tripping the full client list.
id: return-just-the-email-list-of-clients-that-currently-belong-to-the-given-group-useful-for-fanning-a-single-bulk-action-over-an-entire-group-without-round-tripping-the-full-client-list
- content: Create a new empty (placeholder) group. The group becomes selectable in
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
id: create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
- content: Rename a group. The new name is applied to the client_groups row AND
- content: Create a new group, optionally with host rules bound to it. The group
becomes selectable in client forms and the filter drawer even before
any client is added to it. Host group IDs are validated before the
group is created. Errors if a group with the same name already exists.
id: create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: Rename a group and optionally replace its host rules in one
transaction. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
client entry inside every owning inbound's settings JSON). Omit
hostGroupIds to leave the bindings unchanged; send an empty array to
clear them. Returns the number of clients whose label was updated.
id: rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
inbound settings JSON). The clients themselves are NOT deleted — use
@@ -866,7 +883,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
</>
);
}
@@ -216,7 +216,7 @@ _openapi:
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- depth: 2
title: >-
Return just the email list of clients that currently belong to the given
@@ -230,7 +230,7 @@ _openapi:
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- depth: 2
title: >-
Rename a group. The new name is applied to the client_groups row AND
@@ -238,7 +238,7 @@ _openapi:
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- depth: 2
title: >-
Remove a group. Deletes the client_groups row and clears the group label
@@ -514,7 +514,7 @@ _openapi:
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
@@ -526,14 +526,14 @@ _openapi:
in client forms and the filter drawer even before any client is added
to it. Errors if a group with the same name already exists.
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: >-
Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: >-
Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
@@ -216,7 +216,7 @@ _openapi:
group_name values currently set on clients. Sorted alphabetically
(case-insensitive).
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- depth: 2
title: >-
Return just the email list of clients that currently belong to the given
@@ -230,7 +230,7 @@ _openapi:
client forms and the filter drawer even before any client is added to
it. Errors if a group with the same name already exists.
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- depth: 2
title: >-
Rename a group. The new name is applied to the client_groups row AND
@@ -238,7 +238,7 @@ _openapi:
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- depth: 2
title: >-
Remove a group. Deletes the client_groups row and clears the group label
@@ -514,7 +514,7 @@ _openapi:
distinct group_name values currently set on clients. Sorted
alphabetically (case-insensitive).
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
Return just the email list of clients that currently belong to the
given group. Useful for fanning a single bulk action over an entire
@@ -526,14 +526,14 @@ _openapi:
in client forms and the filter drawer even before any client is added
to it. Errors if a group with the same name already exists.
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: >-
Rename a group. The new name is applied to the client_groups row AND
propagated to every matching client (both clients.group_name and the
client entry inside every owning inbound's settings JSON) in a single
transaction. Returns the number of clients whose label was updated.
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: >-
Remove a group. Deletes the client_groups row and clears the group
label from every matching client (both clients.group_name and the
@@ -175,7 +175,7 @@ _openapi:
列出所有客户端分组及其成员数量。将持久化分组(client_groups 中的记录,包括空占位符)
与当前在客户端上设置的去重后的 group_name 值合并。按字母顺序排序(不区分大小写)。
url: >-
#list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
#list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- depth: 2
title: >-
仅返回当前属于指定分组的客户端 email 列表。适用于将单个批量操作扇出到整个分组,而无需
@@ -187,14 +187,14 @@ _openapi:
创建一个新的空(占位)分组。即使尚未向其添加任何客户端,该分组也会在客户端表单和筛选
抽屉中变为可选。若已存在同名分组,则报错。
url: >-
#create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
#create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- depth: 2
title: >-
重命名分组。新名称会应用到 client_groups 记录,并在单个事务中传播到每个匹配的客户端
(包括 clients.group_name 以及每个所属入站的 settings JSON 内的客户端条目)。返回
标签被更新的客户端数量。
url: >-
#rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
#rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- depth: 2
title: >-
移除分组。删除 client_groups 记录,并从每个匹配的客户端清除分组标签(包括
@@ -412,7 +412,7 @@ _openapi:
列出所有客户端分组及其成员数量。将持久化分组(client_groups 中的记录,包括空占位符)
与当前在客户端上设置的去重后的 group_name 值合并。按字母顺序排序(不区分大小写)。
id: >-
list-all-client-groups-with-their-member-counts-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
list-all-client-groups-with-their-member-counts-and-the-host-groups-bound-to-each-merges-persisted-groups-rows-in-client_groups-including-empty-placeholders-with-the-distinct-group_name-values-currently-set-on-clients-sorted-alphabetically-case-insensitive
- content: >-
仅返回当前属于指定分组的客户端 email 列表。适用于将单个批量操作扇出到整个分组,而无需
往返获取完整的客户端列表。
@@ -422,13 +422,13 @@ _openapi:
创建一个新的空(占位)分组。即使尚未向其添加任何客户端,该分组也会在客户端表单和筛选
抽屉中变为可选。若已存在同名分组,则报错。
id: >-
create-a-new-empty-placeholder-group-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-errors-if-a-group-with-the-same-name-already-exists
create-a-new-group-optionally-with-host-rules-bound-to-it-the-group-becomes-selectable-in-client-forms-and-the-filter-drawer-even-before-any-client-is-added-to-it-host-group-ids-are-validated-before-the-group-is-created-errors-if-a-group-with-the-same-name-already-exists
- content: >-
重命名分组。新名称会应用到 client_groups 记录,并在单个事务中传播到每个匹配的客户端
(包括 clients.group_name 以及每个所属入站的 settings JSON 内的客户端条目)。返回
标签被更新的客户端数量。
id: >-
rename-a-group-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-in-a-single-transaction-returns-the-number-of-clients-whose-label-was-updated
rename-a-group-and-optionally-replace-its-host-rules-in-one-transaction-the-new-name-is-applied-to-the-client_groups-row-and-propagated-to-every-matching-client-both-clientsgroup_name-and-the-client-entry-inside-every-owning-inbounds-settings-json-omit-hostgroupids-to-leave-the-bindings-unchanged-send-an-empty-array-to-clear-them-returns-the-number-of-clients-whose-label-was-updated
- content: >-
移除分组。删除 client_groups 记录,并从每个匹配的客户端清除分组标签(包括
clients.group_name 以及入站 settings JSON)。客户端本身不会被删除——如需删除请先按
+83 -7
View File
@@ -11801,7 +11801,7 @@
"tags": [
"Clients"
],
"summary": "List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).",
"summary": "List all client groups with their member counts and the host groups bound to each. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).",
"operationId": "get_panel_api_clients_groups",
"responses": {
"200": {
@@ -11824,12 +11824,18 @@
"success": true,
"obj": [
{
"id": 1,
"name": "customer-a",
"clientCount": 5
"clientCount": 5,
"hostGroupIds": [
"cdn-front"
]
},
{
"id": 2,
"name": "internal",
"clientCount": 0
"clientCount": 0,
"hostGroupIds": []
}
]
}
@@ -11839,6 +11845,70 @@
}
}
},
"/panel/api/clients/groups/{name}/hosts": {
"post": {
"tags": [
"Clients"
],
"summary": "Replace the host groups attached to a client group. Clients in this group receive the bound host groups instead of the inbound default host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs.",
"operationId": "post_panel_api_clients_groups_name_hosts",
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"description": "Group name (URL-encoded).",
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
},
"example": {
"hostGroupIds": [
"cdn-front"
]
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": {
"hostGroupIds": [
"cdn-front"
]
}
}
}
}
}
}
}
},
"/panel/api/clients/groups/{name}/emails": {
"get": {
"tags": [
@@ -11893,7 +11963,7 @@
"tags": [
"Clients"
],
"summary": "Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists.",
"summary": "Create a new group, optionally with host rules bound to it. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Host group IDs are validated before the group is created. Errors if a group with the same name already exists.",
"operationId": "post_panel_api_clients_groups_create",
"requestBody": {
"required": true,
@@ -11903,7 +11973,10 @@
"type": "object"
},
"example": {
"name": "customer-a"
"name": "customer-a",
"hostGroupIds": [
"cdn-front"
]
}
}
}
@@ -11942,7 +12015,7 @@
"tags": [
"Clients"
],
"summary": "Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated.",
"summary": "Rename a group and optionally replace its host rules in one transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON). Omit hostGroupIds to leave the bindings unchanged; send an empty array to clear them. Returns the number of clients whose label was updated.",
"operationId": "post_panel_api_clients_groups_rename",
"requestBody": {
"required": true,
@@ -11953,7 +12026,10 @@
},
"example": {
"oldName": "customer-a",
"newName": "tier-1"
"newName": "tier-1",
"hostGroupIds": [
"cdn-front"
]
}
}
}
+83 -7
View File
@@ -11801,7 +11801,7 @@
"tags": [
"Clients"
],
"summary": "List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).",
"summary": "List all client groups with their member counts and the host groups bound to each. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).",
"operationId": "get_panel_api_clients_groups",
"responses": {
"200": {
@@ -11824,12 +11824,18 @@
"success": true,
"obj": [
{
"id": 1,
"name": "customer-a",
"clientCount": 5
"clientCount": 5,
"hostGroupIds": [
"cdn-front"
]
},
{
"id": 2,
"name": "internal",
"clientCount": 0
"clientCount": 0,
"hostGroupIds": []
}
]
}
@@ -11839,6 +11845,70 @@
}
}
},
"/panel/api/clients/groups/{name}/hosts": {
"post": {
"tags": [
"Clients"
],
"summary": "Replace the host groups attached to a client group. Clients in this group receive the bound host groups instead of the inbound default host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs.",
"operationId": "post_panel_api_clients_groups_name_hosts",
"parameters": [
{
"name": "name",
"in": "path",
"required": true,
"description": "Group name (URL-encoded).",
"schema": {
"type": "string"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object"
},
"example": {
"hostGroupIds": [
"cdn-front"
]
}
}
}
},
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
},
"example": {
"success": true,
"obj": {
"hostGroupIds": [
"cdn-front"
]
}
}
}
}
}
}
}
},
"/panel/api/clients/groups/{name}/emails": {
"get": {
"tags": [
@@ -11893,7 +11963,7 @@
"tags": [
"Clients"
],
"summary": "Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists.",
"summary": "Create a new group, optionally with host rules bound to it. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Host group IDs are validated before the group is created. Errors if a group with the same name already exists.",
"operationId": "post_panel_api_clients_groups_create",
"requestBody": {
"required": true,
@@ -11903,7 +11973,10 @@
"type": "object"
},
"example": {
"name": "customer-a"
"name": "customer-a",
"hostGroupIds": [
"cdn-front"
]
}
}
}
@@ -11942,7 +12015,7 @@
"tags": [
"Clients"
],
"summary": "Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated.",
"summary": "Rename a group and optionally replace its host rules in one transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON). Omit hostGroupIds to leave the bindings unchanged; send an empty array to clear them. Returns the number of clients whose label was updated.",
"operationId": "post_panel_api_clients_groups_rename",
"requestBody": {
"required": true,
@@ -11953,7 +12026,10 @@
},
"example": {
"oldName": "customer-a",
"newName": "tier-1"
"newName": "tier-1",
"hostGroupIds": [
"cdn-front"
]
}
}
}
+15 -6
View File
@@ -1702,9 +1702,18 @@ export const sections: readonly Section[] = [
method: 'GET',
path: '/panel/api/clients/groups',
summary:
'List all client groups with their member counts. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).',
'List all client groups with their member counts and the host groups bound to each. Merges persisted groups (rows in client_groups, including empty placeholders) with the distinct group_name values currently set on clients. Sorted alphabetically (case-insensitive).',
response:
'{\n "success": true,\n "obj": [\n { "name": "customer-a", "clientCount": 5 },\n { "name": "internal", "clientCount": 0 }\n ]\n}',
'{\n "success": true,\n "obj": [\n { "id": 1, "name": "customer-a", "clientCount": 5, "hostGroupIds": ["cdn-front"] },\n { "id": 2, "name": "internal", "clientCount": 0, "hostGroupIds": [] }\n ]\n}',
},
{
method: 'POST',
path: '/panel/api/clients/groups/:name/hosts',
summary:
'Replace the host groups attached to a client group. Clients in this group receive the bound host groups instead of the inbound default host pool; other clients are unaffected. An empty array clears the bindings. Returns the saved host group IDs.',
params: [{ name: 'name', in: 'path', type: 'string', desc: 'Group name (URL-encoded).' }],
body: '{\n "hostGroupIds": ["cdn-front"]\n}',
response: '{\n "success": true,\n "obj": {\n "hostGroupIds": ["cdn-front"]\n }\n}',
},
{
method: 'GET',
@@ -1718,16 +1727,16 @@ export const sections: readonly Section[] = [
method: 'POST',
path: '/panel/api/clients/groups/create',
summary:
'Create a new empty (placeholder) group. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Errors if a group with the same name already exists.',
body: '{\n "name": "customer-a"\n}',
'Create a new group, optionally with host rules bound to it. The group becomes selectable in client forms and the filter drawer even before any client is added to it. Host group IDs are validated before the group is created. Errors if a group with the same name already exists.',
body: '{\n "name": "customer-a",\n "hostGroupIds": ["cdn-front"]\n}',
response: '{\n "success": true,\n "obj": {\n "name": "customer-a"\n }\n}',
},
{
method: 'POST',
path: '/panel/api/clients/groups/rename',
summary:
"Rename a group. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON) in a single transaction. Returns the number of clients whose label was updated.",
body: '{\n "oldName": "customer-a",\n "newName": "tier-1"\n}',
"Rename a group and optionally replace its host rules in one transaction. The new name is applied to the client_groups row AND propagated to every matching client (both clients.group_name and the client entry inside every owning inbound's settings JSON). Omit hostGroupIds to leave the bindings unchanged; send an empty array to clear them. Returns the number of clients whose label was updated.",
body: '{\n "oldName": "customer-a",\n "newName": "tier-1",\n "hostGroupIds": ["cdn-front"]\n}',
response: '{\n "success": true,\n "obj": {\n "affected": 5\n }\n}',
},
{
@@ -0,0 +1,63 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal, Typography } from 'antd';
import type { GroupSummary } from '@/schemas/client';
import HostGroupSelect from './HostGroupSelect';
interface GroupHostRulesModalProps {
open: boolean;
group: GroupSummary | null;
onOpenChange: (open: boolean) => void;
save: (name: string, hostGroupIds: string[]) => Promise<boolean>;
}
export default function GroupHostRulesModal({
open,
group,
onOpenChange,
save,
}: GroupHostRulesModalProps) {
const { t } = useTranslation();
const [loadingSave, setLoadingSave] = useState(false);
const openGroupKey = open ? (group?.name ?? null) : null;
const [syncedGroupKey, setSyncedGroupKey] = useState(openGroupKey);
const [value, setValue] = useState<string[]>(group?.hostGroupIds ?? []);
// Reset during render so the first open frame already shows the saved set.
if (openGroupKey !== syncedGroupKey) {
setSyncedGroupKey(openGroupKey);
if (open) {
setValue(group?.hostGroupIds ?? []);
setLoadingSave(false);
}
}
async function onOk() {
if (!group || loadingSave) return;
setLoadingSave(true);
try {
if (await save(group.name, value)) onOpenChange(false);
} finally {
setLoadingSave(false);
}
}
return (
<Modal
open={open}
title={t('pages.groups.hostRules')}
okText={t('save')}
cancelText={t('cancel')}
confirmLoading={loadingSave}
onOk={onOk}
onCancel={() => onOpenChange(false)}
destroyOnHidden
>
<Typography.Paragraph type="secondary" style={{ marginBottom: 12 }}>
{t('pages.groups.hostRulesHint')}
</Typography.Paragraph>
<HostGroupSelect value={value} onChange={setValue} />
</Modal>
);
}
+141 -41
View File
@@ -29,6 +29,7 @@ import {
EditOutlined,
LinkOutlined,
MoreOutlined,
PartitionOutlined,
PieChartOutlined,
PlusOutlined,
RetweetOutlined,
@@ -56,6 +57,7 @@ import {
type GroupSummary,
} from '@/schemas/client';
import { parseMsg } from '@/utils/zodValidate';
import HostGroupSelect from './HostGroupSelect';
const ClientRecordListSchema = z
.array(ClientRecordSchema)
@@ -66,9 +68,16 @@ const SubLinksModal = lazy(() => import('../clients/SubLinksModal'));
const ClientBulkAdjustModal = lazy(() => import('../clients/ClientBulkAdjustModal'));
const GroupAddClientsModal = lazy(() => import('./GroupAddClientsModal'));
const GroupRemoveClientsModal = lazy(() => import('./GroupRemoveClientsModal'));
const GroupHostRulesModal = lazy(() => import('./GroupHostRulesModal'));
const JSON_HEADERS = { headers: { 'Content-Type': 'application/json' } } as const;
function sameIds(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false;
const ids = new Set(a);
return b.every((id) => ids.has(id));
}
async function fetchGroups(): Promise<GroupSummary[]> {
const msg = await HttpUtil.get('/panel/api/clients/groups', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load groups');
@@ -117,15 +126,15 @@ export default function GroupsPage() {
}, [queryClient]);
const createMut = useMutation({
mutationFn: (body: { name: string }) =>
mutationFn: (body: { name: string; hostGroupIds: string[] }) =>
HttpUtil.post('/panel/api/clients/groups/create', body, JSON_HEADERS),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const renameMut = useMutation({
mutationFn: (body: { oldName: string; newName: string }) =>
const editMut = useMutation({
mutationFn: (body: { oldName: string; newName: string; hostGroupIds: string[] }) =>
HttpUtil.post('/panel/api/clients/groups/rename', body, JSON_HEADERS),
onSuccess: (msg) => {
if (msg?.success) invalidate();
@@ -148,14 +157,30 @@ export default function GroupsPage() {
},
});
const groupHostsMut = useMutation({
mutationFn: (body: { name: string; hostGroupIds: string[] }) =>
HttpUtil.post(
`/panel/api/clients/groups/${encodeURIComponent(body.name)}/hosts`,
{ hostGroupIds: body.hostGroupIds },
JSON_HEADERS,
),
onSuccess: (msg) => {
if (msg?.success) invalidate();
},
});
const [createOpen, setCreateOpen] = useState(false);
const [createName, setCreateName] = useState('');
const [createHostGroupIds, setCreateHostGroupIds] = useState<string[]>([]);
const [renameOpen, setRenameOpen] = useState(false);
const [renameTarget, setRenameTarget] = useState<GroupSummary | null>(null);
const [renameValue, setRenameValue] = useState('');
const [editOpen, setEditOpen] = useState(false);
const [editTarget, setEditTarget] = useState<GroupSummary | null>(null);
const [editName, setEditName] = useState('');
const [editHostGroupIds, setEditHostGroupIds] = useState<string[]>([]);
const [subLinksOpen, setSubLinksOpen] = useState(false);
const [hostRulesOpen, setHostRulesOpen] = useState(false);
const [hostRulesGroup, setHostRulesGroup] = useState<GroupSummary | null>(null);
const [adjustOpen, setAdjustOpen] = useState(false);
const [addClientsOpen, setAddClientsOpen] = useState(false);
const [removeClientsOpen, setRemoveClientsOpen] = useState(false);
@@ -189,6 +214,7 @@ export default function GroupsPage() {
function openCreate() {
setCreateName('');
setCreateHostGroupIds([]);
setCreateOpen(true);
}
@@ -199,39 +225,50 @@ export default function GroupsPage() {
messageApi.error(t('pages.groups.renameCollision', { name }));
return;
}
const msg = await createMut.mutateAsync({ name });
const msg = await createMut.mutateAsync({ name, hostGroupIds: createHostGroupIds });
if (msg?.success) {
messageApi.success(t('pages.groups.createSuccess', { name }));
setCreateOpen(false);
}
}
function openRename(g: GroupSummary) {
setRenameTarget(g);
setRenameValue(g.name);
setRenameOpen(true);
function openEdit(g: GroupSummary) {
setEditTarget(g);
setEditName(g.name);
setEditHostGroupIds(g.hostGroupIds ?? []);
setEditOpen(true);
}
async function confirmRename() {
if (!renameTarget) return;
const next = renameValue.trim();
if (!next || next === renameTarget.name) {
setRenameOpen(false);
return;
}
async function confirmEdit() {
if (!editTarget) return;
const next = editName.trim();
if (!next) return;
const nameChanged = next !== editTarget.name;
if (
groups.some(
(g) => g.name.toLowerCase() === next.toLowerCase() && g.name !== renameTarget.name,
)
nameChanged &&
groups.some((g) => g.name !== editTarget.name && g.name.toLowerCase() === next.toLowerCase())
) {
messageApi.error(t('pages.groups.renameCollision', { name: next }));
return;
}
const msg = await renameMut.mutateAsync({ oldName: renameTarget.name, newName: next });
const previousHostGroupIds = editTarget.hostGroupIds ?? [];
if (!nameChanged && sameIds(previousHostGroupIds, editHostGroupIds)) {
setEditOpen(false);
return;
}
const msg = await editMut.mutateAsync({
oldName: editTarget.name,
newName: next,
hostGroupIds: editHostGroupIds,
});
if (msg?.success) {
const affected = (msg.obj as { affected?: number } | undefined)?.affected ?? 0;
messageApi.success(t('pages.groups.renameSuccess', { count: affected }));
setRenameOpen(false);
if (nameChanged) {
messageApi.success(t('pages.groups.renameSuccess', { count: affected }));
} else {
messageApi.success(t('pages.groups.hostRulesSaved', { name: next }));
}
setEditOpen(false);
}
}
@@ -287,6 +324,21 @@ export default function GroupsPage() {
setAddClientsOpen(true);
}
function openHostRulesFor(g: GroupSummary) {
setHostRulesGroup(g);
setHostRulesOpen(true);
}
async function saveHostRules(name: string, hostGroupIds: string[]): Promise<boolean> {
const msg = await groupHostsMut.mutateAsync({ name, hostGroupIds });
if (msg?.success) {
messageApi.success(t('pages.groups.hostRulesSaved', { name }));
return true;
}
messageApi.error(msg?.msg || t('somethingWentWrong'));
return false;
}
function openRemoveClientsFor(g: GroupSummary) {
if (!g.clientCount) {
messageApi.info(t('pages.groups.emptyForAction'));
@@ -380,10 +432,16 @@ export default function GroupsPage() {
onClick: () => openAddClientsFor(row),
},
{
key: 'rename',
key: 'hostRules',
icon: <PartitionOutlined aria-hidden />,
label: t('pages.groups.hostRules'),
onClick: () => openHostRulesFor(row),
},
{
key: 'edit',
icon: <EditOutlined aria-hidden />,
label: t('pages.groups.rename'),
onClick: () => openRename(row),
label: t('pages.groups.editGroup'),
onClick: () => openEdit(row),
},
{ type: 'divider' },
{
@@ -416,7 +474,7 @@ export default function GroupsPage() {
{
title: t('pages.clients.actions'),
key: 'actions',
width: 90,
width: 130,
render: (_v, row) => (
<Space size={4}>
<Dropdown trigger={['click']} menu={{ items: rowActions(row) }}>
@@ -428,14 +486,24 @@ export default function GroupsPage() {
icon={<MoreOutlined aria-hidden />}
/>
</Dropdown>
<Tooltip title={t('pages.groups.rename')}>
<Tooltip title={t('pages.groups.hostRules')}>
<Button
aria-label={t('pages.groups.rename')}
aria-label={`${t('pages.groups.hostRules')}: ${row.name}`}
size="small"
type="text"
style={{ fontSize: 16 }}
icon={<PartitionOutlined aria-hidden />}
onClick={() => openHostRulesFor(row)}
/>
</Tooltip>
<Tooltip title={t('pages.groups.editGroup')}>
<Button
aria-label={`${t('pages.groups.editGroup')}: ${row.name}`}
size="small"
type="text"
style={{ fontSize: 16 }}
icon={<EditOutlined aria-hidden />}
onClick={() => openRename(row)}
onClick={() => openEdit(row)}
/>
</Tooltip>
</Space>
@@ -458,6 +526,23 @@ export default function GroupsPage() {
width: 180,
render: (count: number) => <span>{count || 0}</span>,
},
{
title: t('pages.groups.hostRules'),
dataIndex: 'hostGroupIds',
key: 'hostGroupIds',
width: 140,
render: (ids: string[] | null | undefined, row) => (
<Button
aria-label={`${t('pages.groups.hostRules')}: ${row.name}`}
type="link"
size="small"
style={{ paddingInline: 0 }}
onClick={() => openHostRulesFor(row)}
>
{ids?.length || 0}
</Button>
),
},
{
title: t('pages.groups.upload'),
dataIndex: 'up',
@@ -623,33 +708,48 @@ export default function GroupsPage() {
autoFocus
/>
</Form.Item>
<Form.Item label={t('pages.groups.hostRules')} extra={t('pages.groups.hostRulesHint')}>
<HostGroupSelect value={createHostGroupIds} onChange={setCreateHostGroupIds} />
</Form.Item>
</Form>
</Modal>
<Modal
open={renameOpen}
title={renameTarget ? t('pages.groups.renameTitle', { name: renameTarget.name }) : ''}
open={editOpen}
title={editTarget ? t('pages.groups.editGroupTitle', { name: editTarget.name }) : ''}
okText={t('save')}
cancelText={t('cancel')}
confirmLoading={renameMut.isPending}
onCancel={() => setRenameOpen(false)}
onOk={confirmRename}
confirmLoading={editMut.isPending}
onCancel={() => setEditOpen(false)}
onOk={confirmEdit}
destroyOnHidden
>
<Form layout="vertical">
<Form.Item label={t('pages.groups.name')} htmlFor={`${uid}-rename-name`}>
<Form.Item label={t('pages.groups.name')} htmlFor={`${uid}-edit-name`}>
<Input
id={`${uid}-rename-name`}
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onPressEnter={confirmRename}
id={`${uid}-edit-name`}
value={editName}
onChange={(e) => setEditName(e.target.value)}
onPressEnter={confirmEdit}
placeholder={t('pages.clients.groupPlaceholder')}
autoFocus
/>
</Form.Item>
<Form.Item label={t('pages.groups.hostRules')} extra={t('pages.groups.hostRulesHint')}>
<HostGroupSelect value={editHostGroupIds} onChange={setEditHostGroupIds} />
</Form.Item>
</Form>
</Modal>
<LazyMount when={hostRulesOpen}>
<GroupHostRulesModal
open={hostRulesOpen}
group={hostRulesGroup}
onOpenChange={setHostRulesOpen}
save={saveHostRules}
/>
</LazyMount>
<LazyMount when={subLinksOpen}>
<SubLinksModal
open={subLinksOpen}
@@ -0,0 +1,38 @@
import { Select } from 'antd';
import { useTranslation } from 'react-i18next';
import { useHostsQuery } from '@/api/queries/useHostsQuery';
import { selectTagRender } from '@/components/form';
interface HostGroupSelectProps {
value: string[];
onChange: (value: string[]) => void;
ariaLabel?: string;
}
// Shared host-rule picker for the group create, edit, and quick-assign dialogs.
export default function HostGroupSelect({ value, onChange, ariaLabel }: HostGroupSelectProps) {
const { t } = useTranslation();
const { hosts, loading } = useHostsQuery();
// /hosts/list returns one grouped entry per groupId, so option values are unique.
const options = hosts.map((host) => ({
value: host.groupId,
label: host.remark || host.groupId,
}));
return (
<Select
mode="multiple"
allowClear
loading={loading}
value={value}
onChange={onChange}
options={options}
optionFilterProp="label"
aria-label={ariaLabel ?? t('pages.groups.hostRules')}
tagRender={selectTagRender}
placeholder={t('pages.groups.hostRulesPlaceholder')}
style={{ width: '100%' }}
/>
);
}
+5
View File
@@ -289,8 +289,13 @@ export const ActiveInboundsByNodeSchema = z
.transform((v) => v ?? {});
export const GroupSummarySchema = z.object({
id: z.number(),
name: z.string(),
clientCount: z.number(),
hostGroupIds: z
.array(z.string())
.nullish()
.transform((v) => v ?? []),
trafficUsed: z
.number()
.nullable()
+91
View File
@@ -0,0 +1,91 @@
package database
import (
"errors"
"sort"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"gorm.io/gorm"
)
// EnsureClientGroup returns the canonical group row for name, creating it if
// absent. Matching is case-insensitive so casing cannot create a second group.
func EnsureClientGroup(tx *gorm.DB, name string) (*model.ClientGroup, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, nil
}
if tx == nil {
tx = db
}
var group model.ClientGroup
err := tx.Where("LOWER(name) = LOWER(?)", name).Order("id ASC").First(&group).Error
if err == nil {
return &group, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
group = model.ClientGroup{Name: name}
if err := tx.Create(&group).Error; err != nil {
// A concurrent writer may have created it between the lookup and insert.
var existing model.ClientGroup
if e := tx.Where("LOWER(name) = LOWER(?)", name).Order("id ASC").First(&existing).Error; e == nil {
return &existing, nil
}
return nil, err
}
return &group, nil
}
// PruneHostGroupClientGroups drops bindings whose host group no longer has any
// hosts row (e.g. the inbound was deleted). Idempotent; runs on every start.
func PruneHostGroupClientGroups() error {
return PruneHostGroupClientGroupsTx(db)
}
// PruneHostGroupClientGroupsTx drops bindings to rules whose hosts are gone, so
// deleting an inbound cannot leave a group bound to a rule nobody can select.
func PruneHostGroupClientGroupsTx(tx *gorm.DB) error {
return tx.Exec(`DELETE FROM host_group_client_groups
WHERE host_group_id NOT IN (SELECT DISTINCT group_id FROM hosts)
OR client_group_id NOT IN (SELECT id FROM client_groups)`).Error
}
// EnsureClientGroupRows repairs group labels that have no client_groups row and
// rewrites case variants to the canonical row's spelling. Idempotent.
func EnsureClientGroupRows() error {
var names []string
if err := db.Model(&model.ClientRecord{}).
Where("TRIM(COALESCE(group_name, '')) <> ''").
Distinct().Pluck("group_name", &names).Error; err != nil {
return err
}
if len(names) == 0 {
return nil
}
sort.Strings(names)
return db.Transaction(func(tx *gorm.DB) error {
for _, raw := range names {
name := strings.TrimSpace(raw)
if name == "" {
continue
}
group, err := EnsureClientGroup(tx, name)
if err != nil {
return err
}
if group == nil || group.Name == raw {
continue
}
if err := tx.Model(&model.ClientRecord{}).
Where("group_name = ?", raw).
UpdateColumn("group_name", group.Name).Error; err != nil {
return err
}
}
return nil
})
}
+123
View File
@@ -0,0 +1,123 @@
package database
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestEnsureClientGroupRows_CreatesMissingAndCanonicalizes(t *testing.T) {
initMigrateDB(t)
db := GetDB()
if err := db.Create(&model.ClientRecord{Email: "a@x", Group: "VIP", Enable: true}).Error; err != nil {
t.Fatalf("create client a: %v", err)
}
if err := db.Create(&model.ClientRecord{Email: "b@x", Group: "vip", Enable: true}).Error; err != nil {
t.Fatalf("create client b: %v", err)
}
if err := EnsureClientGroupRows(); err != nil {
t.Fatalf("EnsureClientGroupRows: %v", err)
}
var groups []model.ClientGroup
if err := db.Order("id ASC").Find(&groups).Error; err != nil {
t.Fatalf("load groups: %v", err)
}
if len(groups) != 1 || groups[0].Name != "VIP" {
t.Fatalf("groups = %+v, want one canonical VIP", groups)
}
var clients []model.ClientRecord
if err := db.Order("email ASC").Find(&clients).Error; err != nil {
t.Fatalf("load clients: %v", err)
}
for _, client := range clients {
if client.Group != "VIP" {
t.Fatalf("client %s group = %q, want VIP", client.Email, client.Group)
}
}
if err := EnsureClientGroupRows(); err != nil {
t.Fatalf("second EnsureClientGroupRows: %v", err)
}
var count int64
if err := db.Model(&model.ClientGroup{}).Count(&count).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if count != 1 {
t.Fatalf("second run created a duplicate: %d", count)
}
}
func TestEnsureClientGroupRows_UpgradeExistingDB(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "x-ui.db")
if err := InitDB(dbPath); err != nil {
t.Fatalf("InitDB: %v", err)
}
if err := GetDB().Create(&model.ClientRecord{Email: "legacy@x", Group: "Legacy", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := CloseDB(); err != nil {
t.Fatalf("CloseDB: %v", err)
}
if err := InitDB(dbPath); err != nil {
t.Fatalf("reopen InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
var group model.ClientGroup
if err := GetDB().Where("name = ?", "Legacy").First(&group).Error; err != nil {
t.Fatalf("reopen did not create the missing group row: %v", err)
}
}
func TestPruneHostGroupClientGroups(t *testing.T) {
initMigrateDB(t)
db := GetDB()
inbound := seedInboundWithStream(t, "prune", 4599, `{"network":"tcp","security":"none"}`)
if err := db.Create(&model.Host{GroupId: "live", InboundId: inbound.Id, Remark: "L", Address: "live.example.com"}).Error; err != nil {
t.Fatalf("create host: %v", err)
}
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
for _, hostGroup := range []string{"live", "gone"} {
if err := db.Create(&model.HostGroupClientGroup{HostGroupId: hostGroup, ClientGroupId: group.Id}).Error; err != nil {
t.Fatalf("create binding %s: %v", hostGroup, err)
}
}
if err := PruneHostGroupClientGroups(); err != nil {
t.Fatalf("PruneHostGroupClientGroups: %v", err)
}
var ids []string
if err := db.Model(&model.HostGroupClientGroup{}).Pluck("host_group_id", &ids).Error; err != nil {
t.Fatalf("load bindings: %v", err)
}
if len(ids) != 1 || ids[0] != "live" {
t.Fatalf("bindings = %v, want only live", ids)
}
}
func TestEnsureClientGroupRows_Postgres(t *testing.T) {
if strings.TrimSpace(os.Getenv("XUI_DB_DSN")) == "" || os.Getenv("XUI_DB_TYPE") != "postgres" {
t.Skip("set XUI_DB_TYPE=postgres and XUI_DB_DSN to run the postgres test")
}
if err := InitDB(""); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
GetDB().Exec("TRUNCATE TABLE clients, client_groups RESTART IDENTITY CASCADE")
if err := GetDB().Create(&model.ClientRecord{Email: "pg@x", Group: "PgGroup", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := EnsureClientGroupRows(); err != nil {
t.Fatalf("EnsureClientGroupRows: %v", err)
}
var group model.ClientGroup
if err := GetDB().Where("name = ?", "PgGroup").First(&group).Error; err != nil {
t.Fatalf("group not created: %v", err)
}
}
+8
View File
@@ -77,6 +77,7 @@ func allModels() []any {
&model.ClientHwid{},
&model.ClientExternalLink{},
&model.ClientGroup{},
&model.HostGroupClientGroup{},
&model.InboundFallback{},
&model.Host{},
&model.HostTombstone{},
@@ -1770,6 +1771,13 @@ func runSeeders(isUsersEmpty bool) error {
return err
}
if err := EnsureClientGroupRows(); err != nil {
return err
}
if err := PruneHostGroupClientGroups(); err != nil {
return err
}
// Self-gated on the "MtprotoSecretsToClients" row.
if err := seedMtprotoSecretsToClients(); err != nil {
return err
+1
View File
@@ -51,6 +51,7 @@ func migrationModels() []any {
&model.ClientHwid{},
&model.ClientExternalLink{},
&model.ClientGroup{},
&model.HostGroupClientGroup{},
&model.InboundFallback{},
&model.Host{},
&model.HostTombstone{},
+9
View File
@@ -1129,6 +1129,15 @@ type ClientGroup struct {
func (ClientGroup) TableName() string { return "client_groups" }
// HostGroupClientGroup binds a host group (hosts.group_id) to a client group.
// Rows added later to the host group inherit the binding; no FK cascade.
type HostGroupClientGroup struct {
HostGroupId string `json:"hostGroupId" gorm:"column:host_group_id;primaryKey"`
ClientGroupId int `json:"clientGroupId" gorm:"column:client_group_id;primaryKey;index"`
}
func (HostGroupClientGroup) TableName() string { return "host_group_client_groups" }
// MarshalJSON emits the reverse column as a nested JSON object rather than an
// escaped JSON-text string, matching the same convention Inbound uses for its
// JSON-text columns. Empty storage renders as null.
+2 -2
View File
@@ -91,7 +91,7 @@ func (s *SubClashService) getClash(subId string, host string, legacy bool) (stri
continue
}
if subReq.hostsFirst {
variants, closed := subReq.clientHostVariants(inbound, client, "clash")
variants, closed := subReq.selectHostVariants(inbound, client, "clash")
hasBoundClosed = hasBoundClosed || closed
for _, variant := range variants {
render := func() []map[string]any {
@@ -102,7 +102,7 @@ func (s *SubClashService) getClash(subId string, host string, legacy bool) (stri
continue
}
effective := inbound
if effectiveEps, bound := subReq.clientHostEndpoints(inbound, client, "clash", baseEps); bound {
if effectiveEps, bound := subReq.selectHostEndpoints(inbound, client, "clash", baseEps); bound {
if len(effectiveEps) == 0 {
hasBoundClosed = true
continue
+431
View File
@@ -0,0 +1,431 @@
package sub
import (
"fmt"
"net/url"
"reflect"
"slices"
"strings"
"testing"
"github.com/goccy/go-yaml"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func seedClientGroup(t *testing.T, name string) *model.ClientGroup {
t.Helper()
group := &model.ClientGroup{Name: name}
if err := database.GetDB().Create(group).Error; err != nil {
t.Fatalf("seed client group %s: %v", name, err)
}
return group
}
func setClientGroup(t *testing.T, email, name string) {
t.Helper()
if err := database.GetDB().Model(&model.ClientRecord{}).
Where("email = ?", email).UpdateColumn("group_name", name).Error; err != nil {
t.Fatalf("set client group %s: %v", email, err)
}
}
func bindHostGroup(t *testing.T, hostGroupID string, clientGroupID int) {
t.Helper()
if err := database.GetDB().Create(&model.HostGroupClientGroup{
HostGroupId: hostGroupID, ClientGroupId: clientGroupID,
}).Error; err != nil {
t.Fatalf("bind host group %s: %v", hostGroupID, err)
}
}
func rawEndpointSet(t *testing.T, links []string) []string {
t.Helper()
var out []string
for _, link := range links {
for _, line := range strings.Split(link, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parsed, err := url.Parse(line)
if err != nil || parsed.Hostname() == "" || parsed.Port() == "" {
continue
}
out = append(out, parsed.Hostname()+":"+parsed.Port())
}
}
slices.Sort(out)
return out
}
func jsonEndpointSet(t *testing.T, body string) []string {
t.Helper()
docs := parseSubJsonDocs(t, body)
var out []string
for _, doc := range docs {
outbounds, _ := doc["outbounds"].([]any)
for _, raw := range outbounds {
ob, _ := raw.(map[string]any)
settings, _ := ob["settings"].(map[string]any)
if address, _ := settings["address"].(string); address != "" {
if port, _ := settings["port"].(float64); port > 0 {
out = append(out, fmt.Sprintf("%s:%d", address, int(port)))
}
}
for _, key := range []string{"vnext", "servers"} {
list, _ := settings[key].([]any)
for _, peerRaw := range list {
peer, _ := peerRaw.(map[string]any)
address, _ := peer["address"].(string)
port, _ := peer["port"].(float64)
if address != "" && port > 0 {
out = append(out, fmt.Sprintf("%s:%d", address, int(port)))
}
}
}
}
}
slices.Sort(out)
return out
}
func clashEndpointSet(t *testing.T, body string) []string {
t.Helper()
var doc struct {
Proxies []struct {
Server string `yaml:"server"`
Port int `yaml:"port"`
} `yaml:"proxies"`
}
if err := yaml.Unmarshal([]byte(body), &doc); err != nil {
t.Fatalf("clash subscription: %v", err)
}
var out []string
for _, proxy := range doc.Proxies {
if proxy.Server != "" && proxy.Port > 0 {
out = append(out, fmt.Sprintf("%s:%d", proxy.Server, proxy.Port))
}
}
slices.Sort(out)
return out
}
// A client in a bound group gets only that group's hosts; every other client
// keeps the inbound's full default pool (binding is a subset, not a scope).
func TestSub_ClientGroup_ReplaceDefaultPool(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4501, 1, tcpTLSStream)
seedSubClient(t, ib, "s1", "other@e")
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "gb", group.Id)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if got := strings.Count(joined, "a.cdn.com:443"); got != 1 {
t.Fatalf("non-member must get host A once, got %d:\n%s", got, joined)
}
if got := strings.Count(joined, "b.cdn.com:443"); got != 2 {
t.Fatalf("member and non-member must both get host B, got %d:\n%s", got, joined)
}
}
// A bound group whose only host is disabled fails closed on that inbound; it
// must not fall through to the default pool.
func TestSub_ClientGroup_DisabledHostFailsClosed(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4502, 1, tcpTLSStream)
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls", IsDisabled: true})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "ga", group.Id)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
if len(links) != 0 {
t.Fatalf("closed group tier must emit no link, got: %v", links)
}
jsonBody, _, err := NewSubJsonService("", "", "", "", NewSubService("")).GetJson("s1", "req.example.com", false)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
if strings.TrimSpace(jsonBody) != "" {
t.Fatalf("closed group tier must emit no JSON outbound, got: %s", jsonBody)
}
clashBody, _, err := NewSubClashService(false, "", false, NewSubService("")).GetClash("s1", "req.example.com")
if err != nil {
t.Fatalf("GetClash: %v", err)
}
if strings.TrimSpace(clashBody) != "" {
t.Fatalf("closed group tier must emit no Clash proxy, got: %s", clashBody)
}
if panel := NewLinkProvider().LinksForClient("req.example.com", ib, "cg@e"); len(panel) != 0 {
t.Fatalf("panel links must fail closed too, got: %v", panel)
}
}
// Format exclusion is applied after tier selection: an excluded group host
// closes the tier instead of falling through to an unbound host.
func TestSub_ClientGroup_FormatExclusionFailsClosed(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4503, 1, tcpTLSStream)
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls", ExcludeFromSubTypes: []string{"raw"}})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "ga", group.Id)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
if len(links) != 0 {
t.Fatalf("excluded group tier must emit no raw link, got: %v", links)
}
jsonBody, _, err := NewSubJsonService("", "", "", "", NewSubService("")).GetJson("s1", "req.example.com", true)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
if !strings.Contains(jsonBody, "a.cdn.com") || strings.Contains(jsonBody, "b.cdn.com") {
t.Fatalf("JSON must keep the group tier, got: %s", jsonBody)
}
}
// A group binding on inbound A must not change the member's default pool on
// inbound B.
func TestSub_ClientGroup_PerInbound(t *testing.T) {
seedSubDB(t)
group := seedClientGroup(t, "VIP")
first := seedSubInbound(t, "s1", "a", 4504, 1, tcpTLSStream)
setClientGroup(t, "a@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: first.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "ga", group.Id)
second := seedSubInbound(t, "s2", "b", 4505, 1, tcpTLSStream)
setClientGroup(t, "b@e", group.Name)
seedHost(t, &model.Host{GroupId: "gb", InboundId: second.Id, SortOrder: 1, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
links, _, _, _, err := NewSubService("").GetSubs("s2", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if !strings.Contains(joined, "b.cdn.com:443") || strings.Contains(joined, "a.cdn.com:443") {
t.Fatalf("inbound B must keep its default pool, got: %s", joined)
}
}
// Existing per-client bindings stay above group bindings.
func TestSub_ClientGroup_ClientBindingWins(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4506, 1, tcpTLSStream)
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
hostA := seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "gb", group.Id)
if err := database.GetDB().Model(&model.ClientRecord{}).Where("email = ?", "cg@e").
Update("client_host_rule_ids", model.EncodeClientHostRuleIds([]int{hostA.Id})).Error; err != nil {
t.Fatalf("bind client host: %v", err)
}
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if !strings.Contains(joined, "a.cdn.com:443") || strings.Contains(joined, "b.cdn.com:443") {
t.Fatalf("client binding must beat the group binding, got: %s", joined)
}
}
// Group binding is by host group, so another row added to the same group later
// is part of the member's pool without a rebind.
func TestSub_ClientGroup_RowAddedLaterInheritsBinding(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4507, 1, tcpTLSStream)
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 2, Remark: "A2", Address: "a2.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "ga", group.Id)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if !strings.Contains(joined, "a.cdn.com:443") || !strings.Contains(joined, "a2.cdn.com:443") {
t.Fatalf("both rows of the bound host group must render, got: %s", joined)
}
}
// Hosts-first mode narrows a group member to the bound variants and leaves the
// non-member on the full default pool.
func TestSub_ClientGroup_HostsFirst(t *testing.T) {
seedSubDB(t)
setHostSortMode(t, "hosts-first")
ib := seedSubInbound(t, "s1", "cg", 4508, 1, tcpTLSStream)
seedSubClient(t, ib, "s1", "other@e")
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "gb", group.Id)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if got := strings.Count(joined, "a.cdn.com:443"); got != 1 {
t.Fatalf("non-member must get A once, got %d:\n%s", got, joined)
}
if got := strings.Count(joined, "b.cdn.com:443"); got != 2 {
t.Fatalf("member and non-member must both get B, got %d:\n%s", got, joined)
}
}
// Raw, JSON and Clash must expose the same endpoint set for each subscriber.
func TestSub_ClientGroup_FormatParity(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "member-sub", "cg", 4509, 1, tcpTLSStream)
seedSubClient(t, ib, "other-sub", "other@e")
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "gb", group.Id)
for _, subID := range []string{"member-sub", "other-sub"} {
t.Run(subID, func(t *testing.T) {
base := NewSubService("")
links, _, _, _, err := base.GetSubs(subID, "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
raw := rawEndpointSet(t, links)
jsonBody, _, err := NewSubJsonService("", "", "", "", NewSubService("")).GetJson(subID, "req.example.com", true)
if err != nil {
t.Fatalf("GetJson: %v", err)
}
js := jsonEndpointSet(t, jsonBody)
clashBody, _, err := NewSubClashService(false, "", false, NewSubService("")).GetClash(subID, "req.example.com")
if err != nil {
t.Fatalf("GetClash: %v", err)
}
clash := clashEndpointSet(t, clashBody)
if !reflect.DeepEqual(raw, js) || !reflect.DeepEqual(raw, clash) {
t.Fatalf("format parity: raw=%v json=%v clash=%v", raw, js, clash)
}
})
}
}
// A group binding whose host rows live only on another inbound leaves this
// inbound on the legacy path, not on an empty group tier.
func TestSub_ClientGroup_LegacyFallbackPerInbound(t *testing.T) {
seedSubDB(t)
group := seedClientGroup(t, "VIP")
other := seedSubInbound(t, "s2", "other", 4511, 1, tcpTLSStream)
seedHost(t, &model.Host{GroupId: "ga", InboundId: other.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "ga", group.Id)
seedSubInbound(t, "s1", "target", 4512, 1, tcpTLSStream)
setClientGroup(t, "target@e", group.Name)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
if len(links) != 1 || !strings.Contains(links[0], "203.0.113.5:4512") {
t.Fatalf("expected the inbound's legacy link, got: %v", links)
}
}
// Bindings on a case-duplicate group row still reach members of the canonical
// group: the resolver folds both ids onto the first row loaded.
func TestSub_ClientGroup_CaseDuplicateBinding(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4513, 1, tcpTLSStream)
canonical := seedClientGroup(t, "VIP")
duplicate := seedClientGroup(t, "vip")
setClientGroup(t, "cg@e", canonical.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "gb", duplicate.Id)
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if strings.Contains(joined, "a.cdn.com:443") || !strings.Contains(joined, "b.cdn.com:443") {
t.Fatalf("case-duplicate binding must be canonicalized, got: %s", joined)
}
}
// A group row without a binding must leave the default pool untouched.
func TestSub_ClientGroup_NoBindingKeepsDefaultPool(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4510, 1, tcpTLSStream)
group := seedClientGroup(t, "VIP")
setClientGroup(t, "cg@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
seedHost(t, &model.Host{GroupId: "gb", InboundId: ib.Id, SortOrder: 2, Remark: "B", Address: "b.cdn.com", Port: 443, Security: "tls"})
links, _, _, _, err := NewSubService("").GetSubs("s1", "req.example.com")
if err != nil {
t.Fatalf("GetSubs: %v", err)
}
joined := strings.Join(links, "\n")
if !strings.Contains(joined, "a.cdn.com:443") || !strings.Contains(joined, "b.cdn.com:443") {
t.Fatalf("unbound group must keep the default pool, got: %s", joined)
}
}
// Most subscribers belong to no group: their request must not pay for the
// client-group index, which is two extra queries on every subscription fetch.
func TestSub_ClientGroup_UngroupedClientSkipsGroupIndex(t *testing.T) {
seedSubDB(t)
ib := seedSubInbound(t, "s1", "cg", 4514, 1, tcpTLSStream)
seedSubClient(t, ib, "s2", "member@e")
group := seedClientGroup(t, "VIP")
setClientGroup(t, "member@e", group.Name)
seedHost(t, &model.Host{GroupId: "ga", InboundId: ib.Id, SortOrder: 1, Remark: "A", Address: "a.cdn.com", Port: 443, Security: "tls"})
bindHostGroup(t, "ga", group.Id)
db := database.GetDB()
reads := 0
const name = "test:count_client_group_index"
if err := db.Callback().Query().After("gorm:query").Register(name, func(tx *gorm.DB) {
if tx.Statement.Table == "client_groups" || tx.Statement.Table == "host_group_client_groups" {
reads++
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(name) })
for subID, want := range map[string]int{"s1": 0, "s2": 2} {
reads = 0
links, _, _, _, err := NewSubService("").GetSubs(subID, "req.example.com")
if err != nil || len(links) != 1 || !strings.Contains(links[0], "a.cdn.com:443") {
t.Fatalf("%s: links = %v, err = %v, want the one host link", subID, links, err)
}
if reads != want {
t.Fatalf("%s: client-group index queries = %d, want %d", subID, reads, want)
}
}
}
+5 -1
View File
@@ -48,7 +48,11 @@ func orderedSubValues[T any](entries []orderedSubEntry[T]) []T {
func (s *SubService) loadSubscriptionHosts(inbounds []*model.Inbound) error {
s.hostsByInbound = make(map[int][]*model.Host, len(inbounds))
s.hostsLoaded = make(map[int]bool, len(inbounds))
s.hostGroupOrders = make(map[string]hostEntryOrder)
for _, inbound := range inbounds {
s.hostsLoaded[inbound.Id] = true
}
ids := make([]int, len(inbounds))
for i, inbound := range inbounds {
ids[i] = inbound.Id
@@ -89,7 +93,7 @@ func hostOrderGroupID(h *model.Host) string {
func (s *SubService) subscriptionHostVariants(inbound *model.Inbound, format string) []subscriptionHostVariant {
var variants []subscriptionHostVariant
enabled := 0
for _, h := range s.hostsByInbound[inbound.Id] {
for _, h := range s.hostsForInbound(inbound) {
if h.IsDisabled {
continue
}
+179
View File
@@ -0,0 +1,179 @@
package sub
import (
"slices"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
)
// ensureClientGroupIndex loads client groups and host-group bindings once per
// request; membership itself stays on clients.group_name.
func (s *SubService) ensureClientGroupIndex() {
if s.clientGroupIndexLoaded {
return
}
s.clientGroupIndexLoaded = true
s.clientGroupIDsByName = map[string]int{}
s.hostGroupsByClientGroup = map[int]map[string]struct{}{}
db := database.GetDB()
if db == nil {
return
}
var groups []model.ClientGroup
if err := db.Select("id", "name").Order("id ASC").Find(&groups).Error; err != nil {
logger.Warning("SubService - ensureClientGroupIndex:", err)
return
}
canonicalByID := make(map[int]int, len(groups))
for _, group := range groups {
key := strings.ToLower(strings.TrimSpace(group.Name))
canonical, exists := s.clientGroupIDsByName[key]
if !exists {
canonical = group.Id
s.clientGroupIDsByName[key] = canonical
}
canonicalByID[group.Id] = canonical
}
var bindings []model.HostGroupClientGroup
if err := db.Find(&bindings).Error; err != nil {
logger.Warning("SubService - ensureClientGroupIndex:", err)
return
}
for _, binding := range bindings {
groupID, ok := canonicalByID[binding.ClientGroupId]
if !ok {
continue
}
bound := s.hostGroupsByClientGroup[groupID]
if bound == nil {
bound = map[string]struct{}{}
s.hostGroupsByClientGroup[groupID] = bound
}
bound[binding.HostGroupId] = struct{}{}
}
}
// hostsForInbound loads one inbound's hosts once per request, including disabled
// rows, so tier selection can tell "no binding" from "bound but unusable".
func (s *SubService) hostsForInbound(inbound *model.Inbound) []*model.Host {
if s.hostsLoaded != nil && s.hostsLoaded[inbound.Id] {
return s.hostsByInbound[inbound.Id]
}
if s.hostsByInbound == nil {
s.hostsByInbound = map[int][]*model.Host{}
}
if s.hostsLoaded == nil {
s.hostsLoaded = map[int]bool{}
}
s.hostsLoaded[inbound.Id] = true
var hosts []*model.Host
if database.GetDB() == nil {
return nil
}
if err := database.GetDB().Where("inbound_id = ?", inbound.Id).
Order("sort_order asc, id asc").Find(&hosts).Error; err != nil {
logger.Warning("SubService - hostsForInbound:", err)
return nil
}
s.hostsByInbound[inbound.Id] = hosts
return hosts
}
// clientGroupHostBinding returns this inbound's rows in host groups bound to the
// client's group, including disabled rows so the caller can fail closed.
func (s *SubService) clientGroupHostBinding(inbound *model.Inbound, client model.Client) (hostBinding, []*model.Host) {
name := strings.ToLower(strings.TrimSpace(client.Group))
if name == "" {
return hostBindingNone, nil
}
s.ensureClientGroupIndex()
groupID, ok := s.clientGroupIDsByName[name]
if !ok {
return hostBindingNone, nil
}
bound := s.hostGroupsByClientGroup[groupID]
if len(bound) == 0 {
return hostBindingNone, nil
}
var here []*model.Host
for _, host := range s.hostsForInbound(inbound) {
if host.GroupId == "" {
continue
}
if _, ok := bound[host.GroupId]; ok {
here = append(here, host)
}
}
if len(here) == 0 {
return hostBindingNone, nil
}
return hostBindingBound, here
}
// hostEndpointsForHosts projects a specific host set, applying format exclusion
// after the tier has been chosen. Empty means the tier is selected but unusable.
func (s *SubService) hostEndpointsForHosts(inbound *model.Inbound, hosts []*model.Host, format string) []map[string]any {
defaultDest := s.resolveInboundAddress(inbound)
eps := make([]map[string]any, 0, len(hosts))
for _, host := range hosts {
if host.IsDisabled || slices.Contains(host.ExcludeFromSubTypes, format) {
continue
}
eps = append(eps, s.hostEndpointMaps(host, defaultDest, inbound.Port)...)
}
return eps
}
// selectHostEndpoints is the single tier decision: per-client binding, then the
// client's group, then the caller's default host set.
func (s *SubService) selectHostEndpoints(inbound *model.Inbound, client model.Client, format string, baseEps []map[string]any) ([]map[string]any, bool) {
if eps, bound := s.clientHostEndpoints(inbound, client, format, baseEps); bound {
return eps, true
}
state, hosts := s.clientGroupHostBinding(inbound, client)
if state != hostBindingBound {
return baseEps, false
}
eps := s.hostEndpointsForHosts(inbound, hosts, format)
if len(eps) == 0 {
return nil, true
}
return eps, true
}
// selectHostVariants is selectHostEndpoints for hosts-first ordering. A selected
// tier that loses every host to disablement or format exclusion fails closed.
func (s *SubService) selectHostVariants(inbound *model.Inbound, client model.Client, format string) ([]subscriptionHostVariant, bool) {
state, _ := s.clientHostBinding(inbound, client)
switch state {
case hostBindingClosed:
return nil, true
case hostBindingBound:
return s.clientHostVariants(inbound, client, format)
}
groupState, groupHosts := s.clientGroupHostBinding(inbound, client)
if groupState == hostBindingBound {
variants := s.hostVariantsForHosts(inbound, groupHosts, format)
return variants, len(variants) == 0
}
variants := s.subscriptionHostVariants(inbound, format)
return variants, len(variants) == 0
}
// hostVariantsForHosts orders specific hosts by the same host-group order the
// default variants use, without adding the legacy default variant.
func (s *SubService) hostVariantsForHosts(inbound *model.Inbound, hosts []*model.Host, format string) []subscriptionHostVariant {
var variants []subscriptionHostVariant
for _, host := range hosts {
if host.IsDisabled || slices.Contains(host.ExcludeFromSubTypes, format) {
continue
}
order := s.hostGroupOrders[hostOrderGroupID(host)]
order.inboundSort, order.inboundID, order.hostID = inbound.SubSortIndex, inbound.Id, host.Id
variants = append(variants, subscriptionHostVariant{host, &order})
}
return variants
}
+1 -10
View File
@@ -115,16 +115,7 @@ func (s *SubService) clientHostVariants(inbound *model.Inbound, client model.Cli
// hostEndpoints returns the externalProxy-shaped endpoints of the inbound's enabled hosts for format, nil without any;
// closed reports that all of them are excluded from format, so the inbound renders nothing there.
func (s *SubService) hostEndpoints(inbound *model.Inbound, format string) (eps []map[string]any, closed bool) {
var hosts []*model.Host
if s.hostsByInbound != nil {
hosts = s.hostsByInbound[inbound.Id]
} else if err := database.GetDB().
Where("inbound_id = ? AND is_disabled = ?", inbound.Id, false).
Order("sort_order asc, id asc").
Find(&hosts).Error; err != nil {
logger.Warning("SubService - hostEndpoints:", err)
return nil, false
}
hosts := s.hostsForInbound(inbound)
if len(hosts) == 0 {
return nil, false
}
+2 -2
View File
@@ -191,7 +191,7 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo
continue
}
if subReq.hostsFirst {
variants, closed := subReq.clientHostVariants(&baseInbound, client, "json")
variants, closed := subReq.selectHostVariants(&baseInbound, client, "json")
hasBoundClosed = hasBoundClosed || (closed && !hiddenMember)
for _, variant := range variants {
render := func() subConfigEntry {
@@ -209,7 +209,7 @@ func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bo
continue
}
effective := inbound
if effectiveEps, bound := subReq.clientHostEndpoints(&baseInbound, client, "json", baseEps); bound {
if effectiveEps, bound := subReq.selectHostEndpoints(&baseInbound, client, "json", baseEps); bound {
if len(effectiveEps) == 0 {
hasBoundClosed = hasBoundClosed || !hiddenMember
continue
+1 -1
View File
@@ -43,7 +43,7 @@ func (p *LinkProvider) LinksForClient(host string, inbound *model.Inbound, email
return nil
}
if client, ok := svc.clientForLink(inbound, email); ok {
effectiveEps, bound := svc.clientHostEndpoints(inbound, client, "raw", baseEps)
effectiveEps, bound := svc.selectHostEndpoints(inbound, client, "raw", baseEps)
if bound && len(effectiveEps) == 0 {
return nil
}
+13 -3
View File
@@ -96,9 +96,15 @@ type SubService struct {
// subscription bodies read through it, never panel link rendering.
settingsCache *inboundSettingsCache
hostsByInbound map[int][]*model.Host
hostsLoaded map[int]bool
hostGroupOrders map[string]hostEntryOrder
hostsFirst bool
sharedGroupSni map[string]string
// clientGroupIDsByName and hostGroupsByClientGroup are loaded once per request;
// membership itself stays on clients.group_name.
clientGroupIDsByName map[string]int
hostGroupsByClientGroup map[int]map[string]struct{}
clientGroupIndexLoaded bool
// tuicByInbound and amneziaWGServerByInbound are the typed equivalents of
// settingsByInbound: one decode per request, not one per link of a subId.
tuicByInbound map[int]*tuicLinkInstance
@@ -167,8 +173,12 @@ func (s *SubService) PrepareForRequest(host string) {
s.tuicByInbound = map[int]*tuicLinkInstance{}
s.amneziaWGServerByInbound = map[int]*amneziawg.ServerSettings{}
s.hostsByInbound = nil
s.hostsLoaded = nil
s.hostGroupOrders = nil
s.sharedGroupSni = nil
s.clientGroupIDsByName = nil
s.hostGroupsByClientGroup = nil
s.clientGroupIndexLoaded = false
s.rendered = 0
s.wireguardDeviceSelected = false
settings := s.settingService.GetSubscriptionRenderSettings()
@@ -616,7 +626,7 @@ func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.Clie
}
var link string
if s.hostsFirst {
variants, closed := s.clientHostVariants(inbound, client, "raw")
variants, closed := s.selectHostVariants(inbound, client, "raw")
if closed {
seenEmails[client.Email] = struct{}{}
continue
@@ -630,7 +640,7 @@ func (s *SubService) getSubs(subId string) ([]string, []string, int64, xray.Clie
}
ordered = append(ordered, orderedSubEntry[func() string]{variant.order, render})
}
} else if effectiveEps, bound := s.clientHostEndpoints(inbound, client, "raw", hostEps); bound && len(effectiveEps) == 0 {
} else if effectiveEps, bound := s.selectHostEndpoints(inbound, client, "raw", hostEps); bound && len(effectiveEps) == 0 {
seenEmails[client.Email] = struct{}{}
continue
} else if len(effectiveEps) > 0 {
@@ -726,7 +736,7 @@ func (s *SubService) inboundLinks(inbound *model.Inbound) []string {
continue
}
seen[key] = struct{}{}
effectiveEps, bound := s.clientHostEndpoints(inbound, client, "raw", hostEps)
effectiveEps, bound := s.selectHostEndpoints(inbound, client, "raw", hostEps)
if bound && len(effectiveEps) == 0 {
continue
}
+36 -6
View File
@@ -27,6 +27,7 @@ func (a *GroupController) initRouter(g *gin.RouterGroup) {
g.POST("/groups/rename", a.rename)
g.POST("/groups/delete", a.delete)
g.POST("/groups/resetTraffic", a.resetTraffic)
g.POST("/groups/:name/hosts", a.setHosts)
g.POST("/groups/bulkAdd", a.bulkAdd)
g.POST("/groups/bulkRemove", a.bulkRemove)
}
@@ -51,7 +52,8 @@ func (a *GroupController) emails(c *gin.Context) {
}
type groupCreateBody struct {
Name string `json:"name"`
Name string `json:"name"`
HostGroupIds []string `json:"hostGroupIds"`
}
func (a *GroupController) create(c *gin.Context) {
@@ -60,7 +62,7 @@ func (a *GroupController) create(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if err := a.clientService.CreateGroup(body.Name); err != nil {
if err := a.clientService.CreateGroup(body.Name, body.HostGroupIds); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
@@ -69,8 +71,9 @@ func (a *GroupController) create(c *gin.Context) {
}
type groupRenameBody struct {
OldName string `json:"oldName"`
NewName string `json:"newName"`
OldName string `json:"oldName"`
NewName string `json:"newName"`
HostGroupIds *[]string `json:"hostGroupIds"`
}
func (a *GroupController) rename(c *gin.Context) {
@@ -79,12 +82,20 @@ func (a *GroupController) rename(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
affected, err := a.clientService.RenameGroup(body.OldName, body.NewName)
var affected int
var err error
if body.HostGroupIds != nil {
affected, err = a.clientService.UpdateGroup(body.OldName, body.NewName, *body.HostGroupIds)
} else {
affected, err = a.clientService.RenameGroup(body.OldName, body.NewName)
}
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
a.xrayService.SetToNeedRestart()
if strings.TrimSpace(body.OldName) != strings.TrimSpace(body.NewName) {
a.xrayService.SetToNeedRestart()
}
jsonObj(c, gin.H{"affected": affected}, nil)
notifyClientsChanged()
}
@@ -113,6 +124,25 @@ type groupResetTrafficBody struct {
Name string `json:"name"`
}
type groupHostsBody struct {
HostGroupIds []string `json:"hostGroupIds"`
}
func (a *GroupController) setHosts(c *gin.Context) {
var body groupHostsBody
if err := c.ShouldBindJSON(&body); err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
ids, err := a.clientService.SetGroupHostGroups(c.Param("name"), body.HostGroupIds)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"hostGroupIds": ids}, nil)
notifyClientsChanged()
}
func (a *GroupController) resetTraffic(c *gin.Context) {
var body groupResetTrafficBody
if err := c.ShouldBindJSON(&body); err != nil {
+7
View File
@@ -774,6 +774,13 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model
}
normalizeClientTrafficReset(&updated)
updated.ClientHostRuleIds = model.NormalizeClientHostRuleIds(updated.ClientHostRuleIds)
if groupName := strings.TrimSpace(updated.Group); groupName != "" {
group, err := database.EnsureClientGroup(database.GetDB(), groupName)
if err != nil {
return false, err
}
updated.Group = group.Name
}
if updated.SubID == "" {
updated.SubID = existing.SubID
}
@@ -0,0 +1,431 @@
package service
import (
"encoding/json"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
"gorm.io/gorm"
)
func TestClientGroup_RenameKeepsMembershipAndBindings(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
if err := db.Create(&model.ClientRecord{Email: "a@x", Group: "VIP", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := db.Create(&model.HostGroupClientGroup{HostGroupId: "hg", ClientGroupId: group.Id}).Error; err != nil {
t.Fatalf("bind host group: %v", err)
}
svc := &ClientService{}
affected, err := svc.RenameGroup("VIP", "PRO")
if err != nil {
t.Fatalf("RenameGroup: %v", err)
}
if affected != 1 {
t.Fatalf("affected = %d, want 1", affected)
}
var client model.ClientRecord
if err := db.Where("email = ?", "a@x").First(&client).Error; err != nil {
t.Fatalf("reload client: %v", err)
}
if client.Group != "PRO" {
t.Fatalf("client group = %q, want PRO", client.Group)
}
var bindings int64
if err := db.Model(&model.HostGroupClientGroup{}).
Where("host_group_id = ? AND client_group_id = ?", "hg", group.Id).Count(&bindings).Error; err != nil {
t.Fatalf("count bindings: %v", err)
}
if bindings != 1 {
t.Fatalf("rename dropped the host binding: %d", bindings)
}
var renamed model.ClientGroup
if err := db.First(&renamed, group.Id).Error; err != nil || renamed.Name != "PRO" {
t.Fatalf("group row = %+v err=%v, want PRO", renamed, err)
}
}
func TestClientGroup_DeleteClearsMembersAndBindings(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
if err := db.Create(&model.ClientRecord{Email: "a@x", Group: "VIP", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := db.Create(&model.HostGroupClientGroup{HostGroupId: "hg", ClientGroupId: group.Id}).Error; err != nil {
t.Fatalf("bind host group: %v", err)
}
svc := &ClientService{}
affected, err := svc.DeleteGroup("VIP")
if err != nil {
t.Fatalf("DeleteGroup: %v", err)
}
if affected != 1 {
t.Fatalf("affected = %d, want 1", affected)
}
var client model.ClientRecord
if err := db.Where("email = ?", "a@x").First(&client).Error; err != nil {
t.Fatalf("client must not be deleted: %v", err)
}
if client.Group != "" {
t.Fatalf("client group = %q, want empty", client.Group)
}
var bindings, groups int64
if err := db.Model(&model.HostGroupClientGroup{}).Where("client_group_id = ?", group.Id).Count(&bindings).Error; err != nil {
t.Fatalf("count bindings: %v", err)
}
if bindings != 0 {
t.Fatalf("delete left %d host bindings", bindings)
}
if err := db.Model(&model.ClientGroup{}).Where("id = ?", group.Id).Count(&groups).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if groups != 0 {
t.Fatalf("delete left the group row: %d", groups)
}
}
func TestClientGroup_AddToGroupCreatesRowForDerivedLabel(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
if err := db.Create(&model.ClientRecord{Email: "a@x", Group: "Derived", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
svc := &ClientService{}
if _, err := svc.AddToGroup([]string{"a@x"}, "Derived"); err != nil {
t.Fatalf("AddToGroup: %v", err)
}
var groups int64
if err := db.Model(&model.ClientGroup{}).Where("name = ?", "Derived").Count(&groups).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if groups != 1 {
t.Fatalf("derived group row = %d, want 1", groups)
}
}
func TestClientGroup_AddToGroupUsesCanonicalCase(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
if err := db.Create(&model.ClientGroup{Name: "VIP"}).Error; err != nil {
t.Fatalf("create group: %v", err)
}
if err := db.Create(&model.ClientRecord{Email: "a@x", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
svc := &ClientService{}
if _, err := svc.AddToGroup([]string{"a@x"}, "vip"); err != nil {
t.Fatalf("AddToGroup: %v", err)
}
var client model.ClientRecord
if err := db.Where("email = ?", "a@x").First(&client).Error; err != nil {
t.Fatalf("reload client: %v", err)
}
if client.Group != "VIP" {
t.Fatalf("client group = %q, want canonical VIP", client.Group)
}
var groups int64
if err := db.Model(&model.ClientGroup{}).Where("LOWER(name) = 'vip'").Count(&groups).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if groups != 1 {
t.Fatalf("case variant created a second group: %d", groups)
}
}
func TestClientGroup_SetHostGroups(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
inbound := &model.Inbound{UserId: 1, Tag: "in", Enable: true, Port: 4501, Protocol: model.VLESS, Settings: `{"clients":[]}`}
if err := db.Create(inbound).Error; err != nil {
t.Fatalf("create inbound: %v", err)
}
hostSvc := &HostService{}
if _, err := hostSvc.AddHostGroup(&entity.HostGroup{
GroupId: "hg", InboundIds: []int{inbound.Id}, Hosts: []string{"a.cdn.com"}, Remark: "A",
}); err != nil {
t.Fatalf("AddHostGroup: %v", err)
}
svc := &ClientService{}
ids, err := svc.SetGroupHostGroups("VIP", []string{"hg", " hg ", ""})
if err != nil {
t.Fatalf("SetGroupHostGroups: %v", err)
}
if len(ids) != 1 || ids[0] != "hg" {
t.Fatalf("saved host groups = %v, want [hg]", ids)
}
groups, err := svc.ListGroups()
if err != nil {
t.Fatalf("ListGroups: %v", err)
}
if got := findGroupSummary(groups, "VIP"); len(got.HostGroupIds) != 1 || got.HostGroupIds[0] != "hg" {
t.Fatalf("listed host groups = %v, want [hg]", got.HostGroupIds)
}
// Clearing the selection removes the binding but keeps the group.
ids, err = svc.SetGroupHostGroups("VIP", nil)
if err != nil {
t.Fatalf("SetGroupHostGroups clear: %v", err)
}
if ids == nil || len(ids) != 0 {
t.Fatalf("cleared host groups = %v, want a non-nil empty slice", ids)
}
groups, err = svc.ListGroups()
if err != nil {
t.Fatalf("ListGroups after clear: %v", err)
}
if got := findGroupSummary(groups, "VIP"); got.HostGroupIds == nil || len(got.HostGroupIds) != 0 {
t.Fatalf("listed host groups after clear = %v, want a non-nil empty slice", got.HostGroupIds)
}
// Deleting the host group also drops the binding.
if _, err := svc.SetGroupHostGroups("VIP", []string{"hg"}); err != nil {
t.Fatalf("SetGroupHostGroups rebind: %v", err)
}
if err := hostSvc.DeleteHostGroup("hg"); err != nil {
t.Fatalf("DeleteHostGroup: %v", err)
}
var bindings int64
if err := db.Model(&model.HostGroupClientGroup{}).Where("host_group_id = ?", "hg").Count(&bindings).Error; err != nil {
t.Fatalf("count bindings: %v", err)
}
if bindings != 0 {
t.Fatalf("delete left %d bindings", bindings)
}
}
func TestClientGroup_RejectsUnknownHostGroup(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
svc := &ClientService{}
if _, err := svc.SetGroupHostGroups("VIP", []string{"missing"}); err == nil {
t.Fatal("unknown host group must be rejected")
}
var bindings int64
if err := db.Model(&model.HostGroupClientGroup{}).Count(&bindings).Error; err != nil {
t.Fatalf("count bindings: %v", err)
}
if bindings != 0 {
t.Fatalf("failed save left %d bindings", bindings)
}
// A failed save must not create the client group as a side effect.
if _, err := svc.SetGroupHostGroups("New", []string{"missing"}); err == nil {
t.Fatal("unknown host group must be rejected for an unknown group too")
}
var groups int64
if err := db.Model(&model.ClientGroup{}).Where("name = ?", "New").Count(&groups).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if groups != 0 {
t.Fatalf("failed save created %d group rows", groups)
}
}
func TestClientGroup_CreateAndUpdateWithHostGroups(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
inbound := &model.Inbound{UserId: 1, Tag: "in", Enable: true, Port: 4503, Protocol: model.VLESS, Settings: `{"clients":[]}`}
if err := db.Create(inbound).Error; err != nil {
t.Fatalf("create inbound: %v", err)
}
if _, err := (&HostService{}).AddHostGroup(&entity.HostGroup{
GroupId: "hg", InboundIds: []int{inbound.Id}, Hosts: []string{"a.cdn.com"}, Remark: "A",
}); err != nil {
t.Fatalf("AddHostGroup: %v", err)
}
svc := &ClientService{}
if err := svc.CreateGroup("VIP", []string{"hg"}); err != nil {
t.Fatalf("CreateGroup: %v", err)
}
groups, err := svc.ListGroups()
if err != nil {
t.Fatalf("ListGroups: %v", err)
}
if got := findGroupSummary(groups, "VIP"); len(got.HostGroupIds) != 1 || got.HostGroupIds[0] != "hg" {
t.Fatalf("created group host rules = %v, want [hg]", got.HostGroupIds)
}
// Renaming and clearing host rules in one edit.
if _, err := svc.UpdateGroup("VIP", "PRO", []string{}); err != nil {
t.Fatalf("UpdateGroup rename+clear: %v", err)
}
groups, err = svc.ListGroups()
if err != nil {
t.Fatalf("ListGroups after update: %v", err)
}
if got := findGroupSummary(groups, "PRO"); got.Name != "PRO" || len(got.HostGroupIds) != 0 {
t.Fatalf("updated group = %+v, want PRO with no host rules", got)
}
// Editing host rules without changing the name.
if _, err := svc.UpdateGroup("PRO", "PRO", []string{"hg"}); err != nil {
t.Fatalf("UpdateGroup host rules only: %v", err)
}
groups, err = svc.ListGroups()
if err != nil {
t.Fatalf("ListGroups after host-only update: %v", err)
}
if got := findGroupSummary(groups, "PRO"); len(got.HostGroupIds) != 1 || got.HostGroupIds[0] != "hg" {
t.Fatalf("host-only update host rules = %v, want [hg]", got.HostGroupIds)
}
}
func TestClientGroup_CreateAndUpdateRejectUnknownHostGroup(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
svc := &ClientService{}
if err := svc.CreateGroup("VIP", []string{"missing"}); err == nil {
t.Fatal("create with unknown host group must be rejected")
}
var groups int64
if err := db.Model(&model.ClientGroup{}).Where("name = ?", "VIP").Count(&groups).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if groups != 0 {
t.Fatalf("failed create left %d group rows", groups)
}
if err := svc.CreateGroup("VIP", nil); err != nil {
t.Fatalf("CreateGroup: %v", err)
}
if _, err := svc.UpdateGroup("VIP", "PRO", []string{"missing"}); err == nil {
t.Fatal("update with unknown host group must be rejected")
}
var renamed, bindings int64
if err := db.Model(&model.ClientGroup{}).Where("name = ?", "PRO").Count(&renamed).Error; err != nil {
t.Fatalf("count renamed groups: %v", err)
}
if err := db.Model(&model.HostGroupClientGroup{}).Count(&bindings).Error; err != nil {
t.Fatalf("count bindings: %v", err)
}
if renamed != 0 || bindings != 0 {
t.Fatalf("failed update left renamed=%d bindings=%d", renamed, bindings)
}
}
// Deleting an inbound removes its host rows; a binding to the vanished host
// group must not survive as a stale tag that blocks later group edits.
func TestClientGroup_StaleBindingAfterInboundDelete(t *testing.T) {
initTrafficTestDB(t)
db := database.GetDB()
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
inbound := &model.Inbound{UserId: 1, Tag: "in", Enable: true, Port: 4504, Protocol: model.VLESS, Settings: `{"clients":[]}`}
if err := db.Create(inbound).Error; err != nil {
t.Fatalf("create inbound: %v", err)
}
if _, err := (&HostService{}).AddHostGroup(&entity.HostGroup{
GroupId: "hg", InboundIds: []int{inbound.Id}, Hosts: []string{"a.cdn.com"}, Remark: "A",
}); err != nil {
t.Fatalf("AddHostGroup: %v", err)
}
svc := &ClientService{}
if _, err := svc.SetGroupHostGroups("VIP", []string{"hg"}); err != nil {
t.Fatalf("SetGroupHostGroups: %v", err)
}
if err := (&InboundService{}).deleteInboundRow(db, inbound.Id); err != nil {
t.Fatalf("deleteInboundRow: %v", err)
}
groups, err := svc.ListGroups()
if err != nil {
t.Fatalf("ListGroups: %v", err)
}
if got := findGroupSummary(groups, "VIP"); len(got.HostGroupIds) != 0 {
t.Fatalf("stale host rules after inbound delete = %v, want none", got.HostGroupIds)
}
if _, err := svc.SetGroupHostGroups("VIP", []string{}); err != nil {
t.Fatalf("edit after inbound delete: %v", err)
}
}
// Inbound settings can still hold a case variant of the canonical group name, so
// rename and delete follow the client, or a later sync resurrects the old group.
func TestClientGroup_RenameAndDeleteFollowCanonicalizedJSONCase(t *testing.T) {
setupBulkDB(t)
db := database.GetDB()
id := "77777777-7777-7777-7777-777777777777"
ib := mkInbound(t, 4505, model.VLESS, clientsSettings(t, []model.Client{{
Email: "case@x", ID: id, Enable: true, Group: "vip",
}}))
svc := &ClientService{}
if err := svc.SyncInbound(nil, ib.Id, []model.Client{{
Email: "case@x", ID: id, Enable: true, Group: "VIP",
}}); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
var rec model.ClientRecord
if err := db.Where("email = ?", "case@x").First(&rec).Error; err != nil {
t.Fatalf("reload client: %v", err)
}
if rec.Group != "VIP" {
t.Fatalf("client group = %q, want canonical VIP", rec.Group)
}
assertInboundClientGroup(t, db, ib.Id, "case@x", "vip")
if _, err := svc.UpdateGroup("VIP", "Gold", nil); err != nil {
t.Fatalf("UpdateGroup: %v", err)
}
assertInboundClientGroup(t, db, ib.Id, "case@x", "Gold")
if _, err := svc.DeleteGroup("Gold"); err != nil {
t.Fatalf("DeleteGroup: %v", err)
}
assertInboundClientGroup(t, db, ib.Id, "case@x", "")
}
func assertInboundClientGroup(t *testing.T, db *gorm.DB, inboundID int, email, want string) {
t.Helper()
var settings string
if err := db.Model(&model.Inbound{}).Where("id = ?", inboundID).Pluck("settings", &settings).Error; err != nil {
t.Fatalf("load settings: %v", err)
}
var parsed struct {
Clients []map[string]any `json:"clients"`
}
if err := json.Unmarshal([]byte(settings), &parsed); err != nil {
t.Fatalf("unmarshal settings: %v", err)
}
if len(parsed.Clients) != 1 {
t.Fatalf("settings clients = %d, want 1: %s", len(parsed.Clients), settings)
}
got, _ := parsed.Clients[0]["group"].(string)
if got != want {
t.Fatalf("settings group = %q, want %q: %s", got, want, settings)
}
}
func findGroupSummary(groups []GroupSummary, name string) GroupSummary {
for _, group := range groups {
if group.Name == name {
return group
}
}
return GroupSummary{}
}
+260 -107
View File
@@ -14,11 +14,13 @@ import (
)
type GroupSummary struct {
Name string `json:"name"`
ClientCount int `json:"clientCount"`
TrafficUsed int64 `json:"trafficUsed"`
Up int64 `json:"up"`
Down int64 `json:"down"`
Id int `json:"id"`
Name string `json:"name"`
ClientCount int `json:"clientCount"`
HostGroupIds []string `json:"hostGroupIds"`
TrafficUsed int64 `json:"trafficUsed"`
Up int64 `json:"up"`
Down int64 `json:"down"`
}
func (s *ClientService) ListGroups() ([]GroupSummary, error) {
@@ -33,6 +35,14 @@ func (s *ClientService) ListGroups() ([]GroupSummary, error) {
if err := db.Find(&stored).Error; err != nil {
return nil, err
}
var bindings []model.HostGroupClientGroup
if err := db.Order("host_group_id ASC").Find(&bindings).Error; err != nil {
return nil, err
}
hostGroups := make(map[int][]string, len(bindings))
for _, binding := range bindings {
hostGroups[binding.ClientGroupId] = append(hostGroups[binding.ClientGroupId], binding.HostGroupId)
}
type groupAgg struct {
count int
up int64
@@ -40,11 +50,13 @@ func (s *ClientService) ListGroups() ([]GroupSummary, error) {
}
baseUp := make(map[string]int64, len(stored))
baseDown := make(map[string]int64, len(stored))
groupIDs := make(map[string]int, len(stored))
merged := make(map[string]groupAgg, len(derived)+len(stored))
for _, g := range stored {
merged[g.Name] = groupAgg{}
baseUp[g.Name] = g.ResetUp
baseDown[g.Name] = g.ResetDown
groupIDs[g.Name] = g.Id
}
for name, g := range derived {
merged[name] = groupAgg{count: g.clients, up: g.up, down: g.down}
@@ -53,7 +65,11 @@ func (s *ClientService) ListGroups() ([]GroupSummary, error) {
for name, agg := range merged {
up := max(clampedTrafficAdd(agg.up, -baseUp[name]), 0)
down := max(clampedTrafficAdd(agg.down, -baseDown[name]), 0)
out = append(out, GroupSummary{Name: name, ClientCount: agg.count, TrafficUsed: clampedTrafficAdd(up, down), Up: up, Down: down})
hostGroupIDs := hostGroups[groupIDs[name]]
if hostGroupIDs == nil {
hostGroupIDs = []string{}
}
out = append(out, GroupSummary{Id: groupIDs[name], Name: name, ClientCount: agg.count, HostGroupIds: hostGroupIDs, TrafficUsed: clampedTrafficAdd(up, down), Up: up, Down: down})
}
sort.Slice(out, func(i, j int) bool {
return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name)
@@ -167,20 +183,30 @@ func (s *ClientService) ResetGroupTraffic(name string) error {
Updates(map[string]any{"reset_up": agg.up, "reset_down": agg.down}).Error
}
func (s *ClientService) CreateGroup(name string) error {
func (s *ClientService) CreateGroup(name string, hostGroupIDs []string) error {
name = strings.TrimSpace(name)
if name == "" {
return common.NewError("group name is required")
}
hostGroupIDs = normalizeHostGroupIDs(hostGroupIDs)
db := database.GetDB()
var count int64
if err := db.Model(&model.ClientGroup{}).Where("name = ?", name).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return common.NewError("group already exists")
}
return db.Create(&model.ClientGroup{Name: name}).Error
return db.Transaction(func(tx *gorm.DB) error {
if err := validateHostGroupIDs(tx, hostGroupIDs); err != nil {
return err
}
var count int64
if err := tx.Model(&model.ClientGroup{}).Where("LOWER(name) = LOWER(?)", name).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return common.NewError("group already exists")
}
group := &model.ClientGroup{Name: name}
if err := tx.Create(group).Error; err != nil {
return err
}
return replaceGroupHostGroups(tx, group.Id, hostGroupIDs)
})
}
func (s *ClientService) RenameGroup(oldName, newName string) (int, error) {
@@ -195,7 +221,32 @@ func (s *ClientService) RenameGroup(oldName, newName string) (int, error) {
if oldName == newName {
return 0, nil
}
return s.replaceGroupValue(oldName, newName)
return s.replaceGroupValue(oldName, newName, nil)
}
// UpdateGroup renames a group and replaces its host rules in one transaction.
// Keeping the name unchanged updates only the host rules.
func (s *ClientService) UpdateGroup(oldName, newName string, hostGroupIDs []string) (int, error) {
oldName = strings.TrimSpace(oldName)
newName = strings.TrimSpace(newName)
if oldName == "" {
return 0, common.NewError("old group name is required")
}
if newName == "" {
return 0, common.NewError("new group name is required")
}
if oldName == newName {
var count int64
if err := database.GetDB().Model(&model.ClientRecord{}).
Where("group_name = ?", oldName).Count(&count).Error; err != nil {
return 0, err
}
if _, err := s.SetGroupHostGroups(oldName, hostGroupIDs); err != nil {
return 0, err
}
return int(count), nil
}
return s.replaceGroupValue(oldName, newName, &hostGroupIDs)
}
func (s *ClientService) DeleteGroup(name string) (int, error) {
@@ -203,7 +254,81 @@ func (s *ClientService) DeleteGroup(name string) (int, error) {
if name == "" {
return 0, common.NewError("group name is required")
}
return s.replaceGroupValue(name, "")
return s.replaceGroupValue(name, "", nil)
}
// SetGroupHostGroups replaces the host rules attached to one client group.
func (s *ClientService) SetGroupHostGroups(name string, hostGroupIDs []string) ([]string, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, common.NewError("group name is required")
}
hostGroupIDs = normalizeHostGroupIDs(hostGroupIDs)
db := database.GetDB()
err := db.Transaction(func(tx *gorm.DB) error {
if err := validateHostGroupIDs(tx, hostGroupIDs); err != nil {
return err
}
group, err := database.EnsureClientGroup(tx, name)
if err != nil {
return err
}
return replaceGroupHostGroups(tx, group.Id, hostGroupIDs)
})
if err != nil {
return nil, err
}
return hostGroupIDs, nil
}
func validateHostGroupIDs(db *gorm.DB, ids []string) error {
if len(ids) == 0 {
return nil
}
var found int64
if err := db.Model(&model.Host{}).
Where("group_id IN ?", ids).
Distinct("group_id").Count(&found).Error; err != nil {
return err
}
if int(found) != len(ids) {
return common.NewError("host group not found")
}
return nil
}
func replaceGroupHostGroups(tx *gorm.DB, clientGroupID int, hostGroupIDs []string) error {
if err := tx.Where("client_group_id = ?", clientGroupID).
Delete(&model.HostGroupClientGroup{}).Error; err != nil {
return err
}
if len(hostGroupIDs) == 0 {
return nil
}
rows := make([]model.HostGroupClientGroup, 0, len(hostGroupIDs))
for _, hostGroupID := range hostGroupIDs {
rows = append(rows, model.HostGroupClientGroup{
HostGroupId: hostGroupID, ClientGroupId: clientGroupID,
})
}
return tx.Create(&rows).Error
}
func normalizeHostGroupIDs(ids []string) []string {
out := make([]string, 0, len(ids))
seen := make(map[string]struct{}, len(ids))
for _, id := range ids {
id = strings.TrimSpace(id)
if id == "" {
continue
}
if _, dup := seen[id]; dup {
continue
}
seen[id] = struct{}{}
out = append(out, id)
}
return out
}
func (s *ClientService) RemoveFromGroup(emails []string) (int, error) {
@@ -218,21 +343,11 @@ func (s *ClientService) AddToGroup(emails []string, group string) (int, error) {
db := database.GetDB()
if group != "" {
var exists int64
if err := db.Model(&model.ClientGroup{}).Where("name = ?", group).Count(&exists).Error; err != nil {
record, err := database.EnsureClientGroup(db, group)
if err != nil {
return 0, err
}
if exists == 0 {
var derived int64
if err := db.Model(&model.ClientRecord{}).Where("group_name = ?", group).Count(&derived).Error; err != nil {
return 0, err
}
if derived == 0 {
if err := db.Create(&model.ClientGroup{Name: group}).Error; err != nil {
return 0, err
}
}
}
group = record.Name
}
var records []model.ClientRecord
@@ -344,78 +459,117 @@ func (s *ClientService) AddToGroup(emails []string, group string) (int, error) {
return int(affected), nil
}
func (s *ClientService) replaceGroupValue(oldName, newName string) (int, error) {
func (s *ClientService) replaceGroupValue(oldName, newName string, hostGroupIDs *[]string) (int, error) {
db := database.GetDB()
if newName == "" {
if err := db.Where("name = ?", oldName).Delete(&model.ClientGroup{}).Error; err != nil {
return 0, err
}
} else {
if err := db.Model(&model.ClientGroup{}).Where("name = ?", oldName).Update("name", newName).Error; err != nil {
return 0, err
}
}
var records []model.ClientRecord
if err := db.Where("group_name = ?", oldName).Find(&records).Error; err != nil {
return 0, err
}
if len(records) == 0 {
return 0, nil
}
affectedEmails := make([]string, 0, len(records))
for _, r := range records {
affectedEmails = append(affectedEmails, r.Email)
}
tx := db.Begin()
if err := tx.Model(&model.ClientRecord{}).
Where("group_name = ?", oldName).
UpdateColumn("group_name", newName).Error; err != nil {
tx.Rollback()
return 0, err
}
var inboundIDs []int
inboundIDSeen := make(map[int]struct{})
for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
var ids []int
if err := tx.Table("client_inbounds").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
Where("clients.email IN ?", batch).
Distinct("client_inbounds.inbound_id").
Pluck("inbound_id", &ids).Error; err != nil {
tx.Rollback()
return 0, err
}
for _, id := range ids {
if _, ok := inboundIDSeen[id]; !ok {
inboundIDSeen[id] = struct{}{}
inboundIDs = append(inboundIDs, id)
affected := 0
err := db.Transaction(func(tx *gorm.DB) error {
var hostGroupValues []string
if hostGroupIDs != nil {
hostGroupValues = normalizeHostGroupIDs(*hostGroupIDs)
if err := validateHostGroupIDs(tx, hostGroupValues); err != nil {
return err
}
}
}
var group model.ClientGroup
groupErr := tx.Where("name = ?", oldName).First(&group).Error
if groupErr != nil && !errors.Is(groupErr, gorm.ErrRecordNotFound) {
return groupErr
}
groupID := 0
if groupErr == nil {
groupID = group.Id
if newName == "" {
if err := tx.Where("client_group_id = ?", group.Id).
Delete(&model.HostGroupClientGroup{}).Error; err != nil {
return err
}
if err := tx.Delete(&group).Error; err != nil {
return err
}
groupID = 0
} else if err := tx.Model(&group).Update("name", newName).Error; err != nil {
return err
}
} else if newName != "" {
record, err := database.EnsureClientGroup(tx, newName)
if err != nil {
return err
}
groupID = record.Id
}
for _, ibID := range inboundIDs {
var ib model.Inbound
if err := tx.First(&ib, ibID).Error; err != nil {
tx.Rollback()
return 0, err
if hostGroupIDs != nil && newName != "" {
if err := replaceGroupHostGroups(tx, groupID, hostGroupValues); err != nil {
return err
}
}
var settings map[string]any
if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
continue
var records []model.ClientRecord
if err := tx.Where("group_name = ?", oldName).Find(&records).Error; err != nil {
return err
}
clients, ok := settings["clients"].([]any)
if !ok {
continue
affected = len(records)
if len(records) == 0 {
return nil
}
modified := false
for i := range clients {
cm, ok := clients[i].(map[string]any)
affectedEmails := make([]string, 0, len(records))
for _, r := range records {
affectedEmails = append(affectedEmails, r.Email)
}
if err := tx.Model(&model.ClientRecord{}).
Where("group_name = ?", oldName).
UpdateColumn("group_name", newName).Error; err != nil {
return err
}
var inboundIDs []int
inboundIDSeen := make(map[int]struct{})
for _, batch := range chunkStrings(affectedEmails, sqlInChunk) {
var ids []int
if err := tx.Table("client_inbounds").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
Where("clients.email IN ?", batch).
Distinct("client_inbounds.inbound_id").
Pluck("inbound_id", &ids).Error; err != nil {
return err
}
for _, id := range ids {
if _, ok := inboundIDSeen[id]; !ok {
inboundIDSeen[id] = struct{}{}
inboundIDs = append(inboundIDs, id)
}
}
}
emailSet := make(map[string]struct{}, len(affectedEmails))
for _, email := range affectedEmails {
emailSet[email] = struct{}{}
}
for _, ibID := range inboundIDs {
var ib model.Inbound
if err := tx.First(&ib, ibID).Error; err != nil {
return err
}
var settings map[string]any
if err := json.Unmarshal([]byte(ib.Settings), &settings); err != nil {
continue
}
clients, ok := settings["clients"].([]any)
if !ok {
continue
}
if g, ok := cm["group"].(string); ok && g == oldName {
modified := false
for i := range clients {
cm, ok := clients[i].(map[string]any)
if !ok {
continue
}
email, _ := cm["email"].(string)
if _, hit := emailSet[email]; !hit {
continue
}
// The clients row may have been canonicalized without rewriting the
// settings JSON, so match by member rather than by stored spelling.
if newName == "" {
delete(cm, "group")
} else {
@@ -424,25 +578,24 @@ func (s *ClientService) replaceGroupValue(oldName, newName string) (int, error)
clients[i] = cm
modified = true
}
}
if modified {
settings["clients"] = clients
newSettings, err := json.Marshal(settings)
if err != nil {
continue
}
ib.Settings = string(newSettings)
if err := tx.Save(&ib).Error; err != nil {
tx.Rollback()
return 0, err
if modified {
settings["clients"] = clients
newSettings, err := json.Marshal(settings)
if err != nil {
continue
}
ib.Settings = string(newSettings)
if err := tx.Save(&ib).Error; err != nil {
return err
}
}
}
}
if err := tx.Commit().Error; err != nil {
return nil
})
if err != nil {
return 0, err
}
return len(records), nil
return affected, nil
}
// groupCounters is a group's summed traffic, held within ±TrafficMax.
+18
View File
@@ -123,6 +123,24 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [
tx = database.GetDB()
}
groupNames := make(map[string]string)
for i := range clients {
name := strings.TrimSpace(clients[i].Group)
if name == "" {
continue
}
canonical, ok := groupNames[name]
if !ok {
group, err := database.EnsureClientGroup(tx, name)
if err != nil {
return err
}
canonical = group.Name
groupNames[name] = canonical
}
clients[i].Group = canonical
}
var inbound model.Inbound
if err := tx.Select("protocol", "node_id").Where("id = ?", inboundId).Take(&inbound).Error; err != nil {
return err
+9 -1
View File
@@ -401,7 +401,7 @@ func (s *HostService) UpdateHostGroup(groupId string, req *entity.HostGroup) ([]
return err
}
}
return nil
return database.PruneHostGroupClientGroupsTx(tx)
})
if err != nil {
return nil, err
@@ -444,6 +444,10 @@ func (s *HostService) MoveInboundSni(inboundId int, oldNames []string, newSni st
func (s *HostService) DeleteHostGroup(groupId string) error {
return database.GetDB().Transaction(func(tx *gorm.DB) error {
if err := tx.Where("host_group_id = ?", groupId).
Delete(&model.HostGroupClientGroup{}).Error; err != nil {
return err
}
_, err := database.DeleteHosts(tx, "group_id = ?", groupId)
return err
})
@@ -465,6 +469,10 @@ func (s *HostService) DeleteHostsGroup(groupIds []string) error {
return nil
}
return database.GetDB().Transaction(func(tx *gorm.DB) error {
if err := tx.Where("host_group_id IN ?", groupIds).
Delete(&model.HostGroupClientGroup{}).Error; err != nil {
return err
}
_, err := database.DeleteHosts(tx, "group_id IN ?", groupIds)
return err
})
+3
View File
@@ -1753,6 +1753,9 @@ func (s *InboundService) deleteInboundRow(tx *gorm.DB, id int) error {
if _, err := database.DeleteHosts(tx, "inbound_id = ?", id); err != nil {
return err
}
if err := database.PruneHostGroupClientGroupsTx(tx); err != nil {
return err
}
// Drop the deleted inbound from any sub-balancer that selects it; a
// dangling id would emit a member no subscriber can resolve (#5648).
var balancers []model.SubBalancer
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "إجمالي الرفع / التنزيل",
"addGroup": "إضافة مجموعة",
"createSuccess": "تم إنشاء المجموعة «{name}».",
"rename": "إعادة تسمية",
"renameTitle": "إعادة تسمية {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "مجموعة باسم «{name}» موجودة بالفعل.",
"renameSuccess": "تمت إعادة تسمية المجموعة على {count} عميل.",
"deleteConfirmTitle": "حذف المجموعة {name}؟",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "إزالة عملاء…",
"removeFromGroupTitle": "إزالة عملاء من المجموعة «{name}»",
"removeFromGroupDesc": "اختر الأعضاء لإزالتهم من هذه المجموعة. يُحفظ العملاء (استخدم «حذف عملاء المجموعة» للإزالة الكاملة).",
"removeFromGroupResult": "تمت إزالة {count} عميل من {name}."
"removeFromGroupResult": "تمت إزالة {count} عميل من {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "إعادة تشغيل Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Total upload / download",
"addGroup": "Add Group",
"createSuccess": "Group \"{name}\" created.",
"rename": "Rename",
"renameTitle": "Rename {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "A group named \"{name}\" already exists.",
"renameSuccess": "Renamed group on {count} client(s).",
"deleteConfirmTitle": "Delete group {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Remove clients…",
"removeFromGroupTitle": "Remove clients from group \"{name}\"",
"removeFromGroupDesc": "Select members to remove from this group. Clients themselves are kept (use \"Delete clients in group\" to remove them entirely).",
"removeFromGroupResult": "Removed {count} client(s) from {name}."
"removeFromGroupResult": "Removed {count} client(s) from {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"hosts": {
"addHost": "Add Host",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Subida / bajada total",
"addGroup": "Añadir grupo",
"createSuccess": "Grupo «{name}» creado.",
"rename": "Renombrar",
"renameTitle": "Renombrar {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Ya existe un grupo llamado «{name}».",
"renameSuccess": "Grupo renombrado en {count} cliente(s).",
"deleteConfirmTitle": "¿Eliminar el grupo {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Quitar clientes…",
"removeFromGroupTitle": "Quitar clientes del grupo «{name}»",
"removeFromGroupDesc": "Selecciona miembros para quitar de este grupo. Los clientes se conservan (usa «Eliminar clientes del grupo» para eliminarlos por completo).",
"removeFromGroupResult": "Quitados {count} cliente(s) de {name}."
"removeFromGroupResult": "Quitados {count} cliente(s) de {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Reiniciar Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "مجموع آپلود / دانلود",
"addGroup": "افزودن گروه",
"createSuccess": "گروه «{name}» ایجاد شد.",
"rename": "تغییر نام",
"renameTitle": "تغییر نام {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "گروهی به نام «{name}» از قبل وجود دارد.",
"renameSuccess": "گروه روی {count} کاربر تغییر نام داده شد.",
"deleteConfirmTitle": "حذف گروه {name}؟",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "حذف کاربران…",
"removeFromGroupTitle": "حذف کاربران از گروه «{name}»",
"removeFromGroupDesc": "اعضایی را برای حذف از این گروه انتخاب کنید. خود کاربران حفظ می‌شوند (برای حذف کامل از «حذف کاربران گروه» استفاده کنید).",
"removeFromGroupResult": "{count} کاربر از {name} حذف شد."
"removeFromGroupResult": "{count} کاربر از {name} حذف شد.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "راه‌اندازی مجدد Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Total unggah / unduh",
"addGroup": "Tambah grup",
"createSuccess": "Grup «{name}» dibuat.",
"rename": "Ubah nama",
"renameTitle": "Ubah nama {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Grup bernama «{name}» sudah ada.",
"renameSuccess": "Grup diubah namanya pada {count} klien.",
"deleteConfirmTitle": "Hapus grup {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Hapus klien…",
"removeFromGroupTitle": "Hapus klien dari grup «{name}»",
"removeFromGroupDesc": "Pilih anggota untuk dihapus dari grup ini. Klien tetap dipertahankan (gunakan «Hapus klien di grup» untuk menghapus sepenuhnya).",
"removeFromGroupResult": "{count} klien dihapus dari {name}."
"removeFromGroupResult": "{count} klien dihapus dari {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Mulai ulang Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "合計アップロード / ダウンロード",
"addGroup": "グループ追加",
"createSuccess": "グループ「{name}」を作成しました。",
"rename": "名前変更",
"renameTitle": "{name} の名前を変更",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "「{name}」という名前のグループは既に存在します。",
"renameSuccess": "{count} クライアントのグループ名を変更しました。",
"deleteConfirmTitle": "グループ {name} を削除?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "クライアントを削除…",
"removeFromGroupTitle": "グループ「{name}」からクライアントを削除",
"removeFromGroupDesc": "このグループから外すメンバーを選択してください。クライアント自体は保持されます (完全に削除するには「グループのクライアントを削除」を使用)。",
"removeFromGroupResult": "{count} クライアントを {name} から外しました。"
"removeFromGroupResult": "{count} クライアントを {name} から外しました。",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Xrayを再起動",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Total de envio / recebimento",
"addGroup": "Adicionar grupo",
"createSuccess": "Grupo «{name}» criado.",
"rename": "Renomear",
"renameTitle": "Renomear {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Já existe um grupo chamado «{name}».",
"renameSuccess": "Grupo renomeado em {count} cliente(s).",
"deleteConfirmTitle": "Excluir o grupo {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Remover clientes…",
"removeFromGroupTitle": "Remover clientes do grupo «{name}»",
"removeFromGroupDesc": "Selecione membros para remover deste grupo. Os clientes em si são mantidos (use «Excluir clientes do grupo» para removê-los por completo).",
"removeFromGroupResult": "Removidos {count} cliente(s) de {name}."
"removeFromGroupResult": "Removidos {count} cliente(s) de {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Reiniciar Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Всего отправлено / получено",
"addGroup": "Добавить группу",
"createSuccess": "Группа «{name}» создана.",
"rename": "Переименовать",
"renameTitle": "Переименовать {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Группа с именем «{name}» уже существует.",
"renameSuccess": "Группа переименована для {count} клиент(ов).",
"deleteConfirmTitle": "Удалить группу {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Удалить клиентов…",
"removeFromGroupTitle": "Удалить клиентов из группы «{name}»",
"removeFromGroupDesc": "Выберите участников для удаления из этой группы. Сами клиенты сохраняются (используйте «Удалить клиентов группы» для полного удаления).",
"removeFromGroupResult": "Удалено {count} клиент(ов) из {name}."
"removeFromGroupResult": "Удалено {count} клиент(ов) из {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Перезапустить Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Celkom odoslané / prijaté",
"addGroup": "Pridať skupinu",
"createSuccess": "Skupina „{name}“ bola vytvorená.",
"rename": "Premenovať",
"renameTitle": "Premenovať skupinu {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Skupina s názvom „{name}“ už existuje.",
"renameSuccess": "Názov skupiny bol zmenený pri klientoch: {count}.",
"deleteConfirmTitle": "Odstrániť skupinu {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Odobrať klientov…",
"removeFromGroupTitle": "Odobrať klientov zo skupiny „{name}“",
"removeFromGroupDesc": "Vyberte členov, ktorých chcete odobrať zo skupiny. Samotní klienti zostanú zachovaní. Na ich úplné odstránenie použite akciu „Odstrániť klientov v skupine“.",
"removeFromGroupResult": "Odobraté zo skupiny {name}: {count}."
"removeFromGroupResult": "Odobraté zo skupiny {name}: {count}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"hosts": {
"addHost": "Pridať adresu servera",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Toplam yükleme / indirme",
"addGroup": "Grup ekle",
"createSuccess": "«{name}» grubu oluşturuldu.",
"rename": "Yeniden adlandır",
"renameTitle": "{name} yeniden adlandır",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "«{name}» adında bir grup zaten var.",
"renameSuccess": "{count} kullanıcının grubu yeniden adlandırıldı.",
"deleteConfirmTitle": "{name} Grubunu Sil?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Kullanıcı Çıkar…",
"removeFromGroupTitle": "«{name}» Grubundan Kullanıcı Çıkar",
"removeFromGroupDesc": "Bu gruptan çıkarılacak üyeleri seçin. Kullanıcılar korunur (tamamen kaldırmak için «Gruptaki kullanıcıları sil» kullanın).",
"removeFromGroupResult": "{name} grubundan {count} kullanıcı çıkarıldı."
"removeFromGroupResult": "{name} grubundan {count} kullanıcı çıkarıldı.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Xray yeniden başlat",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Всього вивантажено / завантажено",
"addGroup": "Додати групу",
"createSuccess": "Групу «{name}» створено.",
"rename": "Перейменувати",
"renameTitle": "Перейменувати {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Група з назвою «{name}» вже існує.",
"renameSuccess": "Групу перейменовано на {count} клієнт(ах).",
"deleteConfirmTitle": "Видалити групу {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Видалити клієнтів…",
"removeFromGroupTitle": "Видалити клієнтів з групи «{name}»",
"removeFromGroupDesc": "Виберіть учасників для видалення з цієї групи. Самі клієнти зберігаються (використовуйте «Видалити клієнтів групи» для повного видалення).",
"removeFromGroupResult": "Видалено {count} клієнт(ів) з {name}."
"removeFromGroupResult": "Видалено {count} клієнт(ів) з {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Перезапустити Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "Tổng tải lên / tải xuống",
"addGroup": "Thêm nhóm",
"createSuccess": "Đã tạo nhóm «{name}».",
"rename": "Đổi tên",
"renameTitle": "Đổi tên {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "Nhóm có tên «{name}» đã tồn tại.",
"renameSuccess": "Đã đổi tên nhóm trên {count} client.",
"deleteConfirmTitle": "Xóa nhóm {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "Xóa client…",
"removeFromGroupTitle": "Xóa client khỏi nhóm «{name}»",
"removeFromGroupDesc": "Chọn thành viên để xóa khỏi nhóm này. Bản thân client được giữ lại (dùng «Xóa client trong nhóm» để xóa hoàn toàn).",
"removeFromGroupResult": "Đã xóa {count} client khỏi {name}."
"removeFromGroupResult": "Đã xóa {count} client khỏi {name}.",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "Khởi động lại Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "总上传 / 下载",
"addGroup": "添加分组",
"createSuccess": "已创建分组 “{name}”。",
"rename": "重命名",
"renameTitle": "重命名 {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "已存在名为 “{name}” 的分组。",
"renameSuccess": "已为 {count} 个客户端重命名分组。",
"deleteConfirmTitle": "删除分组 {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "移除客户端…",
"removeFromGroupTitle": "从分组 “{name}” 移除客户端",
"removeFromGroupDesc": "选择要从此分组中移除的成员。客户端本身保留(使用 “删除分组中的客户端” 完全移除)。",
"removeFromGroupResult": "已从 {name} 移除 {count} 个客户端。"
"removeFromGroupResult": "已从 {name} 移除 {count} 个客户端。",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "重启 Xray",
+7 -3
View File
@@ -1171,8 +1171,8 @@
"totalUpDown": "總上傳 / 下載",
"addGroup": "新增群組",
"createSuccess": "已建立群組「{name}」。",
"rename": "重新命名",
"renameTitle": "重新命名 {name}",
"editGroup": "Edit group",
"editGroupTitle": "Edit group \"{name}\"",
"renameCollision": "已存在名為「{name}」的群組。",
"renameSuccess": "已為 {count} 個客戶端重新命名群組。",
"deleteConfirmTitle": "刪除群組 {name}?",
@@ -1198,7 +1198,11 @@
"removeFromGroup": "移除客戶端…",
"removeFromGroupTitle": "從群組「{name}」移除客戶端",
"removeFromGroupDesc": "選擇要從此群組移除的成員。客戶端本身保留(用「刪除群組中的客戶端」完全移除)。",
"removeFromGroupResult": "已從 {name} 移除 {count} 個客戶端。"
"removeFromGroupResult": "已從 {name} 移除 {count} 個客戶端。",
"hostRules": "Host rules",
"hostRulesHint": "Select the host rules every client in this group should receive. These replace the inbound's default host pool for members; other clients are unaffected.",
"hostRulesPlaceholder": "Select host rules",
"hostRulesSaved": "Host rules updated for {name}."
},
"nodes": {
"restartXray": "重新啟動 Xray",