mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-08-15 15:50:59 +00:00
d7698ec7aa
* feat(xray): browse geosite/geoip categories from routing rules Routing rules made you type category names from memory: nothing showed which categories a database actually contains, what is inside one, or whether a name resolves at all — a typo only surfaced when Xray refused the config. The panel now reads Xray's .dat databases itself and exposes them over four endpoints: databases in the asset folder, a database's categories, one page of a category's rules, and validation of the tokens already in a rule. The reader walks the protobuf wire format directly rather than decoding into Go structs, because a 10 MB geosite.dat holds well over a million domains and materialising them costs ~284 MB where streaming costs ~19 MB. Only the category index is cached, entry pages are scanned on demand, and scans are serialised, so twenty concurrent requests peak at 87 MB instead of 1 GB. A database's type is decided by its contents, not its file name, since custom .dat files are named freely. In the rule form, the source-IP, IP and domain fields gain a database button opening the browser: search over categories, a preview of what a category holds, and a multi-select that merges into the field. Plain domains, CIDRs and categories the panel does not know are left untouched; categories already present come back ticked, and unticking one removes it from the rule. * fix(xray): read geo databases through os.Root and match codes verbatim CodeQL flagged the database read as a path built from a user-supplied value, and it was right about the shape of it. The file name arrives in a request; resolve() rejects traversal and stats the file through an os.Root, but the read itself went through a joined path with os.ReadFile. That left the symlink defence incomplete: the stat could pass while the read followed a link planted — or swapped in — afterwards. Reads now go through the same root, so a request-supplied name never becomes a path this code resolves on its own, and the size limit is applied to the opened file rather than to a separate stat of it. Lookup no longer trims the category code either. It backs the routing-token validator, and the core matches codes verbatim: "geosite: cn" will not start Xray, so repairing that space here hid exactly the typo the validator exists to report. * fix(xray): address review findings on the geo category browser Asset folder. The browser read config.GetBinFolderPath() unconditionally, but the core honours a preset XRAY_LOCATION_ASSET and only falls back to the bin folder (ensureXrayAssetLocation). On an install pointing at a shared asset directory the panel listed an empty folder and reported perfectly valid geosite:/geoip: tokens as missing — the validator warning about a correct config. The directory is now resolved with the core's precedence. Paging. Serving one page read and rescanned the whole database, so walking category-ads-all re-read it per page. The index now records each category's byte range and a page reads only that record through the os.Root handle, with the current category's records held for the duration of a paging session. Profiling that also showed the real cost was not the read but the slice of payload pointers built per call — a category holds a hundred thousand of them — so records are now walked with a callback instead. Ten pages over category-ads-all: 239 MB allocated, now 4.3 MB. Cached failures. Any error from reading a file was latched under the file's size+mtime, so a transient ENOMEM or EMFILE marked a healthy database as damaged until it changed on disk. Only deterministic failures are cached. Wrong kind. A geoip: token typed into a domain field parsed as a plain domain and was waved through, though the core cannot resolve it as one. It is now reported, with its own reason and wording. Frontend. The category filter fed the query key on every keystroke, so each character triggered a request that re-scanned the database; it is debounced now. GeoTokenInput accepts and forwards a ref, so React Hook Form can focus these three fields on a validation error again. A failed validation shows that it failed instead of rendering the same empty state as "no issues". Also drops an unreachable branch in the token-count guard and corrects the categories endpoint docs, where limit is unbounded by default. --------- Co-authored-by: STRENCH0 <17428017+STRENCH0@users.noreply.github.com>
208 lines
8.3 KiB
TypeScript
208 lines
8.3 KiB
TypeScript
import type { ReactNode } from 'react';
|
|
import { render, screen, waitFor, within } from '@testing-library/react';
|
|
import userEvent from '@testing-library/user-event';
|
|
import { QueryClientProvider } from '@tanstack/react-query';
|
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
|
|
import GeoBrowserModal from '@/components/geodata/GeoBrowserModal';
|
|
import GeoTokenInput from '@/components/geodata/GeoTokenInput';
|
|
import { makeTestQueryClient } from '@/test/test-utils';
|
|
import { HttpUtil, Msg } from '@/utils';
|
|
|
|
afterEach(() => {
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
const FILES = [{ name: 'geosite.dat', kind: 'site', size: 1024, modifiedAt: 1785428467270, categories: 3 }];
|
|
|
|
const IP_FILE = { name: 'geoip.dat', kind: 'ip', size: 2048, modifiedAt: 1785428467270, categories: 1 };
|
|
|
|
const IP_CATEGORIES = { total: 1, items: [{ code: 'private', entries: 1, attributes: [] }] };
|
|
|
|
const CATEGORIES = {
|
|
total: 3,
|
|
items: [
|
|
{ code: 'cn', entries: 2, attributes: [] },
|
|
{ code: 'google', entries: 2, attributes: ['ads'] },
|
|
{ code: 'telegram', entries: 1, attributes: [] },
|
|
],
|
|
};
|
|
|
|
function mockGeodata(files: unknown[] = FILES) {
|
|
const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url: string, params?: unknown) => {
|
|
const requestedFile = (params as { file?: string } | undefined)?.file;
|
|
if (url.includes('/geodata/files')) return new Msg(true, '', files);
|
|
if (url.includes('/geodata/categories')) {
|
|
return new Msg(true, '', requestedFile === 'geoip.dat' ? IP_CATEGORIES : CATEGORIES);
|
|
}
|
|
if (url.includes('/geodata/entries')) return new Msg(true, '', { total: 0, items: [] });
|
|
return new Msg(true, '', null);
|
|
});
|
|
vi.spyOn(HttpUtil, 'post').mockImplementation(async () => new Msg(true, '', []));
|
|
return get;
|
|
}
|
|
|
|
type GetSpy = ReturnType<typeof mockGeodata>;
|
|
|
|
function entryFilters(get: GetSpy): string[] {
|
|
return get.mock.calls
|
|
.filter(([url]) => String(url).includes('/geodata/entries'))
|
|
.map(([, params]) => (params as { q?: string } | undefined)?.q ?? '');
|
|
}
|
|
|
|
function wrapper({ children }: { children: ReactNode }) {
|
|
return <QueryClientProvider client={makeTestQueryClient()}>{children}</QueryClientProvider>;
|
|
}
|
|
|
|
async function checkboxFor(code: string) {
|
|
const cell = await screen.findByText(code);
|
|
const row = cell.closest('.ant-table-row');
|
|
if (!row) throw new Error(`row for ${code} not found`);
|
|
return within(row as HTMLElement).getByRole('checkbox') as HTMLInputElement;
|
|
}
|
|
|
|
describe('GeoBrowserModal selection', () => {
|
|
it('seeds the selection from the field every time it opens', async () => {
|
|
mockGeodata();
|
|
const view = render(
|
|
<GeoBrowserModal open kind="site" value="geosite:google" onApply={vi.fn()} onClose={vi.fn()} />,
|
|
{ wrapper },
|
|
);
|
|
|
|
await waitFor(async () => expect((await checkboxFor('google')).checked).toBe(true));
|
|
|
|
view.rerender(
|
|
<GeoBrowserModal open={false} kind="site" value="geosite:google" onApply={vi.fn()} onClose={vi.fn()} />,
|
|
);
|
|
view.rerender(
|
|
<GeoBrowserModal open kind="site" value="geosite:google" onApply={vi.fn()} onClose={vi.fn()} />,
|
|
);
|
|
|
|
await waitFor(async () => expect((await checkboxFor('google')).checked).toBe(true));
|
|
expect((await checkboxFor('cn')).checked).toBe(false);
|
|
});
|
|
|
|
it('keeps selections that the search box has filtered out of view', async () => {
|
|
mockGeodata();
|
|
const user = userEvent.setup();
|
|
const onApply = vi.fn();
|
|
render(<GeoBrowserModal open kind="site" value="" onApply={onApply} onClose={vi.fn()} />, { wrapper });
|
|
|
|
await user.click(await checkboxFor('google'));
|
|
await user.type(screen.getByPlaceholderText(/search category|поиск категории/i), 'cn');
|
|
await waitFor(() => expect(screen.queryByText('google')).toBeNull());
|
|
await user.click(await checkboxFor('cn'));
|
|
|
|
await user.click(screen.getByRole('button', { name: /apply|применить/i }));
|
|
|
|
expect(onApply).toHaveBeenCalledTimes(1);
|
|
const applied = String(onApply.mock.calls[0][0]);
|
|
expect(applied.split(',').map((token) => token.trim()).sort()).toEqual(['geosite:cn', 'geosite:google']);
|
|
});
|
|
|
|
it('drops a category from the field when its checkbox is cleared', async () => {
|
|
mockGeodata();
|
|
const user = userEvent.setup();
|
|
const onApply = vi.fn();
|
|
render(
|
|
<GeoBrowserModal open kind="site" value="google.com, geosite:google, geosite:blabla" onApply={onApply} onClose={vi.fn()} />,
|
|
{ wrapper },
|
|
);
|
|
|
|
await waitFor(async () => expect((await checkboxFor('google')).checked).toBe(true));
|
|
await user.click(await checkboxFor('google'));
|
|
await user.click(screen.getByRole('button', { name: /apply|применить/i }));
|
|
|
|
expect(onApply).toHaveBeenCalledWith('google.com, geosite:blabla');
|
|
});
|
|
|
|
it('offers only databases matching the field kind', async () => {
|
|
mockGeodata([...FILES, IP_FILE]);
|
|
render(<GeoBrowserModal open kind="ip" value="" onApply={vi.fn()} onClose={vi.fn()} />, { wrapper });
|
|
|
|
await screen.findByText('private');
|
|
expect(screen.getByTitle('geoip.dat')).toBeTruthy();
|
|
expect(screen.queryByText('google')).toBeNull();
|
|
});
|
|
|
|
it('does not seed one database from another database categories', async () => {
|
|
mockGeodata([...FILES, IP_FILE]);
|
|
const user = userEvent.setup();
|
|
render(
|
|
<GeoBrowserModal open kind="site" value="geosite:cn" onApply={vi.fn()} onClose={vi.fn()} />,
|
|
{ wrapper },
|
|
);
|
|
|
|
await waitFor(async () => expect((await checkboxFor('cn')).checked).toBe(true));
|
|
await user.click(await checkboxFor('google'));
|
|
await waitFor(async () => expect((await checkboxFor('google')).checked).toBe(true));
|
|
expect(screen.queryByText('private')).toBeNull();
|
|
});
|
|
|
|
it('waits for the entry filter to settle instead of querying every keystroke', async () => {
|
|
const get = mockGeodata();
|
|
const user = userEvent.setup({ delay: null });
|
|
render(<GeoBrowserModal open kind="site" value="" onApply={vi.fn()} onClose={vi.fn()} />, { wrapper });
|
|
|
|
await user.click(await screen.findByText('cn'));
|
|
await waitFor(() => expect(entryFilters(get)).toEqual(['']));
|
|
|
|
await user.type(screen.getByPlaceholderText('Filter inside category'), 'abcd');
|
|
expect(entryFilters(get)).toEqual(['']);
|
|
|
|
await waitFor(() => expect(entryFilters(get)).toEqual(['', 'abcd']), { timeout: 3000 });
|
|
});
|
|
|
|
it('drops the pending filter when another category is opened', async () => {
|
|
const get = mockGeodata();
|
|
const user = userEvent.setup({ delay: null });
|
|
render(<GeoBrowserModal open kind="site" value="" onApply={vi.fn()} onClose={vi.fn()} />, { wrapper });
|
|
|
|
await user.click(await screen.findByText('cn'));
|
|
await user.type(screen.getByPlaceholderText('Filter inside category'), 'abcd');
|
|
await user.click(screen.getByText('telegram'));
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
expect(entryFilters(get)).toEqual(['', '']);
|
|
});
|
|
|
|
it('ticks and unticks a category written in its long ext form', async () => {
|
|
mockGeodata();
|
|
const user = userEvent.setup();
|
|
const onApply = vi.fn();
|
|
render(
|
|
<GeoBrowserModal
|
|
open
|
|
kind="site"
|
|
value="ext:geosite.dat:cn, google.com"
|
|
onApply={onApply}
|
|
onClose={vi.fn()}
|
|
/>,
|
|
{ wrapper },
|
|
);
|
|
|
|
await waitFor(async () => expect((await checkboxFor('cn')).checked).toBe(true));
|
|
await user.click(await checkboxFor('cn'));
|
|
await user.click(screen.getByRole('button', { name: /apply|применить/i }));
|
|
|
|
expect(onApply).toHaveBeenCalledWith('google.com');
|
|
});
|
|
});
|
|
|
|
describe('GeoTokenInput validation feedback', () => {
|
|
it('says the check failed instead of dropping the warnings silently', async () => {
|
|
vi.spyOn(HttpUtil, 'get').mockResolvedValue(new Msg(true, '', []));
|
|
vi.spyOn(HttpUtil, 'post')
|
|
.mockResolvedValueOnce(new Msg(true, '', [{ token: 'geosite:nope', reason: 'categoryMissing' }]))
|
|
.mockResolvedValue(new Msg(false, 'too many tokens'));
|
|
|
|
const view = render(<GeoTokenInput kind="domain" value="geosite:nope" />, { wrapper });
|
|
await screen.findByText(/Not in the database/, {}, { timeout: 3000 });
|
|
|
|
view.rerender(<GeoTokenInput kind="domain" value="geosite:nope, geosite:other" />);
|
|
|
|
await screen.findByText('Could not check these values against the geo databases', {}, { timeout: 3000 });
|
|
expect(screen.queryByText(/Not in the database/)).toBeNull();
|
|
});
|
|
});
|