fix(routing): bound client suggestions in the user picker (#7338)

Replace the eager unpaged client catalog request in the routing rule editor with an admin-only, email-only suggestions endpoint. Project the email column in SQL, enforce a fixed 50-result limit, and use parameterized literal substring matching with request cancellation.

Fetch only while the User picker is open, debounce nonempty searches by 250 ms, and cancel superseded queries. Preserve saved and manual tags, comma-separated entry, the routing rule user array, and Save when suggestions fail.

Add HTTP regression coverage for 50,002 records, token scopes, response shape and literal wildcards, component coverage for stale requests and tag preservation, and browser stories for 1k/10k/50k synthetic catalogs. Update OpenAPI and API reference.

Reviewed head: c01ec35f99. All 13 CI/Docs jobs on the PR head passed. A detached local test merge against main ef99e67507 completed without conflicts; regenerated Go schemas and OpenAPI matched the staged merge, with identical frontend/docs OpenAPI copies (101 schemas, 214 paths, 227 operations). Full CI on the latest integrated tree and independent PostgreSQL-specific execution were not performed. See https://github.com/MHSanaei/3x-ui/pull/7338#issuecomment-7363795973.

Closes #7329
This commit is contained in:
Hamed
2026-12-03 04:38:56 +03:30
committed by GitHub
parent ef99e67507
commit d6afe0ef3c
18 changed files with 673 additions and 92 deletions
@@ -20,6 +20,9 @@ _openapi:
the eligible IDs that match the given search and group for the chosen
source and targets.
url: '#list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets'
- depth: 2
title: Return up to 50 client emails for the routing rule user picker.
url: '#return-up-to-50-client-emails-for-the-routing-rule-user-picker'
- depth: 2
title: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
@@ -412,6 +415,8 @@ _openapi:
the eligible IDs that match the given search and group for the chosen
source and targets.
id: list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets
- content: Return up to 50 client emails for the routing rule user picker.
id: return-up-to-50-client-emails-for-the-routing-rule-user-picker
- content: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
@@ -1031,7 +1036,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/attachCandidates","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkAttach/{id}","method":"get"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/attachCandidates","method":"get"},{"path":"/panel/api/clients/userSuggestions","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkAttach/{id}","method":"get"},{"path":"/panel/api/clients/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 />
</>
);
}
+70
View File
@@ -2611,6 +2611,24 @@
],
"type": "object"
},
"ClientEmailSuggestions": {
"properties": {
"emails": {
"example": [
"alice@example.com",
"bob@example.com"
],
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"emails"
],
"type": "object"
},
"ClientInbound": {
"properties": {
"clientId": {
@@ -10645,6 +10663,58 @@
}
}
},
"/panel/api/clients/userSuggestions": {
"get": {
"tags": [
"Clients"
],
"summary": "Return up to 50 client emails for the routing rule user picker.",
"operationId": "get_panel_api_clients_userSuggestions",
"parameters": [
{
"name": "search",
"in": "query",
"required": false,
"description": "Optional case-insensitive substring. Percent and underscore are literal.",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/ClientEmailSuggestions"
}
}
},
"example": {
"success": true,
"obj": {
"emails": [
"alice@example.com",
"bob@example.com"
]
}
}
}
}
}
}
}
},
"/panel/api/clients/list/paged": {
"get": {
"tags": [
+70
View File
@@ -2611,6 +2611,24 @@
],
"type": "object"
},
"ClientEmailSuggestions": {
"properties": {
"emails": {
"example": [
"alice@example.com",
"bob@example.com"
],
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"emails"
],
"type": "object"
},
"ClientInbound": {
"properties": {
"clientId": {
@@ -10645,6 +10663,58 @@
}
}
},
"/panel/api/clients/userSuggestions": {
"get": {
"tags": [
"Clients"
],
"summary": "Return up to 50 client emails for the routing rule user picker.",
"operationId": "get_panel_api_clients_userSuggestions",
"parameters": [
{
"name": "search",
"in": "query",
"required": false,
"description": "Optional case-insensitive substring. Percent and underscore are literal.",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {
"$ref": "#/components/schemas/ClientEmailSuggestions"
}
}
},
"example": {
"success": true,
"obj": {
"emails": [
"alice@example.com",
"bob@example.com"
]
}
}
}
}
}
}
}
},
"/panel/api/clients/list/paged": {
"get": {
"tags": [
+41 -25
View File
@@ -1,33 +1,49 @@
import { useQuery } from '@tanstack/react-query';
import { z } from 'zod';
import { skipToken, useQuery } from '@tanstack/react-query';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { keys } from '@/api/queryKeys';
import { ClientRecordSchema, type ClientRecord } from '@/schemas/client';
import { ClientEmailSuggestionsSchema } from '@/generated/zod';
const ClientRecordListSchema = z
.array(ClientRecordSchema)
.nullable()
.transform((value) => value ?? []);
const suggestionsSchema = ClientEmailSuggestionsSchema.extend({
emails: ClientEmailSuggestionsSchema.shape.emails.max(50),
});
async function fetchClients(): Promise<ClientRecord[]> {
const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true });
if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients');
const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list');
return validated.obj ?? [];
}
export function useClientOptions(enabled = true) {
return useQuery({
queryKey: keys.clients.all(),
queryFn: fetchClients,
enabled,
staleTime: 30_000,
select: (clients) =>
clients
.map((client) => client.email.trim())
.filter(Boolean)
.sort((a, b) => a.localeCompare(b)),
function waitForTyping(signal: AbortSignal) {
return new Promise<void>((resolve, reject) => {
signal.throwIfAborted();
function cancel() {
clearTimeout(timer);
reject(signal.reason);
}
const timer = setTimeout(() => {
signal.removeEventListener('abort', cancel);
resolve();
}, 250);
signal.addEventListener('abort', cancel, { once: true });
});
}
async function fetchClientOptions(search: string, signal: AbortSignal): Promise<string[]> {
if (search) await waitForTyping(signal);
const msg = await HttpUtil.get(
'/panel/api/clients/userSuggestions',
{ search },
{ signal, silent: true },
);
if (!msg.success || msg.obj == null)
throw new Error(msg.msg || 'Failed to load user suggestions');
return (
parseMsg(msg, suggestionsSchema, 'clients/userSuggestions', { strict: true }).obj?.emails ?? []
);
}
export function useClientOptions(search: string | null) {
return useQuery({
queryKey: keys.clients.userSuggestions(search),
queryFn: search === null ? skipToken : ({ signal }) => fetchClientOptions(search, signal),
staleTime: 30_000,
gcTime: 60_000,
retry: false,
});
}
+1
View File
@@ -37,6 +37,7 @@ export const keys = {
root: () => ['clients'] as const,
list: (params: unknown) => ['clients', 'list', params] as const,
all: () => ['clients', 'all'] as const,
userSuggestions: (search: string | null) => ['clients', 'userSuggestions', search] as const,
onlines: () => ['clients', 'onlines'] as const,
onlinesByGuid: () => ['clients', 'onlinesByGuid'] as const,
activeInbounds: () => ['clients', 'activeInbounds'] as const,
+6
View File
@@ -688,6 +688,12 @@ export const EXAMPLES: Record<string, unknown> = {
"oldValue": "10737418240",
"source": "panel"
},
"ClientEmailSuggestions": {
"emails": [
"alice@example.com",
"bob@example.com"
]
},
"ClientInbound": {
"clientId": 0,
"createdAt": 0,
+18
View File
@@ -2585,6 +2585,24 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"ClientEmailSuggestions": {
"properties": {
"emails": {
"example": [
"alice@example.com",
"bob@example.com"
],
"items": {
"type": "string"
},
"type": "array"
}
},
"required": [
"emails"
],
"type": "object"
},
"ClientInbound": {
"properties": {
"clientId": {
+4
View File
@@ -610,6 +610,10 @@ export interface ClientChangeLog {
source: string;
}
export interface ClientEmailSuggestions {
emails: string[];
}
export interface ClientInbound {
clientId: number;
createdAt: number;
+5
View File
@@ -645,6 +645,11 @@ export const ClientChangeLogSchema = z.object({
});
export type ClientChangeLog = z.infer<typeof ClientChangeLogSchema>;
export const ClientEmailSuggestionsSchema = z.object({
emails: z.array(z.string()),
});
export type ClientEmailSuggestions = z.infer<typeof ClientEmailSuggestionsSchema>;
export const ClientInboundSchema = z.object({
clientId: z.number().int(),
createdAt: z.number().int(),
+15
View File
@@ -1123,6 +1123,21 @@ export const sections: readonly Section[] = [
],
responseSchema: 'AttachCandidatePage',
},
{
method: 'GET',
path: '/panel/api/clients/userSuggestions',
summary: 'Return up to 50 client emails for the routing rule user picker.',
params: [
{
name: 'search',
in: 'query',
type: 'string',
desc: 'Optional case-insensitive substring. Percent and underscore are literal.',
optional: true,
},
],
responseSchema: 'ClientEmailSuggestions',
},
{
method: 'GET',
path: '/panel/api/clients/list/paged',
@@ -0,0 +1,134 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, waitFor, within } from 'storybook/test';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useState } from 'react';
import type { ComponentProps, ReactNode } from 'react';
import { ThemeProvider } from '@/hooks/useTheme';
import { AntdRootConfig } from '@/i18n/AntdRootConfig';
import { HttpUtil, Msg } from '@/utils';
import RuleFormModal from './RuleFormModal';
function QueryFixture({ children }: { children: ReactNode }) {
const [client] = useState(
() => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
);
return (
<QueryClientProvider client={client}>
<AntdRootConfig>
<ThemeProvider>{children}</ThemeProvider>
</AntdRootConfig>
</QueryClientProvider>
);
}
function RoutingRuleFixture(props: ComponentProps<typeof RuleFormModal>) {
const [open, setOpen] = useState(props.open);
return (
<RuleFormModal
{...props}
open={open}
onClose={() => {
props.onClose();
setOpen(false);
}}
onConfirm={(rule) => {
props.onConfirm(rule);
setOpen(false);
}}
/>
);
}
const meta = {
title: 'Xray/Routing Rule',
component: RuleFormModal,
render: (args) => <RoutingRuleFixture {...args} />,
decorators: [
(Story) => (
<QueryFixture>
<Story />
</QueryFixture>
),
],
args: {
open: true,
rule: { user: ['existing@test'], outboundTag: 'direct' },
inboundTags: [],
outboundTags: ['direct'],
balancerTags: [],
onClose: fn(),
onConfirm: fn(),
},
} satisfies Meta<typeof RuleFormModal>;
export default meta;
type Story = StoryObj<typeof meta>;
function largeCatalog(size: number): Story {
const requests: Array<{ path: string; search: string; count: number }> = [];
const target = `client-${size}@test`;
const legacyList = '/panel/api/clients/list';
const suggestionsPath = '/panel/api/clients/userSuggestions';
return {
beforeEach: () => {
requests.length = 0;
const get = HttpUtil.get;
const fixture = Array.from({ length: size }, (_, index) => `client-${index + 1}@test`);
HttpUtil.get = async <T,>(path: string, params?: unknown) => {
if (path === legacyList) {
requests.push({ path, search: '', count: size });
return new Msg<T>(true, '', fixture.map((email) => ({ email })) as T);
}
if (path === suggestionsPath) {
const { search } = params as { search: string };
const emails = fixture.filter((email) => email.includes(search)).slice(0, 50);
requests.push({ path, search, count: emails.length });
return new Msg<T>(true, '', { emails } as T);
}
return new Msg<T>(true, '', [] as T);
};
return () => {
HttpUtil.get = get;
};
},
play: async ({ args, canvasElement, userEvent }) => {
const screen = within(canvasElement.ownerDocument.body);
const dialog = await screen.findByRole('dialog');
const picker = within(dialog).getByRole('combobox', { name: 'User' });
await expect(requests).toEqual([]);
await userEvent.click(picker);
await waitFor(() =>
expect(requests).toEqual([{ path: suggestionsPath, search: '', count: 50 }]),
);
const search = target.replace('client-', '');
await userEvent.type(picker, search);
const option = await screen.findByText(target, {
selector: '.ant-select-item-option-content',
});
await userEvent.click(option);
await userEvent.type(picker, 'manual@test,existing@test,');
await expect(screen.getByRole('button', { name: 'Remove existing@test' })).toBeVisible();
await expect(screen.getByRole('button', { name: `Remove ${target}` })).toBeVisible();
await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
await expect(args.onConfirm).toHaveBeenCalledWith(
expect.objectContaining({
user: ['existing@test', target, 'manual@test'],
outboundTag: 'direct',
}),
);
await expect(requests.filter(({ search }) => search)).toEqual([
{ path: suggestionsPath, search, count: 1 },
]);
await expect(
requests.every(({ path, count }) => path === suggestionsPath && count <= 50),
).toBe(true);
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
},
};
}
export const Thousand = largeCatalog(1_000);
export const TenThousand = largeCatalog(10_000);
export const FiftyThousand = largeCatalog(50_000);
@@ -1,4 +1,4 @@
import { useEffect, useMemo } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, Modal, Select, Space, Switch } from 'antd';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
@@ -71,6 +71,73 @@ function csv(value: string): string[] {
.filter(Boolean);
}
function RoutingUserField({ active }: { active: boolean }) {
const { t } = useTranslation();
const [pickerOpen, setPickerOpen] = useState(false);
const [search, setSearch] = useState('');
const { data, isFetching, isError } = useClientOptions(
active && pickerOpen ? search.trim() : null,
);
const user = useWatch<RuleFormValues, 'user'>({ name: 'user' }) ?? '';
const selectedUsers = useMemo(() => csv(user), [user]);
const options = useMemo(
() =>
[...new Set([...(data ?? []), ...selectedUsers])].map((email) => ({
value: email,
label: email,
})),
[data, selectedUsers],
);
const status = isFetching
? t('loading')
: isError
? t('pages.xray.ruleForm.userLoadError')
: !data?.length
? t('pages.xray.ruleForm.userEmpty')
: undefined;
const showStatusInMenu = Boolean(search || options.length);
return (
<FormField
name="user"
label={t('pages.xray.ruleForm.user')}
tooltip={t('pages.xray.rules.useComma')}
transform={{
input: (value) => csv(typeof value === 'string' ? value : ''),
output: (value) => (Array.isArray(value) ? value.join(',') : ''),
}}
onAfterChange={() => setSearch('')}
>
<Select
mode="tags"
tagRender={selectTagRender}
tokenSeparators={[',']}
allowClear
loading={isFetching}
placeholder={t('pages.xray.ruleForm.userPlaceholder')}
open={active && pickerOpen}
onOpenChange={(next) => {
setPickerOpen(next);
if (!next) setSearch('');
}}
showSearch={{ searchValue: search, onSearch: setSearch, filterOption: false }}
notFoundContent={<span role="status">{status}</span>}
popupRender={(menu) => (
<>
{menu}
{showStatusInMenu && status && (
<div role="status" className="px-8 py-4">
{status}
</div>
)}
</>
)}
options={options}
/>
</FormField>
);
}
export default function RuleFormModal({
open,
rule,
@@ -86,21 +153,6 @@ export default function RuleFormModal({
const { data: inboundOptions } = useInboundOptions();
const remarkByTag = useMemo(() => buildRemarkByTag(inboundOptions || []), [inboundOptions]);
const {
data: clientEmails = [],
isFetching: clientsLoading,
isError: clientsError,
} = useClientOptions(open);
const user = useWatch({ control: methods.control, name: 'user' }) ?? '';
const selectedUsers = useMemo(() => csv(user), [user]);
const userOptions = useMemo(
() =>
[...new Set([...clientEmails, ...selectedUsers])].map((email) => ({
value: email,
label: email,
})),
[clientEmails, selectedUsers],
);
useEffect(() => {
if (!open) return;
@@ -286,33 +338,7 @@ export default function RuleFormModal({
<GeoTokenInput kind="domain" placeholder="google.com, geosite:cn" />
</FormField>
<FormField
name="user"
label={t('pages.xray.ruleForm.user')}
tooltip={t('pages.xray.rules.useComma')}
transform={{
input: (value) => csv(typeof value === 'string' ? value : ''),
output: (value) => (Array.isArray(value) ? value.join(',') : ''),
}}
>
<Select
mode="tags"
tagRender={selectTagRender}
tokenSeparators={[',']}
allowClear
loading={clientsLoading}
placeholder={t('pages.xray.ruleForm.userPlaceholder')}
showSearch={{ optionFilterProp: 'label' }}
notFoundContent={
clientsLoading
? t('loading')
: clientsError
? t('pages.xray.ruleForm.userLoadError')
: t('pages.xray.ruleForm.userEmpty')
}
options={userOptions}
/>
</FormField>
<RoutingUserField key={String(open)} active={open} />
<FormField
name="port"
@@ -0,0 +1,72 @@
import { act, fireEvent, screen, waitFor } from '@testing-library/react';
import { afterEach, expect, it, vi } from 'vitest';
import RuleFormModal, { type RoutingRule } from '@/pages/xray/routing/RuleFormModal';
import { HttpUtil, Msg } from '@/utils';
import { renderWithProviders } from './test-utils';
const suggestionsURL = '/panel/api/clients/userSuggestions';
function renderRule(rule: RoutingRule | null = null) {
const onConfirm = vi.fn();
renderWithProviders(
<RuleFormModal
open
rule={rule}
inboundTags={[]}
outboundTags={[]}
balancerTags={[]}
onClose={vi.fn()}
onConfirm={onConfirm}
/>,
);
const input = screen.getByRole('combobox', { name: 'User' });
return { input, onConfirm };
}
afterEach(() => vi.restoreAllMocks());
it('defers requests until the picker opens, debounces, and discards a late response', async () => {
let respondToOldSearch: ((value: Msg<unknown>) => void) | undefined;
const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url, params) => {
if (url !== suggestionsURL) return new Msg(true, '', []);
const { search } = params as { search: string };
if (search === 'old') return new Promise((resolve) => (respondToOldSearch = resolve));
return new Msg(true, '', { emails: search === 'new' ? ['new-user@test'] : [] });
});
const requests = () => get.mock.calls.filter(([url]) => url.startsWith('/panel/api/clients/'));
const { input } = renderRule();
expect(requests()).toEqual([]);
fireEvent.change(input, { target: { value: 'old' } });
await waitFor(() => expect(respondToOldSearch).toBeTypeOf('function'));
await act(async () => {
fireEvent.change(input, { target: { value: 'n' } });
fireEvent.change(input, { target: { value: 'ne' } });
fireEvent.change(input, { target: { value: 'new' } });
});
expect(requests()).toHaveLength(1);
expect(requests()[0][2]?.signal?.aborted).toBe(true);
await screen.findByRole('option', { name: 'new-user@test' });
await act(async () => {
respondToOldSearch?.(new Msg(true, '', { emails: ['old-user@test'] }));
});
expect(screen.queryByRole('option', { name: 'old-user@test' })).toBeNull();
expect(requests().map(([, params]) => params)).toEqual([{ search: 'old' }, { search: 'new' }]);
});
it('preserves selected users and saves comma-delimited tags even when suggestions fail', async () => {
vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) =>
url === suggestionsURL ? new Msg(false, 'offline') : new Msg(true, '', []),
);
const { input, onConfirm } = renderRule({ user: 'saved@test,remove@test' });
fireEvent.change(input, { target: { value: 'typed' } });
await screen.findByText('Could not load users');
expect(screen.getByRole('button', { name: 'Remove saved@test' })).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Remove remove@test' }));
fireEvent.change(input, { target: { value: 'manual@test,saved@test,manual@test,' } });
fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
expect(onConfirm).toHaveBeenCalledWith(
expect.objectContaining({ user: ['saved@test', 'manual@test'] }),
);
});
@@ -3,10 +3,18 @@ import { fireEvent, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import RuleFormModal from '@/pages/xray/routing/RuleFormModal';
import { keys } from '@/api/queryKeys';
import { HttpUtil, Msg } from '@/utils';
import { chooseSelectOption, renderWithProviders } from './test-utils';
import { renderWithProviders } from './test-utils';
function mockUserSuggestions(...emails: string[]) {
return vi
.spyOn(HttpUtil, 'get')
.mockImplementation(
async (path) =>
new Msg(true, '', path === '/panel/api/clients/userSuggestions' ? { emails } : []),
);
}
describe('RuleFormModal edit preserves unsurfaced fields', () => {
afterEach(() => vi.restoreAllMocks());
@@ -37,12 +45,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('selects existing clients for the user criterion', async () => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(
new Msg(true, '', [
{ id: 1, email: 'alice@example.com' },
{ id: 2, email: 'bob@example.com' },
]),
);
const get = mockUserSuggestions('alice@example.com', 'bob@example.com');
const onConfirm = vi.fn();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -59,16 +62,19 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
{ queryClient },
);
await waitFor(() =>
expect(HttpUtil.get).toHaveBeenCalledWith('/panel/api/clients/list', undefined, {
silent: true,
}),
);
await waitFor(() => expect(queryClient.getQueryData(keys.clients.all())).toHaveLength(2));
const userField = screen.getByLabelText('User');
const userField = screen.getByRole('combobox', { name: 'User' });
expect(screen.getByText('Select users')).toBeTruthy();
chooseSelectOption(userField.id, 'alice@example.com');
chooseSelectOption(userField.id, 'bob@example.com');
fireEvent.mouseDown(userField);
for (const email of ['alice@example.com', 'bob@example.com']) {
fireEvent.click(
await screen.findByText(email, { selector: '.ant-select-item-option-content' }),
);
}
expect(get).toHaveBeenCalledWith(
'/panel/api/clients/userSuggestions',
{ search: '' },
expect.objectContaining({ silent: true }),
);
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
expect(onConfirm).toHaveBeenCalledWith(
@@ -77,9 +83,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('preserves a saved user that is no longer in the client list', async () => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(
new Msg(true, '', [{ id: 1, email: 'alice@example.com' }]),
);
mockUserSuggestions('alice@example.com');
const onConfirm = vi.fn();
renderWithProviders(
@@ -103,9 +107,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('accepts a custom user identifier that is not a client record', async () => {
vi.spyOn(HttpUtil, 'get').mockResolvedValue(
new Msg(true, '', [{ id: 1, email: 'alice@example.com' }]),
);
mockUserSuggestions('alice@example.com');
const onConfirm = vi.fn();
renderWithProviders(
+6
View File
@@ -54,6 +54,7 @@ func NewClientController(g *gin.RouterGroup) *ClientController {
func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/list/paged", a.listPaged)
g.GET("/userSuggestions", a.userSuggestions)
g.GET("/attachCandidates", a.attachCandidates)
g.GET("/get", a.get)
g.GET("/get/:email", a.get)
@@ -155,6 +156,11 @@ func (a *ClientController) attachCandidates(c *gin.Context) {
jsonObj(c, result, nil)
}
func (a *ClientController) userSuggestions(c *gin.Context) {
result, err := a.clientService.ListUserSuggestions(c.Request.Context(), c.Query("search"))
jsonObj(c, result, err)
}
func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, error) {
inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id)
if err != nil {
@@ -0,0 +1,97 @@
package controller
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"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/testpg"
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
)
func TestClientUserSuggestionsHTTP(t *testing.T) {
cleanup, err := testpg.IsolatePackage("routing_user_suggestions")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
router, api := newAPIAuthTestEngine(t)
NewClientController(router.Group("/base/panel/api/clients", api.checkAPIAuth, api.enforceTokenScope))
db := database.GetDB()
for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} {
token := model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Enabled: true, Scope: scope}
if err := db.Create(&token).Error; err != nil {
t.Fatal(err)
}
}
seeds := []model.ClientRecord{
{Email: "literal_%@test", Password: "private", Group: "ignored"},
{Email: "literal_ab@test", Comment: "only-in-a-comment"},
}
if err := db.Create(&seeds).Error; err != nil {
t.Fatal(err)
}
clients := make([]model.ClientRecord, 50000)
for i := range clients {
clients[i] = model.ClientRecord{Email: fmt.Sprintf("fixture-%05d@test", i)}
}
if err := db.CreateInBatches(&clients, 100).Error; err != nil {
t.Fatal(err)
}
request := func(scope, search string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, "/base/panel/api/clients/userSuggestions?search="+url.QueryEscape(search)+"&pageSize=50000", nil)
req.Header.Set("X-Requested-With", "XMLHttpRequest")
if scope != "" {
req.Header.Set("Authorization", "Bearer "+scope)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
for _, scope := range []string{"", model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} {
want := http.StatusForbidden
if scope == "" {
want = http.StatusUnauthorized
}
if got := request(scope, "fixture"); got.Code != want {
t.Errorf("scope %q: status = %d, want %d", scope, got.Code, want)
}
}
for _, tt := range []struct {
search string
count int
first string
}{
{"", 50, "fixture-00000@test"},
{"FIXTURE-", 50, "fixture-00000@test"},
{"49999@", 1, "fixture-49999@test"},
{" LITERAL_% ", 1, "literal_%@test"},
{"only-in-a-comment", 0, ""},
} {
t.Run(tt.search, func(t *testing.T) {
w := request(model.ApiScopeAdmin, tt.search)
var body struct {
Success bool `json:"success"`
Msg string `json:"msg"`
Obj struct {
Emails []string `json:"emails"`
} `json:"obj"`
}
decoder := json.NewDecoder(w.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&body); w.Code != http.StatusOK || err != nil || !body.Success {
t.Fatalf("status = %d, response = %+v, error = %v", w.Code, body, err)
}
emails := body.Obj.Emails
if emails == nil || len(emails) != tt.count || !slices.IsSorted(emails) || (tt.count > 0 && emails[0] != tt.first) {
t.Fatalf("search %q: emails = %v, want %d starting with %q", tt.search, emails, tt.count, tt.first)
}
})
}
}
@@ -0,0 +1,33 @@
package service
import (
"context"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const clientEmailSuggestionLimit = 50
type ClientEmailSuggestions struct {
Emails []string `json:"emails" example:"[\"alice@example.com\",\"bob@example.com\"]"`
}
func (s *ClientService) ListUserSuggestions(ctx context.Context, search string) (ClientEmailSuggestions, error) {
query := database.GetDB().WithContext(ctx).Model(&model.ClientRecord{}).Where("email <> ''")
if search = strings.TrimSpace(search); search != "" {
like := func(value string) string { return "%" + escapeLikeLiteral(value) + "%" }
variants := caseVariants(search)
conditions := []string{"LOWER(email) LIKE ? ESCAPE '\\'"}
args := []any{like(variants[0])}
for _, variant := range variants {
conditions = append(conditions, "email LIKE ? ESCAPE '\\'")
args = append(args, like(variant))
}
query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
}
result := ClientEmailSuggestions{Emails: make([]string, 0, clientEmailSuggestionLimit)}
err := query.Order("email").Limit(clientEmailSuggestionLimit).Pluck("email", &result.Emails).Error
return result, err
}
+1
View File
@@ -115,6 +115,7 @@ func run(root, outDir string) error {
"ClientRenewalPreviewRequest",
"ClientRenewalPreview",
"ClientPageResponse",
"ClientEmailSuggestions",
"AttachCandidate",
"AttachCandidatePage",
"AttachSelectionResult",