mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-08-16 00:01:02 +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>
248 lines
9.6 KiB
TypeScript
248 lines
9.6 KiB
TypeScript
import { useEffect, useState, type ReactNode } from 'react';
|
|
import type { Decorator, Meta, StoryObj } from '@storybook/react-vite';
|
|
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
|
import { expect, within } from 'storybook/test';
|
|
import { Space } from 'antd';
|
|
|
|
import { parseTokens } from '@/lib/xray/geoTokens';
|
|
import type { GeoCategory, GeoEntry, GeoFile, GeodataTokenIssue } from '@/generated/types';
|
|
|
|
import GeoTokenInput, { type GeoTokenInputProps } from './GeoTokenInput';
|
|
|
|
type GeoResponder = (query: URLSearchParams, body: URLSearchParams) => unknown;
|
|
type GeoRoutes = Record<string, GeoResponder>;
|
|
|
|
const realFetch = window.fetch.bind(window);
|
|
let activeRoutes: GeoRoutes = {};
|
|
|
|
function requestUrl(input: RequestInfo | URL): URL {
|
|
if (typeof input === 'string') return new URL(input, window.location.origin);
|
|
if (input instanceof URL) return input;
|
|
return new URL(input.url, window.location.origin);
|
|
}
|
|
|
|
function geoFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
|
const url = requestUrl(input);
|
|
const responder = activeRoutes[url.pathname];
|
|
if (!responder) return realFetch(input, init);
|
|
const form = new URLSearchParams(typeof init?.body === 'string' ? init.body : '');
|
|
const body = JSON.stringify({ success: true, msg: '', obj: responder(url.searchParams, form) });
|
|
return Promise.resolve(
|
|
new Response(body, { status: 200, headers: { 'content-type': 'application/json' } }),
|
|
);
|
|
}
|
|
|
|
function activate(routes: GeoRoutes): void {
|
|
activeRoutes = routes;
|
|
window.fetch = geoFetch;
|
|
}
|
|
|
|
function deactivate(routes: GeoRoutes): void {
|
|
if (activeRoutes === routes) activeRoutes = {};
|
|
}
|
|
|
|
function GeoApi({ routes, children }: { routes: GeoRoutes; children: ReactNode }) {
|
|
const [client] = useState(() => {
|
|
activate(routes);
|
|
return new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
|
|
});
|
|
useEffect(() => {
|
|
activate(routes);
|
|
return () => deactivate(routes);
|
|
}, [routes]);
|
|
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
|
|
}
|
|
|
|
const domain = (value: string): GeoEntry => ({ kind: 'domain', value });
|
|
const cidr = (value: string): GeoEntry => ({ kind: 'cidr', value });
|
|
|
|
const SITE_ENTRIES: Record<string, GeoEntry[]> = {
|
|
'category-ads-all': [
|
|
domain('doubleclick.net'), domain('googleadservices.com'), domain('googlesyndication.com'),
|
|
domain('criteo.com'), domain('taboola.com'), domain('outbrain.com'),
|
|
],
|
|
cn: [domain('baidu.com'), domain('qq.com'), domain('taobao.com'), domain('weibo.com'), domain('bilibili.com')],
|
|
google: [
|
|
domain('google.com'), domain('googleapis.com'), domain('gstatic.com'),
|
|
domain('googleusercontent.com'), domain('ggpht.com'), domain('android.com'),
|
|
],
|
|
netflix: [domain('netflix.com'), domain('nflximg.net'), domain('nflxvideo.net'), domain('fast.com')],
|
|
telegram: [domain('telegram.org'), domain('t.me'), domain('telesco.pe'), domain('telegra.ph')],
|
|
youtube: [domain('youtube.com'), domain('youtu.be'), domain('ytimg.com'), domain('googlevideo.com')],
|
|
};
|
|
|
|
const IP_ENTRIES: Record<string, GeoEntry[]> = {
|
|
cloudflare: ['104.16.0.0/13', '172.64.0.0/13', '2606:4700::/32'].map(cidr),
|
|
cn: ['1.0.1.0/24', '36.0.0.0/22', '116.0.0.0/9', '2408:8000::/20'].map(cidr),
|
|
private: [
|
|
'10.0.0.0/8', '127.0.0.0/8', '169.254.0.0/16', '172.16.0.0/12', '192.168.0.0/16',
|
|
'::1/128', 'fc00::/7', 'fe80::/10',
|
|
].map(cidr),
|
|
telegram: ['91.108.4.0/22', '149.154.160.0/20', '2001:b28:f23d::/48'].map(cidr),
|
|
};
|
|
|
|
const SITE_ATTRIBUTES: Record<string, string[]> = {
|
|
google: ['ads', 'cn'],
|
|
youtube: ['ads'],
|
|
};
|
|
|
|
function categoriesOf(
|
|
entries: Record<string, GeoEntry[]>,
|
|
attributes: Record<string, string[]> = {},
|
|
): GeoCategory[] {
|
|
return Object.keys(entries)
|
|
.sort()
|
|
.map((code) => ({ code, entries: entries[code].length, attributes: attributes[code] ?? [] }));
|
|
}
|
|
|
|
const DATASETS: Record<string, { categories: GeoCategory[]; entries: Record<string, GeoEntry[]> }> = {
|
|
'geosite.dat': { categories: categoriesOf(SITE_ENTRIES, SITE_ATTRIBUTES), entries: SITE_ENTRIES },
|
|
'geoip.dat': { categories: categoriesOf(IP_ENTRIES), entries: IP_ENTRIES },
|
|
};
|
|
|
|
const UPDATED_AT = Date.UTC(2026, 6, 24, 3, 12);
|
|
|
|
const FILES: GeoFile[] = [
|
|
{
|
|
name: 'geosite.dat',
|
|
kind: 'site',
|
|
size: 4_812_544,
|
|
modifiedAt: UPDATED_AT,
|
|
categories: DATASETS['geosite.dat'].categories.length,
|
|
},
|
|
{
|
|
name: 'geoip.dat',
|
|
kind: 'ip',
|
|
size: 8_694_272,
|
|
modifiedAt: UPDATED_AT,
|
|
categories: DATASETS['geoip.dat'].categories.length,
|
|
},
|
|
];
|
|
|
|
function referenceOf(token: string, isIP: boolean): { file: string; code: string } | null {
|
|
const [prefix, ...rest] = token.split(':');
|
|
const code = (value: string) => value.split('@')[0].toLowerCase();
|
|
if (prefix === 'geosite') return { file: 'geosite.dat', code: code(rest.join(':')) };
|
|
if (prefix === 'geoip') return { file: 'geoip.dat', code: code(rest.join(':')) };
|
|
if (prefix === 'ext') return { file: rest[0] ?? '', code: code(rest.slice(1).join(':')) };
|
|
return isIP && prefix === 'ext-ip' ? { file: rest[0] ?? '', code: code(rest.slice(1).join(':')) } : null;
|
|
}
|
|
|
|
function validate(tokens: string[], isIP: boolean): GeodataTokenIssue[] {
|
|
const issues: GeodataTokenIssue[] = [];
|
|
for (const token of tokens) {
|
|
const reference = referenceOf(token, isIP);
|
|
if (!reference) continue;
|
|
const dataset = DATASETS[reference.file];
|
|
if (!dataset) {
|
|
issues.push({ token, reason: 'fileMissing', file: reference.file, code: reference.code });
|
|
continue;
|
|
}
|
|
if (!dataset.categories.some((category) => category.code === reference.code)) {
|
|
issues.push({ token, reason: 'categoryMissing', file: reference.file, code: reference.code });
|
|
}
|
|
}
|
|
return issues;
|
|
}
|
|
|
|
const routes: GeoRoutes = {
|
|
'/csrf-token': () => 'storybook-csrf-token',
|
|
'/panel/api/xray/geodata/files': () => FILES,
|
|
'/panel/api/xray/geodata/categories': (query) => {
|
|
const dataset = DATASETS[query.get('file') ?? ''];
|
|
const needle = (query.get('q') ?? '').trim().toLowerCase();
|
|
const items = (dataset?.categories ?? []).filter((category) => category.code.includes(needle));
|
|
return { total: items.length, items };
|
|
},
|
|
'/panel/api/xray/geodata/entries': (query) => {
|
|
const dataset = DATASETS[query.get('file') ?? ''];
|
|
const needle = (query.get('q') ?? '').trim().toLowerCase();
|
|
const matched = (dataset?.entries[query.get('code') ?? ''] ?? []).filter((entry) =>
|
|
entry.value.toLowerCase().includes(needle),
|
|
);
|
|
const offset = Number(query.get('offset') ?? 0);
|
|
const limit = Number(query.get('limit') ?? 100);
|
|
return { total: matched.length, items: matched.slice(offset, offset + limit) };
|
|
},
|
|
'/panel/api/xray/geodata/validate': (_query, form) =>
|
|
validate(parseTokens(form.get('tokens') ?? ''), form.get('kind') === 'ip'),
|
|
};
|
|
|
|
const withGeodata: Decorator = function GeodataBackend(Story) {
|
|
return (
|
|
<GeoApi routes={routes}>
|
|
<Story />
|
|
</GeoApi>
|
|
);
|
|
};
|
|
|
|
function ControlledTokenInput({ value = '', id = 'geo-rule', ...rest }: GeoTokenInputProps) {
|
|
const [current, setCurrent] = useState(value);
|
|
useEffect(() => setCurrent(value), [value]);
|
|
return (
|
|
<Space direction="vertical" size={4} style={{ width: 460 }}>
|
|
<label htmlFor={id}>{rest.kind === 'ip' ? 'Target IP' : 'Target domain'}</label>
|
|
<GeoTokenInput {...rest} id={id} value={current} onChange={setCurrent} />
|
|
</Space>
|
|
);
|
|
}
|
|
|
|
const meta = {
|
|
title: 'Geodata/GeoTokenInput',
|
|
component: GeoTokenInput,
|
|
tags: ['autodocs'],
|
|
parameters: {
|
|
layout: 'padded',
|
|
a11y: {
|
|
config: {
|
|
rules: [{ id: 'color-contrast', enabled: false }],
|
|
},
|
|
},
|
|
docs: {
|
|
description: {
|
|
component:
|
|
'Routing rule field for the xray rule editor: a comma separated list of domains/CIDRs and `geosite:` / `geoip:` tokens, with a database button in the addon that opens the geo category browser. Typed tokens are validated against the databases on disk after a short pause, and anything the running core would not resolve is called out under the field. The stories answer `/panel/api/xray/geodata/*` from an in-memory fixture, so validation and the browser both work without a panel backend.',
|
|
},
|
|
},
|
|
},
|
|
decorators: [withGeodata],
|
|
args: { kind: 'domain' },
|
|
argTypes: {
|
|
value: { description: 'Comma separated rule string held by the parent form.' },
|
|
onChange: { description: 'Called with the full rule string on every edit and on Apply from the browser.' },
|
|
onBlur: { description: 'Forwarded to the input; used by React Hook Form to mark the field touched.' },
|
|
kind: {
|
|
description: 'Which database the tokens are validated against: `domain` for geosite, `ip` for geoip.',
|
|
control: 'inline-radio',
|
|
options: ['domain', 'ip'],
|
|
},
|
|
placeholder: { description: 'Placeholder shown while the field is empty.' },
|
|
id: { description: 'Input id, linked to the label rendered by the surrounding form field.' },
|
|
},
|
|
render: (args) => <ControlledTokenInput {...args} />,
|
|
} satisfies Meta<typeof GeoTokenInput>;
|
|
|
|
export default meta;
|
|
|
|
type Story = StoryObj<typeof meta>;
|
|
|
|
export const Empty: Story = {
|
|
args: { kind: 'domain', value: '', placeholder: 'geosite:google, example.com' },
|
|
};
|
|
|
|
export const DomainTokens: Story = {
|
|
args: { kind: 'domain', value: 'geosite:google, google.com' },
|
|
};
|
|
|
|
export const IpTokens: Story = {
|
|
args: { kind: 'ip', value: 'geoip:private' },
|
|
};
|
|
|
|
export const UnknownCategory: Story = {
|
|
args: { kind: 'domain', value: 'geosite:blabla, geosite:google' },
|
|
play: async ({ canvasElement }) => {
|
|
const canvas = within(canvasElement);
|
|
await expect(await canvas.findByText(/geosite:blabla/, undefined, { timeout: 3000 })).toBeVisible();
|
|
},
|
|
};
|