Compare commits

...

15 Commits

Author SHA1 Message Date
semantic-release-bot d7879a8654 🔖 chore(release): v1.4.5 [skip ci]
## [1.4.5](https://github.com/perfect-panel/ppanel-web/compare/v1.4.4...v1.4.5) (2025-09-17)

### ♻ Code Refactoring

* Replace useQuery with Zustand store for subscription and node data management ([c6dd0b6](https://github.com/perfect-panel/ppanel-web/commit/c6dd0b6))
* Simplify TemplatePreview component structure by consolidating Sheet and Button elements ([1b715c5](https://github.com/perfect-panel/ppanel-web/commit/1b715c5))

### 🐛 Bug Fixes

*  Add showLineNumbers prop handling in MonacoEditor for improved placeholder positioning ([bd67ece](https://github.com/perfect-panel/ppanel-web/commit/bd67ece))
* Add fetchTags method to NodesPage and ensure tags are fetched alongside nodes ([a3c5e31](https://github.com/perfect-panel/ppanel-web/commit/a3c5e31))
* Add NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT to control tutorial visibility and update page query accordingly ([e94405d](https://github.com/perfect-panel/ppanel-web/commit/e94405d))
* Add subscribeSchema for subscription management with detailed proxy and user information ([49b3dcc](https://github.com/perfect-panel/ppanel-web/commit/49b3dcc))
* Enhance server ID display in ServerTrafficLogPage with badges and server ratio ([6dfac27](https://github.com/perfect-panel/ppanel-web/commit/6dfac27))
* Update platform handling in Content component to ensure available platforms are correctly filtered and displayed ([1dde708](https://github.com/perfect-panel/ppanel-web/commit/1dde708))
2025-09-17 10:13:51 +00:00
web 49b3dcc591 🐛 fix: Add subscribeSchema for subscription management with detailed proxy and user information 2025-09-17 03:10:44 -07:00
web e94405d1cd 🐛 fix: Add NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT to control tutorial visibility and update page query accordingly 2025-09-17 03:03:12 -07:00
web 1dde7088bc 🐛 fix: Update platform handling in Content component to ensure available platforms are correctly filtered and displayed 2025-09-17 02:55:33 -07:00
web bd67ece479 🐛 fix: Add showLineNumbers prop handling in MonacoEditor for improved placeholder positioning 2025-09-17 02:45:16 -07:00
web a3c5e31094 🐛 fix: Add fetchTags method to NodesPage and ensure tags are fetched alongside nodes 2025-09-17 02:35:53 -07:00
web 1b715c5f8b ♻️ refactor: Simplify TemplatePreview component structure by consolidating Sheet and Button elements 2025-09-17 02:29:29 -07:00
web 6dfac27bc3 🐛 fix: Enhance server ID display in ServerTrafficLogPage with badges and server ratio 2025-09-17 02:24:54 -07:00
web c6dd0b63f2 ♻️ refactor: Replace useQuery with Zustand store for subscription and node data management 2025-09-17 02:20:54 -07:00
semantic-release-bot bdd53b1551 🔖 chore(release): v1.4.4 [skip ci]
## [1.4.4](https://github.com/perfect-panel/ppanel-web/compare/v1.4.3...v1.4.4) (2025-09-16)

### 🐛 Bug Fixes

* Add minimum value constraint for count and user limit inputs in CouponForm ([6991b69](https://github.com/perfect-panel/ppanel-web/commit/6991b69))
* Add protocol-related constants, default configurations, field definitions, and validation modes ([d685407](https://github.com/perfect-panel/ppanel-web/commit/d685407))
* Added the enabled field in the protocol configuration, updated the related type definition and default configuration ([2b0cf9a](https://github.com/perfect-panel/ppanel-web/commit/2b0cf9a))
* Filter available protocols to exclude disabled ones in NodeForm ([982d288](https://github.com/perfect-panel/ppanel-web/commit/982d288))
* Refactor key generation logic and update dependencies for ML-KEM-768 integration ([b8f630f](https://github.com/perfect-panel/ppanel-web/commit/b8f630f))
2025-09-16 17:42:46 +00:00
web 982d2882e9 🐛 fix: Filter available protocols to exclude disabled ones in NodeForm 2025-09-16 10:30:49 -07:00
web 2b0cf9a46d 🐛 fix: Added the enabled field in the protocol configuration, updated the related type definition and default configuration 2025-09-16 10:17:39 -07:00
web d6854076fe 🐛 fix: Add protocol-related constants, default configurations, field definitions, and validation modes 2025-09-16 04:50:05 -07:00
web 6991b69d40 🐛 fix: Add minimum value constraint for count and user limit inputs in CouponForm 2025-09-16 04:33:42 -07:00
web b8f630f8ab 🐛 fix: Refactor key generation logic and update dependencies for ML-KEM-768 integration 2025-09-16 04:32:16 -07:00
50 changed files with 1564 additions and 1058 deletions
+41 -6
View File
@@ -1,16 +1,51 @@
<a name="readme-top"></a>
# Changelog
## [1.4.3](https://github.com/perfect-panel/ppanel-web/compare/v1.4.2...v1.4.3) (2025-09-16)
## [1.4.5](https://github.com/perfect-panel/ppanel-web/compare/v1.4.4...v1.4.5) (2025-09-17)
### ♻ Code Refactoring
* Replace useQuery with Zustand store for subscription and node data management ([c6dd0b6](https://github.com/perfect-panel/ppanel-web/commit/c6dd0b6))
* Simplify TemplatePreview component structure by consolidating Sheet and Button elements ([1b715c5](https://github.com/perfect-panel/ppanel-web/commit/1b715c5))
### 🐛 Bug Fixes
* Add success toast message for sorting in nodes and servers pages ([2d5175d](https://github.com/perfect-panel/ppanel-web/commit/2d5175d))
* Implement encryption and obfuscation features in protocol configuration ([54de16b](https://github.com/perfect-panel/ppanel-web/commit/54de16b))
* Refactor toB64 function to toB64Url for URL-safe base64 encoding in VlessX25519Pair generation ([8700cf6](https://github.com/perfect-panel/ppanel-web/commit/8700cf6))
* Simplify initialValues assignment and update node submission logic in NodesPage ([05d6c89](https://github.com/perfect-panel/ppanel-web/commit/05d6c89))
* Update bun.lockb to reflect dependency changes ([ebcebd7](https://github.com/perfect-panel/ppanel-web/commit/ebcebd7))
* Add showLineNumbers prop handling in MonacoEditor for improved placeholder positioning ([bd67ece](https://github.com/perfect-panel/ppanel-web/commit/bd67ece))
* Add fetchTags method to NodesPage and ensure tags are fetched alongside nodes ([a3c5e31](https://github.com/perfect-panel/ppanel-web/commit/a3c5e31))
* Add NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT to control tutorial visibility and update page query accordingly ([e94405d](https://github.com/perfect-panel/ppanel-web/commit/e94405d))
* Add subscribeSchema for subscription management with detailed proxy and user information ([49b3dcc](https://github.com/perfect-panel/ppanel-web/commit/49b3dcc))
* Enhance server ID display in ServerTrafficLogPage with badges and server ratio ([6dfac27](https://github.com/perfect-panel/ppanel-web/commit/6dfac27))
* Update platform handling in Content component to ensure available platforms are correctly filtered and displayed ([1dde708](https://github.com/perfect-panel/ppanel-web/commit/1dde708))
<a name="readme-top"></a>
# Changelog
## [1.4.4](https://github.com/perfect-panel/ppanel-web/compare/v1.4.3...v1.4.4) (2025-09-16)
### 🐛 Bug Fixes
- Add minimum value constraint for count and user limit inputs in CouponForm ([6991b69](https://github.com/perfect-panel/ppanel-web/commit/6991b69))
- Add protocol-related constants, default configurations, field definitions, and validation modes ([d685407](https://github.com/perfect-panel/ppanel-web/commit/d685407))
- Added the enabled field in the protocol configuration, updated the related type definition and default configuration ([2b0cf9a](https://github.com/perfect-panel/ppanel-web/commit/2b0cf9a))
- Filter available protocols to exclude disabled ones in NodeForm ([982d288](https://github.com/perfect-panel/ppanel-web/commit/982d288))
- Refactor key generation logic and update dependencies for ML-KEM-768 integration ([b8f630f](https://github.com/perfect-panel/ppanel-web/commit/b8f630f))
<a name="readme-top"></a>
# Changelog
## [1.4.3](https://github.com/perfect-panel/ppanel-web/compare/v1.4.2...v1.4.3) (2025-09-16)
### 🐛 Bug Fixes
- Add success toast message for sorting in nodes and servers pages ([2d5175d](https://github.com/perfect-panel/ppanel-web/commit/2d5175d))
- Implement encryption and obfuscation features in protocol configuration ([54de16b](https://github.com/perfect-panel/ppanel-web/commit/54de16b))
- Refactor toB64 function to toB64Url for URL-safe base64 encoding in VlessX25519Pair generation ([8700cf6](https://github.com/perfect-panel/ppanel-web/commit/8700cf6))
- Simplify initialValues assignment and update node submission logic in NodesPage ([05d6c89](https://github.com/perfect-panel/ppanel-web/commit/05d6c89))
- Update bun.lockb to reflect dependency changes ([ebcebd7](https://github.com/perfect-panel/ppanel-web/commit/ebcebd7))
<a name="readme-top"></a>
@@ -1,8 +1,7 @@
'use client';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
@@ -81,16 +80,7 @@ export default function CouponForm<T extends Record<string, any>>({
const type = form.watch('type');
const { data: subscribe } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.Subscribe[];
},
});
const { subscribes } = useSubscribe();
return (
<Sheet open={open} onOpenChange={setOpen}>
@@ -247,9 +237,9 @@ export default function CouponForm<T extends Record<string, any>>({
onChange={(value) => {
form.setValue(field.name, value);
}}
options={subscribe?.map((item: API.Subscribe) => ({
value: item.id,
label: item.name,
options={subscribes?.map((item) => ({
value: item.id!,
label: item.name!,
}))}
/>
</FormControl>
@@ -307,6 +297,7 @@ export default function CouponForm<T extends Record<string, any>>({
<EnhancedInput
placeholder={t('form.countPlaceholder')}
type='number'
min={0}
step={1}
{...field}
onValueChange={(value) => {
@@ -328,6 +319,7 @@ export default function CouponForm<T extends Record<string, any>>({
<EnhancedInput
placeholder={t('form.userLimitPlaceholder')}
type='number'
min={0}
step={1}
{...field}
onValueChange={(value) => {
+4 -14
View File
@@ -9,9 +9,8 @@ import {
getCouponList,
updateCoupon,
} from '@/services/admin/coupon';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
@@ -24,16 +23,7 @@ import CouponForm from './coupon-form';
export default function Page() {
const t = useTranslations('coupon');
const [loading, setLoading] = useState(false);
const { data } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.SubscribeGroup[];
},
});
const { subscribes } = useSubscribe();
const ref = useRef<ProTableActions>(null);
return (
<ProTable<API.Coupon, { group_id: number; query: string }>
@@ -67,8 +57,8 @@ export default function Page() {
{
key: 'subscribe',
placeholder: t('subscribe'),
options: data?.map((item) => ({
label: item.name,
options: subscribes?.map((item) => ({
label: item.name!,
value: String(item.id),
})),
},
@@ -2,8 +2,8 @@
import { ProTable } from '@/components/pro-table';
import { filterServerTrafficLog } from '@/services/admin/log';
import { filterServerList } from '@/services/admin/server';
import { useQuery } from '@tanstack/react-query';
import { useServer } from '@/store/server';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { formatBytes } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
@@ -13,20 +13,10 @@ import { useSearchParams } from 'next/navigation';
export default function ServerTrafficLogPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const { getServerName, getServerById } = useServer();
const today = new Date().toISOString().split('T')[0];
const { data: servers = [] } = useQuery({
queryKey: ['filterServerListAll'],
queryFn: async () => {
const { data } = await filterServerList({ page: 1, size: 999999999 });
return data?.data?.list || [];
},
});
const getServerName = (id?: number) =>
id ? (servers.find((s) => s.id === id)?.name ?? `Server ${id}`) : 'Unknown';
const initialFilters = {
date: sp.get('date') || today,
server_id: sp.get('server_id') ? Number(sp.get('server_id')) : undefined,
@@ -50,11 +40,17 @@ export default function ServerTrafficLogPage() {
{
accessorKey: 'server_id',
header: t('column.server'),
cell: ({ row }) => (
<span>
{getServerName(row.original.server_id)} ({row.original.server_id})
</span>
),
cell: ({ row }) => {
const server = getServerById(row.original.server_id);
const ratio = server?.ratio || 1;
return (
<div className='flex items-center gap-2'>
<Badge>{row.original.server_id}</Badge>
<span>{getServerName(row.original.server_id)}</span>
<Badge variant='outline'>{ratio}X</Badge>
</div>
);
},
},
{
accessorKey: 'upload',
@@ -3,9 +3,8 @@
import { UserDetail, UserSubscribeDetail } from '@/app/dashboard/user/user-detail';
import { ProTable } from '@/components/pro-table';
import { filterTrafficLogDetails } from '@/services/admin/log';
import { filterServerList } from '@/services/admin/server';
import { useServer } from '@/store/server';
import { formatDate } from '@/utils/common';
import { useQuery } from '@tanstack/react-query';
import { formatBytes } from '@workspace/ui/utils';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
@@ -13,20 +12,10 @@ import { useSearchParams } from 'next/navigation';
export default function TrafficDetailsPage() {
const t = useTranslations('log');
const sp = useSearchParams();
const { getServerName } = useServer();
const today = new Date().toISOString().split('T')[0];
const { data: servers = [] } = useQuery({
queryKey: ['filterServerListAll'],
queryFn: async () => {
const { data } = await filterServerList({ page: 1, size: 999999999 });
return data?.data?.list || [];
},
});
const getServerName = (id?: number) =>
id ? (servers.find((s) => s.id === id)?.name ?? `Server ${id}`) : 'Unknown';
const initialFilters = {
date: sp.get('date') || today,
server_id: sp.get('server_id') ? Number(sp.get('server_id')) : undefined,
@@ -2,9 +2,8 @@
import { Display } from '@/components/display';
import { createQuotaTask, queryQuotaTaskPreCount } from '@/services/admin/marketing';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
@@ -73,17 +72,7 @@ export default function QuotaBroadcastForm() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [open, setOpen] = useState(false);
// Get subscribe list
const { data: subscribeList } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 999999999,
});
return data.data?.list as API.SubscribeItem[];
},
});
const { subscribes } = useSubscribe();
// Calculate recipient count
const calculateRecipients = async () => {
@@ -217,21 +206,19 @@ export default function QuotaBroadcastForm() {
value={field.value || []}
onChange={field.onChange}
placeholder={t('pleaseSelectSubscribers')}
options={
subscribeList?.map((subscribe) => ({
value: subscribe.id!,
label: subscribe.name!,
children: (
<div>
<div>{subscribe.name}</div>
<div className='text-muted-foreground text-xs'>
<Display type='traffic' value={subscribe.traffic || 0} /> /{' '}
<Display type='currency' value={subscribe.unit_price || 0} />
</div>
options={subscribes?.map((subscribe) => ({
value: subscribe.id!,
label: subscribe.name!,
children: (
<div>
<div>{subscribe.name}</div>
<div className='text-muted-foreground text-xs'>
<Display type='traffic' value={subscribe.traffic || 0} /> /{' '}
<Display type='currency' value={subscribe.unit_price || 0} />
</div>
),
})) || []
}
</div>
),
}))}
/>
</FormControl>
<FormMessage />
@@ -3,9 +3,8 @@
import { Display } from '@/components/display';
import { ProTable } from '@/components/pro-table';
import { queryQuotaTaskList } from '@/services/admin/marketing';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import { ScrollArea } from '@workspace/ui/components/scroll-area';
import {
@@ -23,21 +22,9 @@ export default function QuotaTaskManager() {
const t = useTranslations('marketing');
const [open, setOpen] = useState(false);
// Get subscribe list to show subscription names
const { data: subscribeList } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 999999999,
});
return data.data?.list as API.SubscribeItem[];
},
});
// Create a map for quick lookup of subscription names
const { subscribes } = useSubscribe();
const subscribeMap =
subscribeList?.reduce(
subscribes?.reduce(
(acc, subscribe) => {
acc[subscribe.id!] = subscribe.name!;
return acc;
+10 -41
View File
@@ -1,8 +1,8 @@
'use client';
import { filterServerList, queryNodeTag } from '@/services/admin/server';
import { useNode } from '@/store/node';
import { useServer } from '@/store/server';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
@@ -40,8 +40,6 @@ export type ProtocolName =
| 'tuic'
| 'anytls';
type ServerRow = API.Server;
const buildSchema = (t: ReturnType<typeof useTranslations>) =>
z.object({
name: z.string().trim().min(1, t('errors.nameRequired')),
@@ -103,38 +101,12 @@ export default function NodeForm(props: {
const serverId = form.watch('server_id');
const { data } = useQuery({
enabled: open,
queryKey: ['filterServerListAll'],
queryFn: async () => {
const { data } = await filterServerList({ page: 1, size: 999999999 });
return data?.data?.list || [];
},
});
const servers: ServerRow[] = data as ServerRow[];
const { servers, getAvailableProtocols } = useServer();
const { tags } = useNode();
const { data: tagsData } = useQuery({
enabled: open,
queryKey: ['queryNodeTag'],
queryFn: async () => {
const { data } = await queryNodeTag();
return data?.data?.tags || [];
},
});
const existingTags: string[] = tagsData as string[];
const existingTags: string[] = tags || [];
const currentServer = useMemo(() => servers?.find((s) => s.id === serverId), [servers, serverId]);
const availableProtocols = useMemo(() => {
if (!currentServer?.protocols) return [];
return (currentServer.protocols as Array<{ type: ProtocolName; port?: number }>)
.filter((p) => p.type)
.map((p) => ({
protocol: p.type,
port: p.port,
}));
}, [currentServer]);
const availableProtocols = getAvailableProtocols(serverId);
useEffect(() => {
if (initialValues) {
@@ -176,12 +148,11 @@ export default function NodeForm(props: {
fieldsToFill.push('address');
}
const protocols =
(selectedServer.protocols as Array<{ type: ProtocolName; port?: number }>) || [];
const protocols = getAvailableProtocols(id);
const firstProtocol = protocols[0];
if (firstProtocol && (!currentValues.protocol || autoFilledFields.has('protocol'))) {
form.setValue('protocol', firstProtocol.type, { shouldDirty: false });
form.setValue('protocol', firstProtocol.protocol, { shouldDirty: false });
fieldsToFill.push('protocol');
if (!currentValues.port || currentValues.port === 0 || autoFilledFields.has('port')) {
@@ -203,7 +174,7 @@ export default function NodeForm(props: {
const protocol = (nextProto || '') as ProtocolName | '';
form.setValue('protocol', protocol);
if (!protocol || !currentServer) {
if (!protocol || !serverId) {
removeAutoFilledField('protocol');
return;
}
@@ -214,9 +185,7 @@ export default function NodeForm(props: {
removeAutoFilledField('protocol');
if (!currentValues.port || currentValues.port === 0 || isPortAutoFilled) {
const protocolData = (
currentServer.protocols as Array<{ type: ProtocolName; port?: number }>
)?.find((p) => p.type === protocol);
const protocolData = availableProtocols.find((p) => p.protocol === protocol);
if (protocolData) {
const port = protocolData.port || 0;
+22 -25
View File
@@ -5,12 +5,12 @@ import {
createNode,
deleteNode,
filterNodeList,
filterServerList,
resetSortWithNode,
toggleNodeStatus,
updateNode,
} from '@/services/admin/server';
import { useQuery } from '@tanstack/react-query';
import { useNode } from '@/store/node';
import { useServer } from '@/store/server';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
@@ -25,24 +25,9 @@ export default function NodesPage() {
const ref = useRef<ProTableActions>(null);
const [loading, setLoading] = useState(false);
const { data: servers = [] } = useQuery({
queryKey: ['filterServerListAll'],
queryFn: async () => {
const { data } = await filterServerList({ page: 1, size: 999999999 });
return data?.data?.list || [];
},
});
const getServerName = (id?: number) =>
id ? (servers.find((s) => s.id === id)?.name ?? `#${id}`) : '—';
const getServerOriginAddr = (id?: number) =>
id ? (servers.find((s) => s.id === id)?.address ?? '—') : '—';
const getProtocolOriginPort = (id?: number, proto?: string) => {
if (!id || !proto) return '—';
const hit = servers.find((s) => s.id === id)?.protocols?.find((p) => (p as any).type === proto);
const p = (hit as any)?.port as number | undefined;
return typeof p === 'number' ? String(p) : '—';
};
// Use our zustand store for server data
const { getServerName, getServerAddress, getProtocolPort } = useServer();
const { fetchNodes, fetchTags } = useNode();
return (
<ProTable<API.Node, { search: string }>
@@ -69,6 +54,8 @@ export default function NodesPage() {
await createNode(body);
toast.success(t('created'));
ref.current?.refresh();
fetchNodes();
fetchTags();
setLoading(false);
return true;
} catch (e) {
@@ -90,6 +77,8 @@ export default function NodesPage() {
await toggleNodeStatus({ id: row.original.id, enable: v });
toast.success(v ? t('enabled_on') : t('enabled_off'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
/>
),
@@ -106,14 +95,14 @@ export default function NodesPage() {
id: 'server_id',
header: t('server'),
cell: ({ row }) => (
<div className='flex flex-wrap gap-2'>
<div className='space-y-1'>
<Badge variant='outline'>
{getServerName(row.original.server_id)} ·{' '}
{getServerOriginAddr(row.original.server_id)}
{getServerName(row.original.server_id)} : {getServerAddress(row.original.server_id)}
</Badge>
<br />
<Badge variant='outline'>
{row.original.protocol || '—'} ·{' '}
{getProtocolOriginPort(row.original.server_id, row.original.protocol)}
{row.original.protocol || '—'} :{' '}
{getProtocolPort(row.original.server_id, row.original.protocol)}
</Badge>
</div>
),
@@ -163,6 +152,8 @@ export default function NodesPage() {
await updateNode(body);
toast.success(t('updated'));
ref.current?.refresh();
fetchNodes();
fetchTags();
setLoading(false);
return true;
} catch (e) {
@@ -180,6 +171,8 @@ export default function NodesPage() {
await deleteNode({ id: row.id } as any);
toast.success(t('deleted'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
@@ -195,6 +188,8 @@ export default function NodesPage() {
});
toast.success(t('copied'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
>
{t('copy')}
@@ -211,6 +206,8 @@ export default function NodesPage() {
await Promise.all(rows.map((r) => deleteNode({ id: r.id } as any)));
toast.success(t('deleted'));
ref.current?.refresh();
fetchNodes();
fetchTags();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
+5 -17
View File
@@ -1,6 +1,5 @@
'use client';
import { useQuery } from '@tanstack/react-query';
import { useTranslations } from 'next-intl';
import { useSearchParams } from 'next/navigation';
import { useRef } from 'react';
@@ -8,7 +7,7 @@ import { useRef } from 'react';
import { Display } from '@/components/display';
import { ProTable, ProTableActions } from '@/components/pro-table';
import { getOrderList, updateOrderStatus } from '@/services/admin/order';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
@@ -32,16 +31,7 @@ export default function Page() {
const ref = useRef<ProTableActions>(null);
const { data: subscribeList } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 999999999,
});
return data.data?.list as API.SubscribeGroup[];
},
});
const { subscribes, getSubscribeName } = useSubscribe();
const initialFilters = {
search: sp.get('search') || undefined,
@@ -68,9 +58,7 @@ export default function Page() {
accessorKey: 'subscribe_id',
header: t('subscribe'),
cell: ({ row }) => {
const name = subscribeList?.find(
(item) => item.id === row.getValue('subscribe_id'),
)?.name;
const name = getSubscribeName(row.getValue('subscribe_id'));
const quantity = row.original.quantity;
return name ? `${name} × ${quantity}` : '';
},
@@ -186,8 +174,8 @@ export default function Page() {
{
key: 'subscribe_id',
placeholder: `${t('subscribe')}`,
options: subscribeList?.map((item) => ({
label: item.name,
options: subscribes?.map((item) => ({
label: item.name!,
value: String(item.id),
})),
},
@@ -1,9 +1,5 @@
import { getTranslations } from 'next-intl/server';
import SubscribeTable from './subscribe-table';
export default async function Page() {
const t = await getTranslations('product');
return <SubscribeTable />;
}
@@ -1,8 +1,7 @@
'use client';
import { filterNodeList, queryNodeTag } from '@/services/admin/server';
import { useNode } from '@/store/node';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import {
Accordion,
AccordionContent,
@@ -229,35 +228,9 @@ export default function SubscribeForm<T extends Record<string, any>>({
if (bool) setOpen(false);
}
const { data: nodes } = useQuery({
queryKey: ['filterNodeListAll'],
queryFn: async () => {
const { data } = await filterNodeList({ page: 1, size: 999999999 });
return (data.data?.list || []) as API.Node[];
},
});
const { nodes, getAllAvailableTags, getNodesByTag, getNodesWithoutTags } = useNode();
const { data: allTagsData } = useQuery({
queryKey: ['queryNodeTag'],
queryFn: async () => {
const { data } = await queryNodeTag();
return data?.data?.tags || [];
},
});
const nodeExtractedTags = Array.from(
new Set(
((nodes as API.Node[]) || [])
.flatMap((n) => (Array.isArray(n.tags) ? n.tags : []))
.filter(Boolean),
),
) as string[];
const allAvailableTags = (allTagsData as string[]) || [];
const tagGroups = Array.from(new Set([...allAvailableTags, ...nodeExtractedTags])).filter(
Boolean,
);
const tagGroups = getAllAvailableTags();
const unit_time = form.watch('unit_time');
@@ -806,10 +779,7 @@ export default function SubscribeForm<T extends Record<string, any>>({
{tagGroups.map((tag) => {
const value = field.value || [];
const tagId = tag;
const nodesWithTag =
(nodes as API.Node[])?.filter((n) =>
(n.tags || []).includes(tag),
) || [];
const nodesWithTag = getNodesByTag(tag);
return (
<AccordionItem key={tag} value={String(tag)}>
@@ -836,22 +806,20 @@ export default function SubscribeForm<T extends Record<string, any>>({
</AccordionTrigger>
<AccordionContent>
<ul className='space-y-1'>
{(nodes as API.Node[])
?.filter((n) => (n.tags || []).includes(tag))
?.map((node) => (
<li
key={node.id}
className='flex items-center justify-between gap-3'
>
<span className='flex-1'>{node.name}</span>
<span className='flex-1'>
{node.address}:{node.port}
</span>
<span className='flex-1 text-right'>
{node.protocol}
</span>
</li>
))}
{getNodesByTag(tag).map((node) => (
<li
key={node.id}
className='flex items-center justify-between gap-3'
>
<span className='flex-1'>{node.name}</span>
<span className='flex-1'>
{node.address}:{node.port}
</span>
<span className='flex-1 text-right'>
{node.protocol}
</span>
</li>
))}
</ul>
</AccordionContent>
</AccordionItem>
@@ -872,34 +840,32 @@ export default function SubscribeForm<T extends Record<string, any>>({
<FormLabel>{t('form.node')}</FormLabel>
<FormControl>
<div className='flex flex-col gap-2'>
{(nodes as API.Node[])
?.filter((item) => (item.tags || []).length === 0)
?.map((item) => {
const value = field.value || [];
{getNodesWithoutTags().map((item) => {
const value = field.value || [];
return (
<div className='flex items-center gap-2' key={item.id}>
<Checkbox
checked={value.includes(item.id!)}
onCheckedChange={(checked) => {
return checked
? form.setValue(field.name, [...value, item.id])
: form.setValue(
field.name,
value.filter((value: number) => value !== item.id),
);
}}
/>
<Label className='flex w-full items-center justify-between gap-3'>
<span className='flex-1'>{item.name}</span>
<span className='flex-1'>
{item.address}:{item.port}
</span>
<span className='flex-1 text-right'>{item.protocol}</span>
</Label>
</div>
);
})}
return (
<div className='flex items-center gap-2' key={item.id}>
<Checkbox
checked={value.includes(item.id!)}
onCheckedChange={(checked) => {
return checked
? form.setValue(field.name, [...value, item.id])
: form.setValue(
field.name,
value.filter((value: number) => value !== item.id),
);
}}
/>
<Label className='flex w-full items-center justify-between gap-3'>
<span className='flex-1'>{item.name}</span>
<span className='flex-1'>
{item.address}:{item.port}
</span>
<span className='flex-1 text-right'>{item.protocol}</span>
</Label>
</div>
);
})}
</div>
</FormControl>
<FormMessage />
@@ -10,6 +10,7 @@ import {
subscribeSort,
updateSubscribe,
} from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
import { Switch } from '@workspace/ui/components/switch';
@@ -23,6 +24,7 @@ export default function SubscribeTable() {
const t = useTranslations('product');
const [loading, setLoading] = useState(false);
const ref = useRef<ProTableActions>(null);
const { fetchSubscribes } = useSubscribe();
return (
<ProTable<API.SubscribeItem, { group_id: number; query: string }>
action={ref}
@@ -42,6 +44,7 @@ export default function SubscribeTable() {
});
toast.success(t('createSuccess'));
ref.current?.refresh();
fetchSubscribes();
setLoading(false);
return true;
@@ -83,6 +86,7 @@ export default function SubscribeTable() {
show: checked,
} as API.UpdateSubscribeRequest);
ref.current?.refresh();
fetchSubscribes();
}}
/>
);
@@ -101,6 +105,7 @@ export default function SubscribeTable() {
sell: checked,
} as API.UpdateSubscribeRequest);
ref.current?.refresh();
fetchSubscribes();
}}
/>
);
@@ -186,6 +191,7 @@ export default function SubscribeTable() {
} as API.UpdateSubscribeRequest);
toast.success(t('updateSuccess'));
ref.current?.refresh();
fetchSubscribes();
setLoading(false);
return true;
} catch (error) {
@@ -206,6 +212,7 @@ export default function SubscribeTable() {
});
toast.success(t('deleteSuccess'));
ref.current?.refresh();
fetchSubscribes();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
@@ -224,6 +231,7 @@ export default function SubscribeTable() {
} as API.CreateSubscribeRequest);
toast.success(t('copySuccess'));
ref.current?.refresh();
fetchSubscribes();
setLoading(false);
return true;
} catch (error) {
@@ -248,6 +256,7 @@ export default function SubscribeTable() {
toast.success(t('deleteSuccess'));
ref.current?.reset();
fetchSubscribes();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
@@ -0,0 +1,99 @@
export const protocols = [
'shadowsocks',
'vmess',
'vless',
'trojan',
'hysteria2',
'tuic',
'anytls',
'socks',
'naive',
'http',
'mieru',
] as const;
// Global label map for display; fallback to raw value if missing
export const LABELS = {
// transport
'tcp': 'TCP',
'udp': 'UDP',
'websocket': 'WebSocket',
'grpc': 'gRPC',
'mkcp': 'mKCP',
'httpupgrade': 'HTTP Upgrade',
'xhttp': 'XHTTP',
// security
'none': 'NONE',
'tls': 'TLS',
'reality': 'Reality',
// fingerprint
'chrome': 'Chrome',
'firefox': 'Firefox',
'safari': 'Safari',
'ios': 'IOS',
'android': 'Android',
'edge': 'edge',
'360': '360',
'qq': 'QQ',
// multiplex
'low': 'Low',
'middle': 'Middle',
'high': 'High',
} as const;
// Flat arrays for enum-like sets
export const SS_CIPHERS = [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305',
'2022-blake3-aes-128-gcm',
'2022-blake3-aes-256-gcm',
'2022-blake3-chacha20-poly1305',
] as const;
export const TRANSPORTS = {
vmess: ['tcp', 'websocket', 'grpc'] as const,
vless: ['tcp', 'websocket', 'grpc', 'mkcp', 'httpupgrade', 'xhttp'] as const,
trojan: ['tcp', 'websocket', 'grpc'] as const,
mieru: ['tcp', 'udp'] as const,
} as const;
export const SECURITY = {
vmess: ['none', 'tls'] as const,
vless: ['none', 'tls', 'reality'] as const,
trojan: ['tls'] as const,
hysteria2: ['tls'] as const,
tuic: ['tls'] as const,
anytls: ['tls'] as const,
naive: ['none', 'tls'] as const,
http: ['none', 'tls'] as const,
} as const;
export const FLOWS = {
vless: ['none', 'xtls-rprx-direct', 'xtls-rprx-splice', 'xtls-rprx-vision'] as const,
} as const;
export const TUIC_UDP_RELAY_MODES = ['native', 'quic'] as const;
export const TUIC_CONGESTION = ['bbr', 'cubic', 'new_reno'] as const;
export const XHTTP_MODES = ['auto', 'packet-up', 'stream-up', 'stream-one'] as const;
export const ENCRYPTION_TYPES = ['none', 'mlkem768x25519plus'] as const;
export const ENCRYPTION_MODES = ['native', 'xorpub', 'random'] as const;
export const ENCRYPTION_RTT = ['0rtt', '1rtt'] as const;
export const FINGERPRINTS = [
'chrome',
'firefox',
'safari',
'ios',
'android',
'edge',
'360',
'qq',
] as const;
export const multiplexLevels = ['none', 'low', 'middle', 'high'] as const;
export function getLabel(value: string): string {
const label = (LABELS as Record<string, string>)[value];
return label ?? value.toUpperCase();
}
@@ -0,0 +1,113 @@
import { XHTTP_MODES } from './constants';
import type { ProtocolType } from './types';
export function getProtocolDefaultConfig(proto: ProtocolType) {
switch (proto) {
case 'shadowsocks':
return {
type: 'shadowsocks',
enable: false,
port: null,
cipher: 'chacha20-ietf-poly1305',
server_key: null,
obfs: 'none',
obfs_host: null,
obfs_path: null,
} as any;
case 'vmess':
return {
type: 'vmess',
enable: false,
port: null,
transport: 'tcp',
security: 'none',
} as any;
case 'vless':
return {
type: 'vless',
enable: false,
port: null,
transport: 'tcp',
security: 'none',
flow: 'none',
xhttp_mode: XHTTP_MODES[0], // 'auto'
xhttp_extra: null,
} as any;
case 'trojan':
return {
type: 'trojan',
enable: false,
port: null,
transport: 'tcp',
security: 'tls',
} as any;
case 'hysteria2':
return {
type: 'hysteria2',
enable: false,
port: null,
hop_ports: null,
hop_interval: null,
obfs: 'none',
obfs_password: null,
security: 'tls',
up_mbps: null,
down_mbps: null,
} as any;
case 'tuic':
return {
type: 'tuic',
enable: false,
port: null,
disable_sni: false,
reduce_rtt: false,
udp_relay_mode: 'native',
congestion_controller: 'bbr',
security: 'tls',
sni: null,
allow_insecure: false,
fingerprint: 'chrome',
} as any;
case 'socks':
return {
type: 'socks',
enable: false,
port: null,
} as any;
case 'naive':
return {
type: 'naive',
enable: false,
port: null,
security: 'none',
} as any;
case 'http':
return {
type: 'http',
enable: false,
port: null,
security: 'none',
} as any;
case 'mieru':
return {
type: 'mieru',
enable: false,
port: null,
multiplex: 'none',
transport: 'tcp',
} as any;
case 'anytls':
return {
type: 'anytls',
enable: false,
port: null,
security: 'tls',
padding_scheme: null,
sni: null,
allow_insecure: false,
fingerprint: 'chrome',
} as any;
default:
return {} as any;
}
}
@@ -1,374 +1,24 @@
import { z } from 'zod';
import { generatePassword, generateRealityKeyPair, generateRealityShortId } from './generate';
import { generateVlessX25519Pair } from './generate/mlkem768x25519plus';
export const protocols = [
'shadowsocks',
'vmess',
'vless',
'trojan',
'hysteria2',
'tuic',
'anytls',
'socks',
'naive',
'http',
'meru',
] as const;
export type FieldConfig = {
name: string;
type: 'input' | 'select' | 'switch' | 'number' | 'textarea';
label: string;
placeholder?: string | ((t: (key: string) => string, protocol: any) => string);
options?: readonly string[];
defaultValue?: any;
min?: number;
max?: number;
step?: number;
suffix?: string;
generate?: {
function: () => any;
updateFields?: Record<string, string>;
};
condition?: (protocol: any, values: any) => boolean;
group?: 'basic' | 'transport' | 'security' | 'reality' | 'obfs' | 'encryption';
gridSpan?: 1 | 2;
};
// Global label map for display; fallback to raw value if missing
export const LABELS = {
// transport
'tcp': 'TCP',
'udp': 'UDP',
'websocket': 'WebSocket',
'grpc': 'gRPC',
'mkcp': 'mKCP',
'httpupgrade': 'HTTP Upgrade',
'xhttp': 'XHTTP',
// security
'none': 'NONE',
'tls': 'TLS',
'reality': 'Reality',
// fingerprint
'chrome': 'Chrome',
'firefox': 'Firefox',
'safari': 'Safari',
'ios': 'IOS',
'android': 'Android',
'edge': 'edge',
'360': '360',
'qq': 'QQ',
// multiplex
'low': 'Low',
'middle': 'Middle',
'high': 'High',
} as const;
// Flat arrays for enum-like sets
export const SS_CIPHERS = [
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'chacha20-ietf-poly1305',
'2022-blake3-aes-128-gcm',
'2022-blake3-aes-256-gcm',
'2022-blake3-chacha20-poly1305',
] as const;
export const TRANSPORTS = {
vmess: ['tcp', 'websocket', 'grpc'] as const,
vless: ['tcp', 'websocket', 'grpc', 'mkcp', 'httpupgrade', 'xhttp'] as const,
trojan: ['tcp', 'websocket', 'grpc'] as const,
meru: ['tcp', 'udp'] as const,
} as const;
export const SECURITY = {
vmess: ['none', 'tls'] as const,
vless: ['none', 'tls', 'reality'] as const,
trojan: ['tls'] as const,
hysteria2: ['tls'] as const,
tuic: ['tls'] as const,
anytls: ['tls'] as const,
naive: ['none', 'tls'] as const,
http: ['none', 'tls'] as const,
} as const;
export const FLOWS = {
vless: ['none', 'xtls-rprx-direct', 'xtls-rprx-splice', 'xtls-rprx-vision'] as const,
} as const;
export const TUIC_UDP_RELAY_MODES = ['native', 'quic'] as const;
export const TUIC_CONGESTION = ['bbr', 'cubic', 'new_reno'] as const;
export const XHTTP_MODES = ['auto', 'packet-up', 'stream-up', 'stream-one'] as const;
export const ENCRYPTION_TYPES = ['none', 'mlkem768x25519plus'] as const;
export const ENCRYPTION_MODES = ['native', 'xorpub', 'random'] as const;
export const ENCRYPTION_RTT = ['0rtt', '1rtt'] as const;
export const FINGERPRINTS = [
'chrome',
'firefox',
'safari',
'ios',
'android',
'edge',
'360',
'qq',
] as const;
export const multiplexLevels = ['none', 'low', 'middle', 'high'] as const;
export function getLabel(value: string): string {
const label = (LABELS as Record<string, string>)[value];
return label ?? value.toUpperCase();
}
const nullableString = z.string().nullish();
const nullableBool = z.boolean().nullish();
const nullablePort = z.number().int().min(0).max(65535).nullish();
const ss = z.object({
type: z.literal('shadowsocks'),
host: nullableString,
port: nullablePort,
cipher: z.enum(SS_CIPHERS as any).nullish(),
server_key: nullableString,
obfs: z.enum(['none', 'http', 'tls'] as const).nullish(),
obfs_host: nullableString,
obfs_path: nullableString,
});
const vmess = z.object({
type: z.literal('vmess'),
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.vmess as any).nullish(),
security: z.enum(SECURITY.vmess as any).nullish(),
path: nullableString,
service_name: nullableString,
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const vless = z.object({
type: z.literal('vless'),
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.vless as any).nullish(),
security: z.enum(SECURITY.vless as any).nullish(),
path: nullableString,
service_name: nullableString,
flow: z.enum(FLOWS.vless as any).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
reality_server_addr: nullableString,
reality_server_port: nullablePort,
reality_private_key: nullableString,
reality_public_key: nullableString,
reality_short_id: nullableString,
mode: nullableString,
extra: nullableString,
encryption: z.enum(ENCRYPTION_TYPES as any).nullish(),
encryption_mode: z.enum(ENCRYPTION_MODES as any).nullish(),
encryption_rtt: z.enum(ENCRYPTION_RTT as any).nullish(),
encryption_ticket: nullableString,
encryption_server_padding: nullableString,
encryption_private_key: nullableString,
encryption_client_padding: nullableString,
encryption_password: nullableString,
});
const trojan = z.object({
type: z.literal('trojan'),
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.trojan as any).nullish(),
security: z.enum(SECURITY.trojan as any).nullish(),
path: nullableString,
service_name: nullableString,
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const hysteria2 = z.object({
type: z.literal('hysteria2'),
hop_ports: nullableString,
hop_interval: z.number().nullish(),
obfs_password: nullableString,
obfs: z.enum(['none', 'salamander'] as const).nullish(),
port: nullablePort,
security: z.enum(SECURITY.hysteria2 as any).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
up_mbps: z.number().nullish(),
down_mbps: z.number().nullish(),
});
const tuic = z.object({
type: z.literal('tuic'),
host: nullableString,
port: nullablePort,
disable_sni: z.boolean().nullish(),
reduce_rtt: z.boolean().nullish(),
udp_relay_mode: z.enum(TUIC_UDP_RELAY_MODES as any).nullish(),
congestion_controller: z.enum(TUIC_CONGESTION as any).nullish(),
security: z.enum(SECURITY.tuic as any).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const anytls = z.object({
type: z.literal('anytls'),
port: nullablePort,
security: z.enum(SECURITY.anytls as any).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
padding_scheme: nullableString,
});
const socks = z.object({
type: z.literal('socks'),
port: nullablePort,
});
const naive = z.object({
type: z.literal('naive'),
port: nullablePort,
security: z.enum(SECURITY.naive as any).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const http = z.object({
type: z.literal('http'),
port: nullablePort,
security: z.enum(SECURITY.http as any).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const meru = z.object({
type: z.literal('meru'),
port: nullablePort,
multiplex: z.enum(multiplexLevels).nullish(),
transport: z.enum(TRANSPORTS.meru as any).nullish(),
});
export const protocolApiScheme = z.discriminatedUnion('type', [
ss,
vmess,
vless,
trojan,
hysteria2,
tuic,
anytls,
socks,
naive,
http,
meru,
]);
export const formSchema = z.object({
name: z.string().min(1),
address: z.string().min(1),
country: z.string().optional(),
city: z.string().optional(),
ratio: z.number().default(1),
protocols: z.array(protocolApiScheme),
});
export type ServerFormValues = z.infer<typeof formSchema>;
export type ProtocolType = (typeof protocols)[number];
export function getProtocolDefaultConfig(proto: ProtocolType) {
switch (proto) {
case 'shadowsocks':
return {
type: 'shadowsocks',
port: null,
cipher: 'chacha20-ietf-poly1305',
server_key: null,
obfs: 'none',
obfs_host: null,
obfs_path: null,
} as any;
case 'vmess':
return { type: 'vmess', port: null, transport: 'tcp', security: 'none' } as any;
case 'vless':
return { type: 'vless', port: null, transport: 'tcp', security: 'none', flow: 'none' } as any;
case 'trojan':
return { type: 'trojan', port: null, transport: 'tcp', security: 'tls' } as any;
case 'hysteria2':
return {
type: 'hysteria2',
port: null,
hop_ports: null,
hop_interval: null,
obfs: 'none',
obfs_password: null,
security: 'tls',
up_mbps: null,
down_mbps: null,
} as any;
case 'tuic':
return {
type: 'tuic',
port: null,
disable_sni: false,
reduce_rtt: false,
udp_relay_mode: 'native',
congestion_controller: 'bbr',
security: 'tls',
sni: null,
allow_insecure: false,
fingerprint: 'chrome',
} as any;
case 'socks':
return {
type: 'socks',
port: null,
} as any;
case 'naive':
return {
type: 'naive',
port: null,
security: 'none',
} as any;
case 'http':
return {
type: 'http',
port: null,
security: 'none',
} as any;
case 'meru':
return {
type: 'meru',
port: null,
multiplex: 'none',
transport: 'tcp',
} as any;
case 'anytls':
return {
type: 'anytls',
port: null,
security: 'tls',
padding_scheme: null,
sni: null,
allow_insecure: false,
fingerprint: 'chrome',
} as any;
default:
return {} as any;
}
}
import {
generateMLKEM768KeyPair,
generatePassword,
generateRealityKeyPair,
generateRealityShortId,
} from '../generate';
import {
ENCRYPTION_MODES,
ENCRYPTION_RTT,
ENCRYPTION_TYPES,
FINGERPRINTS,
FLOWS,
multiplexLevels,
SECURITY,
SS_CIPHERS,
TRANSPORTS,
TUIC_CONGESTION,
TUIC_UDP_RELAY_MODES,
XHTTP_MODES,
} from './constants';
import type { FieldConfig } from './types';
export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
shadowsocks: [
@@ -561,7 +211,7 @@ export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
condition: (p) => p.transport === 'grpc',
},
{
name: 'mode',
name: 'xhttp_mode',
type: 'select',
label: 'mode',
options: XHTTP_MODES,
@@ -570,7 +220,7 @@ export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
condition: (p) => p.transport === 'xhttp',
},
{
name: 'extra',
name: 'xhttp_extra',
type: 'textarea',
label: 'extra',
placeholder: '{}',
@@ -700,10 +350,10 @@ export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
placeholder: (t) => t('encryption_private_key_placeholder'),
group: 'encryption',
generate: {
function: () => generateVlessX25519Pair(),
function: generateMLKEM768KeyPair,
updateFields: {
encryption_private_key: 'privateKeyB64',
encryption_password: 'passwordB64',
encryption_private_key: 'privateKey',
encryption_password: 'publicKey',
},
},
condition: (p) => p.encryption === 'mlkem768x25519plus',
@@ -1006,7 +656,7 @@ export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
condition: (p) => p.security !== 'none',
},
],
meru: [
mieru: [
{
name: 'port',
type: 'number',
@@ -1028,7 +678,7 @@ export const PROTOCOL_FIELDS: Record<string, FieldConfig[]> = {
name: 'transport',
type: 'select',
label: 'transport',
options: TRANSPORTS.meru,
options: TRANSPORTS.mieru,
defaultValue: 'tcp',
group: 'transport',
},
@@ -0,0 +1,30 @@
// Re-export all constants
export {
ENCRYPTION_MODES,
ENCRYPTION_RTT,
ENCRYPTION_TYPES,
FINGERPRINTS,
FLOWS,
LABELS,
SECURITY,
SS_CIPHERS,
TRANSPORTS,
TUIC_CONGESTION,
TUIC_UDP_RELAY_MODES,
XHTTP_MODES,
getLabel,
multiplexLevels,
protocols,
} from './constants';
// Re-export all types
export type { FieldConfig, ProtocolType } from './types';
// Re-export all schemas
export { formSchema, protocolApiScheme } from './schemas';
// Re-export defaults
export { getProtocolDefaultConfig } from './defaults';
// Re-export fields
export { PROTOCOL_FIELDS } from './fields';
@@ -0,0 +1,187 @@
import { z } from 'zod';
import {
ENCRYPTION_MODES,
ENCRYPTION_RTT,
ENCRYPTION_TYPES,
FLOWS,
multiplexLevels,
SECURITY,
SS_CIPHERS,
TRANSPORTS,
TUIC_CONGESTION,
TUIC_UDP_RELAY_MODES,
XHTTP_MODES,
} from './constants';
const nullableString = z.string().nullish();
const nullableBool = z.boolean().nullish();
const nullablePort = z.number().int().min(0).max(65535).nullish();
const ss = z.object({
type: z.literal('shadowsocks'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
cipher: z.enum(SS_CIPHERS).nullish(),
server_key: nullableString,
obfs: z.enum(['none', 'http', 'tls'] as const).nullish(),
obfs_host: nullableString,
obfs_path: nullableString,
});
const vmess = z.object({
type: z.literal('vmess'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.vmess).nullish(),
security: z.enum(SECURITY.vmess).nullish(),
path: nullableString,
service_name: nullableString,
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const vless = z.object({
type: z.literal('vless'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.vless).nullish(),
security: z.enum(SECURITY.vless).nullish(),
path: nullableString,
service_name: nullableString,
flow: z.enum(FLOWS.vless).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
reality_server_addr: nullableString,
reality_server_port: nullablePort,
reality_private_key: nullableString,
reality_public_key: nullableString,
reality_short_id: nullableString,
xhttp_mode: z.enum(XHTTP_MODES).nullish(),
xhttp_extra: nullableString,
encryption: z.enum(ENCRYPTION_TYPES).nullish(),
encryption_mode: z.enum(ENCRYPTION_MODES).nullish(),
encryption_rtt: z.enum(ENCRYPTION_RTT).nullish(),
encryption_ticket: nullableString,
encryption_server_padding: nullableString,
encryption_private_key: nullableString,
encryption_client_padding: nullableString,
encryption_password: nullableString,
});
const trojan = z.object({
type: z.literal('trojan'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
transport: z.enum(TRANSPORTS.trojan).nullish(),
security: z.enum(SECURITY.trojan).nullish(),
path: nullableString,
service_name: nullableString,
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const hysteria2 = z.object({
type: z.literal('hysteria2'),
enable: nullableBool,
hop_ports: nullableString,
hop_interval: z.number().nullish(),
obfs_password: nullableString,
obfs: z.enum(['none', 'salamander'] as const).nullish(),
port: nullablePort,
security: z.enum(SECURITY.hysteria2).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
up_mbps: z.number().nullish(),
down_mbps: z.number().nullish(),
});
const tuic = z.object({
type: z.literal('tuic'),
enable: nullableBool,
host: nullableString,
port: nullablePort,
disable_sni: z.boolean().nullish(),
reduce_rtt: z.boolean().nullish(),
udp_relay_mode: z.enum(TUIC_UDP_RELAY_MODES).nullish(),
congestion_controller: z.enum(TUIC_CONGESTION).nullish(),
security: z.enum(SECURITY.tuic).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const anytls = z.object({
type: z.literal('anytls'),
enable: nullableBool,
port: nullablePort,
security: z.enum(SECURITY.anytls).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
padding_scheme: nullableString,
});
const socks = z.object({
type: z.literal('socks'),
enable: nullableBool,
port: nullablePort,
});
const naive = z.object({
type: z.literal('naive'),
enable: nullableBool,
port: nullablePort,
security: z.enum(SECURITY.naive).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const http = z.object({
type: z.literal('http'),
enable: nullableBool,
port: nullablePort,
security: z.enum(SECURITY.http).nullish(),
sni: nullableString,
allow_insecure: nullableBool,
fingerprint: nullableString,
});
const mieru = z.object({
type: z.literal('mieru'),
enable: nullableBool,
port: nullablePort,
multiplex: z.enum(multiplexLevels).nullish(),
transport: z.enum(TRANSPORTS.mieru).nullish(),
});
export const protocolApiScheme = z.discriminatedUnion('type', [
ss,
vmess,
vless,
trojan,
hysteria2,
tuic,
anytls,
socks,
naive,
http,
mieru,
]);
export const formSchema = z.object({
name: z.string().min(1),
address: z.string().min(1),
country: z.string().optional(),
city: z.string().optional(),
ratio: z.number().default(1),
protocols: z.array(protocolApiScheme),
});
@@ -0,0 +1,23 @@
import { protocols } from './constants';
export type FieldConfig = {
name: string;
type: 'input' | 'select' | 'switch' | 'number' | 'textarea';
label: string;
placeholder?: string | ((t: (key: string) => string, protocol: any) => string);
options?: readonly string[];
defaultValue?: any;
min?: number;
max?: number;
step?: number;
suffix?: string;
generate?: {
function: () => Promise<string | Record<string, string>> | string | Record<string, string>;
updateFields?: Record<string, string>;
};
condition?: (protocol: any, values: any) => boolean;
group?: 'basic' | 'transport' | 'security' | 'reality' | 'obfs' | 'encryption';
gridSpan?: 1 | 2;
};
export type ProtocolType = (typeof protocols)[number];
@@ -1,6 +1,4 @@
export { generatePassword } from './random';
export {
generateRealityKeyPair,
generateRealityShortId,
publicKeyFromPrivate,
} from './reality-key';
export { generateMLKEM768KeyPair } from './mlkem768';
export { generateRealityShortId } from './short-id';
export { generatePassword } from './uid';
export { generateRealityKeyPair } from './x25519';
@@ -0,0 +1,16 @@
import mlkem from 'mlkem-wasm';
import { toB64Url } from './util';
export async function generateMLKEM768KeyPair() {
const mlkemKeyPair = await mlkem.generateKey({ name: 'ML-KEM-768' }, true, [
'encapsulateBits',
'decapsulateBits',
]);
const mlkemPublicKeyRaw = await mlkem.exportKey('raw-public', mlkemKeyPair.publicKey);
const mlkemPrivateKeyRaw = await mlkem.exportKey('raw-seed', mlkemKeyPair.privateKey);
return {
publicKey: toB64Url(new Uint8Array(mlkemPublicKeyRaw)),
privateKey: toB64Url(new Uint8Array(mlkemPrivateKeyRaw)),
};
}
@@ -1,23 +0,0 @@
import { x25519 } from '@noble/curves/ed25519';
const toB64Url = (u8: Uint8Array) =>
(typeof Buffer !== 'undefined'
? Buffer.from(u8).toString('base64')
: btoa(String.fromCharCode(...u8))
)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
export type VlessX25519Pair = {
passwordB64: string;
privateKeyB64: string;
};
export function generateVlessX25519Pair(): VlessX25519Pair {
const { secretKey, publicKey } = x25519.keygen();
return {
passwordB64: toB64Url(publicKey),
privateKeyB64: toB64Url(secretKey),
};
}
@@ -1,49 +0,0 @@
import { x25519 } from '@noble/curves/ed25519.js';
function toB64Url(bytes: Uint8Array) {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
}
function fromB64Url(s: string) {
const b64 = s
.replace(/-/g, '+')
.replace(/_/g, '/')
.padEnd(Math.ceil(s.length / 4) * 4, '=');
const bin = atob(b64);
return new Uint8Array([...bin].map((c) => c.charCodeAt(0)));
}
/**
* Generate a Reality key pair
* @returns An object containing the private and public keys in base64url format
*/
export function generateRealityKeyPair() {
const { secretKey, publicKey } = x25519.keygen();
return { privateKey: toB64Url(secretKey), publicKey: toB64Url(publicKey) };
}
/**
* Derive public key from private key
* @param privateKeyB64Url Private key in base64url format
* @returns Public key in base64url format
*/
export function publicKeyFromPrivate(privateKeyB64Url: string) {
return toB64Url(x25519.getPublicKey(fromB64Url(privateKeyB64Url)));
}
/**
* Generate a short ID for Reality
* @returns A random hexadecimal string of length 2, 4, 6, 8, 10, 12, 14, or 16
*/
export function generateRealityShortId() {
const hex = '0123456789abcdef';
const lengths = [2, 4, 6, 8, 10, 12, 14, 16];
const idx = Math.floor(Math.random() * lengths.length);
const len = lengths[idx] ?? 16;
let out = '';
for (let i = 0; i < len; i++) {
out += hex.charAt(Math.floor(Math.random() * hex.length));
}
return out;
}
@@ -0,0 +1,15 @@
/**
* Generate a short ID for Reality
* @returns A random hexadecimal string of length 2, 4, 6, 8, 10, 12, 14, or 16
*/
export function generateRealityShortId() {
const hex = '0123456789abcdef';
const lengths = [2, 4, 6, 8, 10, 12, 14, 16];
const idx = Math.floor(Math.random() * lengths.length);
const len = lengths[idx] ?? 16;
let out = '';
for (let i = 0; i < len; i++) {
out += hex.charAt(Math.floor(Math.random() * hex.length));
}
return out;
}
@@ -0,0 +1,6 @@
export function toB64Url(bytes: Uint8Array) {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
}
@@ -0,0 +1,11 @@
import { x25519 } from '@noble/curves/ed25519';
import { toB64Url } from './util';
/**
* Generate a Reality key pair
* @returns An object containing the private and public keys in base64url format
*/
export function generateRealityKeyPair() {
const { secretKey, publicKey } = x25519.keygen();
return { privateKey: toB64Url(secretKey), publicKey: toB64Url(publicKey) };
}
+27 -28
View File
@@ -1,5 +1,5 @@
'use client';
// Online users detail moved to separate component
import { ProTable, ProTableActions } from '@/components/pro-table';
import {
createServer,
@@ -10,6 +10,8 @@ import {
resetSortWithServer,
updateServer,
} from '@/services/admin/server';
import { useNode } from '@/store/node';
import { useServer } from '@/store/server';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
import { Button } from '@workspace/ui/components/button';
@@ -23,18 +25,6 @@ import OnlineUsersCell from './online-users-cell';
import ServerConfig from './server-config';
import ServerForm from './server-form';
type ProtocolName = 'shadowsocks' | 'vmess' | 'vless' | 'trojan' | 'hysteria2' | 'tuic' | 'anytls';
const PROTOCOL_COLORS: Record<ProtocolName, string> = {
shadowsocks: 'bg-green-500',
vmess: 'bg-rose-500',
vless: 'bg-blue-500',
trojan: 'bg-yellow-500',
hysteria2: 'bg-purple-500',
tuic: 'bg-cyan-500',
anytls: 'bg-gray-500',
};
function PctBar({ value }: { value: number }) {
const v = value.toFixed(2);
return (
@@ -69,6 +59,8 @@ function RegionIpCell({
export default function ServersPage() {
const t = useTranslations('servers');
const { isServerReferencedByNodes } = useNode();
const { fetchServers } = useServer();
const [loading, setLoading] = useState(false);
const [migrating, setMigrating] = useState(false);
@@ -129,6 +121,7 @@ export default function ServersPage() {
await createServer(values as unknown as API.CreateServerRequest);
toast.success(t('created'));
ref.current?.refresh();
fetchServers();
setLoading(false);
return true;
} catch (e) {
@@ -163,23 +156,16 @@ export default function ServersPage() {
accessorKey: 'protocols',
header: t('protocols'),
cell: ({ row }) => {
const list = (row.original.protocols || []) as API.Protocol[];
if (!list.length) return t('noData');
const list = row.original.protocols.filter(
(p) => p.enable !== false,
) as API.Protocol[];
if (!list.length) return '—';
return (
<div className='flex flex-wrap gap-1'>
{list.map((p, idx) => {
const proto = ((p as any)?.type || '') as ProtocolName | '';
if (!proto) return null;
const color = PROTOCOL_COLORS[proto as ProtocolName];
const port = (p as any)?.port as number | undefined;
const label = `${proto}${port ? ` (${port})` : ''}`;
return (
<Badge
key={idx}
variant='outline'
className={cn('text-primary-foreground', color)}
>
{label}
<Badge key={idx} variant='outline'>
{p.type} ({p.port})
</Badge>
);
})}
@@ -272,6 +258,7 @@ export default function ServersPage() {
});
toast.success(t('updated'));
ref.current?.refresh();
fetchServers();
setLoading(false);
return true;
} catch (e) {
@@ -282,13 +269,18 @@ export default function ServersPage() {
/>,
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
trigger={
<Button variant='destructive' disabled={isServerReferencedByNodes(row.id)}>
{t('delete')}
</Button>
}
title={t('confirmDeleteTitle')}
description={t('confirmDeleteDesc')}
onConfirm={async () => {
await deleteServer({ id: row.id } as any);
toast.success(t('deleted'));
ref.current?.refresh();
fetchServers();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
@@ -311,6 +303,7 @@ export default function ServersPage() {
await createServer(body);
toast.success(t('copied'));
ref.current?.refresh();
fetchServers();
setLoading(false);
}}
>
@@ -318,16 +311,22 @@ export default function ServersPage() {
</Button>,
],
batchRender(rows) {
const hasReferencedServers = rows.some((row) => isServerReferencedByNodes(row.id));
return [
<ConfirmButton
key='delete'
trigger={<Button variant='destructive'>{t('delete')}</Button>}
trigger={
<Button variant='destructive' disabled={hasReferencedServers}>
{t('delete')}
</Button>
}
title={t('confirmDeleteTitle')}
description={t('confirmDeleteDesc')}
onConfirm={async () => {
await Promise.all(rows.map((r) => deleteServer({ id: r.id })));
toast.success(t('deleted'));
ref.current?.refresh();
fetchServers();
}}
cancelText={t('cancel')}
confirmText={t('confirm')}
@@ -1,5 +1,6 @@
'use client';
import { useNode } from '@/store/node';
import { zodResolver } from '@hookform/resolvers/zod';
import {
Accordion,
@@ -48,7 +49,6 @@ import {
getProtocolDefaultConfig,
PROTOCOL_FIELDS,
protocols as PROTOCOLS,
ServerFormValues,
} from './form-schema';
function DynamicField({
@@ -102,8 +102,8 @@ function DynamicField({
<Button
type='button'
variant='ghost'
onClick={() => {
const result = field.generate!.function();
onClick={async () => {
const result = await field.generate!.function();
if (typeof result === 'string') {
fieldProps.onChange(result);
} else if (field.generate!.updateFields) {
@@ -321,14 +321,16 @@ export default function ServerForm(props: {
trigger: string;
title: string;
loading?: boolean;
initialValues?: Partial<ServerFormValues>;
onSubmit: (values: ServerFormValues) => Promise<boolean> | boolean;
initialValues?: Partial<API.Server>;
onSubmit: (values: Partial<API.Server>) => Promise<boolean> | boolean;
}) {
const { trigger, title, loading, initialValues, onSubmit } = props;
const t = useTranslations('servers');
const [open, setOpen] = useState(false);
const [accordionValue, setAccordionValue] = useState<string>();
const { isProtocolUsedInNodes } = useNode();
const form = useForm({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -337,7 +339,7 @@ export default function ServerForm(props: {
country: '',
city: '',
ratio: 1,
protocols: [],
protocols: [] as any[],
...initialValues,
},
});
@@ -364,24 +366,18 @@ export default function ServerForm(props: {
}, [initialValues]);
async function handleSubmit(values: Record<string, any>) {
const filtered = (values?.protocols || []).filter((p: any, index: number) => {
const port = Number(p?.port);
const protocolType = PROTOCOLS[index];
return protocolType && p && Number.isFinite(port) && port > 0 && port <= 65535;
const filteredProtocols = (values?.protocols || []).filter((protocol: any) => {
const port = Number(protocol?.port);
return protocol && Number.isFinite(port) && port > 0 && port <= 65535;
});
if (filtered.length === 0) {
toast.error(t('validation_failed'));
return;
}
const result = {
name: values.name,
country: values.country,
city: values.city,
ratio: Number(values.ratio || 1),
ratio: values.ratio || 1,
address: values.address,
protocols: filtered,
protocols: filteredProtocols,
};
const ok = await onSubmit(result);
@@ -507,6 +503,7 @@ export default function ServerForm(props: {
{t('protocol_configurations_desc')}
</p>
</div>
<Accordion
type='single'
collapsible
@@ -520,39 +517,50 @@ export default function ServerForm(props: {
PROTOCOLS.findIndex((t) => t === type),
);
const current = (protocolsValues[i] || {}) as Record<string, any>;
const isEnabled = current.port && Number(current.port) > 0;
const isEnabled = current?.enable !== false;
const fields = PROTOCOL_FIELDS[type] || [];
return (
<AccordionItem key={type} value={type} className='mb-2 rounded-lg border'>
<AccordionTrigger className='px-4 py-3 hover:no-underline'>
<div className='flex w-full items-center justify-between'>
<div className='flex flex-col items-start'>
<div className='flex items-center gap-2'>
<div className='flex flex-col items-start gap-1'>
<div className='flex items-center gap-1'>
<span className='font-medium capitalize'>{type}</span>
</div>
<span
className={cn(
'text-muted-foreground text-xs',
isEnabled && 'text-green-500',
{current.transport && (
<Badge variant='secondary' className='text-xs'>
{current.transport.toUpperCase()}
</Badge>
)}
>
{isEnabled ? t('enabled') : t('disabled')}
</span>
{current.security && current.security !== 'none' && (
<Badge variant='outline' className='text-xs'>
{current.security.toUpperCase()}
</Badge>
)}
{current.port && <Badge className='text-xs'>{current.port}</Badge>}
</div>
<div className='flex items-center gap-1'>
<span
className={cn(
'text-xs',
isEnabled ? 'text-green-500' : 'text-muted-foreground',
)}
>
{isEnabled ? t('enabled') : t('disabled')}
</span>
</div>
</div>
<div className='mr-2 flex items-center gap-1'>
{current.transport && (
<Badge variant='secondary' className='text-xs'>
{current.transport.toUpperCase()}
</Badge>
<Switch
className='mr-2'
checked={!!isEnabled}
disabled={Boolean(
initialValues?.id &&
isProtocolUsedInNodes(initialValues?.id || 0, type),
)}
{current.security && current.security !== 'none' && (
<Badge variant='outline' className='text-xs'>
{current.security.toUpperCase()}
</Badge>
)}
{current.port && <Badge className='text-xs'>{current.port}</Badge>}
</div>
onCheckedChange={(checked) => {
form.setValue(`protocols.${i}.enable`, checked);
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
</AccordionTrigger>
<AccordionContent className='px-4 pb-4 pt-0'>
@@ -621,7 +629,8 @@ export default function ServerForm(props: {
return false;
})}
>
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />} {t('confirm')}
{loading && <Icon icon='mdi:loading' className='mr-2 animate-spin' />}
{t('confirm')}
</Button>
</SheetFooter>
</SheetContent>
@@ -56,6 +56,7 @@ import { useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { z } from 'zod';
import { subscribeSchema } from './schema';
import { TemplatePreview } from './template-preview';
const createClientFormSchema = (t: any) =>
@@ -662,137 +663,7 @@ export function ProtocolForm() {
<FormControl>
<GoTemplateEditor
showLineNumbers
schema={{
SiteName: { type: 'string', description: 'Site name' },
SubscribeName: { type: 'string', description: 'Subscribe name' },
Proxies: {
type: 'array',
description: 'Array of proxy nodes',
items: {
type: 'object',
properties: {
Name: { type: 'string', description: 'Node name' },
Server: { type: 'string', description: 'Server host' },
Port: { type: 'number', description: 'Server port' },
Type: { type: 'string', description: 'Proxy type' },
Tags: {
type: 'array',
description: 'Node tags',
items: { type: 'string' },
},
Sort: { type: 'number', description: 'Node sort order' },
// Security Options
Security: {
type: 'string',
description: 'Security protocol',
},
SNI: {
type: 'string',
description: 'Server Name Indication for TLS',
},
AllowInsecure: {
type: 'boolean',
description:
'Allow insecure connections (skip certificate verification)',
},
Fingerprint: {
type: 'string',
description: 'Client fingerprint for TLS connections',
},
RealityServerAddr: {
type: 'string',
description: 'Reality server address',
},
RealityServerPort: {
type: 'number',
description: 'Reality server port',
},
RealityPrivateKey: {
type: 'string',
description: 'Reality private key for authentication',
},
RealityPublicKey: {
type: 'string',
description: 'Reality public key for authentication',
},
RealityShortId: {
type: 'string',
description: 'Reality short ID for authentication',
},
// Transport Options
Transport: {
type: 'string',
description: 'Transport protocol (e.g., ws, http, grpc)',
},
Host: {
type: 'string',
description: 'For WebSocket/HTTP/HTTPS',
},
Path: { type: 'string', description: 'For HTTP/HTTPS' },
ServiceName: {
type: 'string',
description: 'For gRPC',
},
// Shadowsocks Options
Method: { type: 'string', description: 'Encryption method' },
ServerKey: {
type: 'string',
description: 'For Shadowsocks 2022',
},
// Vmess/Vless/Trojan Options
Flow: {
type: 'string',
description: 'Flow for Vmess/Vless/Trojan',
},
// Hysteria2 Options
HopPorts: {
type: 'string',
description: 'Comma-separated list of hop ports',
},
HopInterval: {
type: 'number',
description: 'Interval for hop ports in seconds',
},
ObfsPassword: {
type: 'string',
description: 'Obfuscation password for Hysteria2',
},
// Tuic Options
DisableSNI: {
type: 'boolean',
description: 'Disable SNI',
},
ReduceRtt: {
type: 'boolean',
description: 'Reduce RTT',
},
UDPRelayMode: {
type: 'string',
description: 'UDP relay mode (e.g., "full", "partial")',
},
CongestionController: {
type: 'string',
description: 'Congestion controller (e.g., "cubic", "bbr")',
},
},
},
},
UserInfo: {
type: 'object',
description: 'User information',
properties: {
Password: { type: 'string', description: 'User password' },
ExpiredAt: { type: 'string', description: 'Expiration date' },
Download: { type: 'number', description: 'Downloaded bytes' },
Upload: { type: 'number', description: 'Uploaded bytes' },
Traffic: { type: 'number', description: 'Total traffic bytes' },
SubscribeURL: {
type: 'string',
description: 'Subscription URL',
},
},
},
}}
schema={subscribeSchema}
enableSprig
value={field.value || ''}
onChange={(value) => field.onChange(value)}
@@ -0,0 +1,238 @@
export const subscribeSchema = {
SiteName: { type: 'string', description: 'Site name' },
SubscribeName: { type: 'string', description: 'Subscribe name' },
Proxies: {
type: 'array',
description: 'Array of proxy nodes',
items: {
type: 'object',
properties: {
Name: { type: 'string', description: 'Node name' },
Server: { type: 'string', description: 'Server host' },
Port: { type: 'number', description: 'Server port' },
Type: { type: 'string', description: 'Proxy type' },
Tags: {
type: 'array',
description: 'Node tags',
items: { type: 'string' },
},
Sort: { type: 'number', description: 'Node sort order' },
// Security Options
Security: {
type: 'string',
description: 'Security protocol',
},
SNI: {
type: 'string',
description: 'Server Name Indication for TLS',
},
AllowInsecure: {
type: 'boolean',
description: 'Allow insecure connections (skip certificate verification)',
},
Fingerprint: {
type: 'string',
description: 'Client fingerprint for TLS connections',
},
RealityServerAddr: {
type: 'string',
description: 'Reality server address',
},
RealityServerPort: {
type: 'number',
description: 'Reality server port',
},
RealityPrivateKey: {
type: 'string',
description: 'Reality private key for authentication',
},
RealityPublicKey: {
type: 'string',
description: 'Reality public key for authentication',
},
RealityShortId: {
type: 'string',
description: 'Reality short ID for authentication',
},
// Transport Options
Transport: {
type: 'string',
description: 'Transport protocol (e.g., ws, http, grpc)',
},
Host: {
type: 'string',
description: 'For WebSocket/HTTP/HTTPS',
},
Path: { type: 'string', description: 'For HTTP/HTTPS' },
ServiceName: {
type: 'string',
description: 'For gRPC',
},
// Shadowsocks Options
Method: { type: 'string', description: 'Encryption method' },
ServerKey: {
type: 'string',
description: 'For Shadowsocks 2022',
},
// Vmess/Vless/Trojan Options
Flow: {
type: 'string',
description: 'Flow for Vmess/Vless/Trojan',
},
// Hysteria2 Options
HopPorts: {
type: 'string',
description: 'Comma-separated list of hop ports',
},
HopInterval: {
type: 'number',
description: 'Interval for hop ports in seconds',
},
ObfsPassword: {
type: 'string',
description: 'Obfuscation password for Hysteria2',
},
// Tuic Options
DisableSNI: {
type: 'boolean',
description: 'Disable SNI',
},
ReduceRtt: {
type: 'boolean',
description: 'Reduce RTT',
},
UDPRelayMode: {
type: 'string',
description: 'UDP relay mode (e.g., "full", "partial")',
},
CongestionController: {
type: 'string',
description: 'Congestion controller (e.g., "cubic", "bbr")',
},
// Hysteria2 additional options
UpMbps: {
type: 'number',
description: 'Upload bandwidth in Mbps',
},
DownMbps: {
type: 'number',
description: 'Download bandwidth in Mbps',
},
// VLESS encryption options
Encryption: {
type: 'string',
description: 'Encryption type for VLESS',
},
EncryptionMode: {
type: 'string',
description: 'Encryption mode (e.g., "native", "xorpub", "random")',
},
EncryptionRtt: {
type: 'string',
description: 'Encryption RTT (e.g., "0rtt", "1rtt")',
},
EncryptionTicket: {
type: 'string',
description: 'Encryption ticket',
},
EncryptionServerPadding: {
type: 'string',
description: 'Server padding for encryption',
},
EncryptionClientPadding: {
type: 'string',
description: 'Client padding for encryption',
},
EncryptionPassword: {
type: 'string',
description: 'Encryption password',
},
EncryptionPrivateKey: {
type: 'string',
description: 'Private key for encryption',
},
// XHTTP options
XhttpMode: {
type: 'string',
description: 'XHTTP mode (e.g., "auto", "packet-up", "stream-up", "stream-one")',
},
XhttpExtra: {
type: 'string',
description: 'XHTTP extra parameters',
},
// Shadowsocks obfs options (combined with Hysteria2 obfs)
ObfsHost: {
type: 'string',
description: 'Obfuscation host',
},
ObfsPath: {
type: 'string',
description: 'Obfuscation path',
},
// Shadowsocks cipher
Cipher: {
type: 'string',
description: 'Shadowsocks cipher method',
},
// AnyTLS options
PaddingScheme: {
type: 'string',
description: 'Padding scheme for AnyTLS',
},
// Mieru options
Multiplex: {
type: 'string',
description: 'Multiplex level (e.g., "none", "low", "middle", "high")',
},
// General protocol field
Enable: {
type: 'boolean',
description: 'Whether this protocol is enabled',
},
// Node metadata
Country: {
type: 'string',
description: 'Node country',
},
City: {
type: 'string',
description: 'Node city',
},
Ratio: {
type: 'number',
description: 'Traffic ratio multiplier',
},
// UUID for vmess/vless
UUID: {
type: 'string',
description: 'User UUID for vmess/vless protocols',
},
// Alternative ID for vmess
AlterId: {
type: 'number',
description: 'Alternative ID for vmess (deprecated)',
},
// Password for trojan/tuic
Password: {
type: 'string',
description: 'Password for authentication',
},
},
},
},
UserInfo: {
type: 'object',
description: 'User information',
properties: {
Password: { type: 'string', description: 'User password' },
ExpiredAt: { type: 'string', description: 'Expiration date' },
Download: { type: 'number', description: 'Downloaded bytes' },
Upload: { type: 'number', description: 'Uploaded bytes' },
Traffic: { type: 'number', description: 'Total traffic bytes' },
SubscribeURL: {
type: 'string',
description: 'Subscription URL',
},
},
},
};
@@ -3,7 +3,13 @@
import { previewSubscribeTemplate } from '@/services/admin/application';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@workspace/ui/components/sheet';
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@workspace/ui/components/sheet';
import { MonacoEditor } from '@workspace/ui/custom-components/editor/monaco-editor';
import { Icon } from '@workspace/ui/custom-components/icon';
import { useTranslations } from 'next-intl';
@@ -68,36 +74,33 @@ export function TemplatePreview({ applicationId, output_format }: TemplatePrevie
}
};
const handleOpenChange = (newOpen: boolean) => {
setIsOpen(newOpen);
};
return (
<>
<Button variant='ghost' size='sm' onClick={() => setIsOpen(true)}>
<Icon icon='mdi:eye' className='mr-2 h-4 w-4' />
{t('preview')}
</Button>
<Sheet open={isOpen} onOpenChange={handleOpenChange}>
<SheetHeader>
<SheetTitle></SheetTitle>
</SheetHeader>
<SheetContent className='w-[800px] max-w-[90vw] md:max-w-screen-md'>
{isLoading ? (
<div className='flex items-center justify-center'>
<Icon icon='mdi:loading' className='h-6 w-6 animate-spin' />
<span className='ml-2'>{t('loading')}</span>
</div>
) : (
<MonacoEditor
title={t('title')}
value={getDisplayContent()}
language={mapLanguage(output_format)}
readOnly
/>
)}
</SheetContent>
</Sheet>
</>
<Sheet open={isOpen} onOpenChange={setIsOpen}>
<SheetTrigger asChild>
<Button variant='ghost'>
<Icon icon='mdi:eye' className='h-4 w-4' />
{t('preview')}
</Button>
</SheetTrigger>
<SheetHeader>
<SheetTitle></SheetTitle>
</SheetHeader>
<SheetContent className='w-[800px] max-w-[90vw] pt-10 md:max-w-screen-md'>
{isLoading ? (
<div className='flex items-center justify-center'>
<Icon icon='mdi:loading' className='h-6 w-6 animate-spin' />
<span className='ml-2'>{t('loading')}</span>
</div>
) : (
<MonacoEditor
title={t('title')}
value={getDisplayContent()}
language={mapLanguage(output_format)}
showLineNumbers
readOnly
/>
)}
</SheetContent>
</Sheet>
);
}
@@ -1,7 +1,7 @@
'use client';
import { getSubscribeList } from '@/services/admin/subscribe';
import { getRegisterConfig, updateRegisterConfig } from '@/services/admin/system';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
@@ -61,17 +61,7 @@ export default function RegisterConfig() {
enabled: open,
});
const { data: subscribe } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.Subscribe[];
},
enabled: open,
});
const { subscribes } = useSubscribe();
const form = useForm<RegisterFormData>({
resolver: zodResolver(registerSchema),
@@ -268,12 +258,10 @@ export default function RegisterConfig() {
field.onChange(value);
}
}}
options={
subscribe?.map((item) => ({
label: item.name,
value: item.id,
})) || []
}
options={subscribes?.map((item) => ({
label: item.name!,
value: item.id!,
}))}
className='bg-secondary w-32 rounded-r-none'
/>
)}
+5 -14
View File
@@ -2,7 +2,6 @@
import { Display } from '@/components/display';
import { ProTable, ProTableActions } from '@/components/pro-table';
import { getSubscribeList } from '@/services/admin/subscribe';
import {
createUser,
deleteUser,
@@ -10,6 +9,7 @@ import {
getUserList,
updateUserBasicInfo,
} from '@/services/admin/user';
import { useSubscribe } from '@/store/subscribe';
import { formatDate } from '@/utils/common';
import { useQuery } from '@tanstack/react-query';
import { Badge } from '@workspace/ui/components/badge';
@@ -49,16 +49,7 @@ export default function Page() {
const ref = useRef<ProTableActions>(null);
const sp = useSearchParams();
const { data: subscribeList } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.SubscribeGroup[];
},
});
const { subscribes } = useSubscribe();
const initialFilters = {
search: sp.get('search') || undefined,
@@ -194,9 +185,9 @@ export default function Page() {
{
key: 'subscribe_id',
placeholder: t('subscription'),
options: subscribeList?.map((item) => ({
label: item.name,
value: String(item.id),
options: subscribes?.map((item) => ({
label: item.name!,
value: String(item.id!),
})),
},
{
@@ -1,8 +1,7 @@
'use client';
import { getSubscribeList } from '@/services/admin/subscribe';
import { useSubscribe } from '@/store/subscribe';
import { zodResolver } from '@hookform/resolvers/zod';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/ui/components/button';
import {
Form,
@@ -74,16 +73,7 @@ export function SubscriptionForm({ trigger, title, loading, initialData, onSubmi
}
};
const { data: subscribe } = useQuery({
queryKey: ['getSubscribeList', 'all'],
queryFn: async () => {
const { data } = await getSubscribeList({
page: 1,
size: 9999,
});
return data.data?.list as API.Subscribe[];
},
});
const { subscribes } = useSubscribe();
return (
<Sheet open={open} onOpenChange={setOpen}>
@@ -117,9 +107,9 @@ export function SubscriptionForm({ trigger, title, loading, initialData, onSubmi
onChange={(value) => {
form.setValue(field.name, value);
}}
options={subscribe?.map((item: API.Subscribe) => ({
value: item.id,
label: item.name,
options={subscribes?.map((item) => ({
value: item.id!,
label: item.name!,
}))}
/>
</FormControl>
+1
View File
@@ -18,6 +18,7 @@
"ahooks": "^3.9.4",
"axios": "^1.11.0",
"js-yaml": "^4.1.0",
"mlkem-wasm": "^0.0.6",
"nanoid": "^5.1.5",
"next": "^15.5.2",
"next-intl": "^3.26.3",
+27 -4
View File
@@ -1496,6 +1496,7 @@ declare namespace API {
type Protocol = {
type: string;
port: number;
enable: boolean;
security?: string;
sni?: string;
allow_insecure?: boolean;
@@ -1519,10 +1520,6 @@ declare namespace API {
reduce_rtt?: boolean;
udp_relay_mode?: string;
congestion_controller?: string;
/** obfs, v2ray-plugin, simple-obfs */
plugin?: string;
/** plugin options, eg: obfs=http;obfs-host=www.bing.com */
plugin_options?: string;
/** mux, eg: off/low/medium/high */
multiplex?: string;
/** padding scheme */
@@ -1531,6 +1528,32 @@ declare namespace API {
up_mbps?: number;
/** download speed limit */
down_mbps?: number;
/** obfs, 'none', 'http', 'tls' */
obfs?: string;
/** obfs host */
obfs_host?: string;
/** obfs path */
obfs_path?: string;
/** xhttp mode */
xhttp_mode?: string;
/** xhttp extra path */
xhttp_extra?: string;
/** encryption'none', 'mlkem768x25519plus' */
encryption?: string;
/** encryption mode'native', 'xorpub', 'random' */
encryption_mode?: string;
/** encryption rtt'0rtt', '1rtt' */
encryption_rtt?: string;
/** encryption ticket */
encryption_ticket?: string;
/** encryption server padding */
encryption_server_padding?: string;
/** encryption private key */
encryption_private_key?: string;
/** encryption client padding */
encryption_client_padding?: string;
/** encryption password */
encryption_password?: string;
};
type PubilcRegisterConfig = {
+27 -4
View File
@@ -504,6 +504,7 @@ declare namespace API {
type Protocol = {
type: string;
port: number;
enable: boolean;
security?: string;
sni?: string;
allow_insecure?: boolean;
@@ -527,10 +528,6 @@ declare namespace API {
reduce_rtt?: boolean;
udp_relay_mode?: string;
congestion_controller?: string;
/** obfs, v2ray-plugin, simple-obfs */
plugin?: string;
/** plugin options, eg: obfs=http;obfs-host=www.bing.com */
plugin_options?: string;
/** mux, eg: off/low/medium/high */
multiplex?: string;
/** padding scheme */
@@ -539,6 +536,32 @@ declare namespace API {
up_mbps?: number;
/** download speed limit */
down_mbps?: number;
/** obfs, 'none', 'http', 'tls' */
obfs?: string;
/** obfs host */
obfs_host?: string;
/** obfs path */
obfs_path?: string;
/** xhttp mode */
xhttp_mode?: string;
/** xhttp extra path */
xhttp_extra?: string;
/** encryption'none', 'mlkem768x25519plus' */
encryption?: string;
/** encryption mode'native', 'xorpub', 'random' */
encryption_mode?: string;
/** encryption rtt'0rtt', '1rtt' */
encryption_rtt?: string;
/** encryption ticket */
encryption_ticket?: string;
/** encryption server padding */
encryption_server_padding?: string;
/** encryption private key */
encryption_private_key?: string;
/** encryption client padding */
encryption_client_padding?: string;
/** encryption password */
encryption_password?: string;
};
type PubilcRegisterConfig = {
+131
View File
@@ -0,0 +1,131 @@
import { filterNodeList, queryNodeTag } from '@/services/admin/server';
import { create } from 'zustand';
interface NodeState {
// Data
nodes: API.Node[];
tags: string[];
// Loading states
loading: boolean;
loadingTags: boolean;
// Actions
fetchNodes: () => Promise<void>;
fetchTags: () => Promise<void>;
// Getters
getNodeById: (nodeId: number) => API.Node | undefined;
isProtocolUsedInNodes: (serverId: number, protocolType: string) => boolean;
isServerReferencedByNodes: (serverId: number) => boolean;
getNodesByTag: (tag: string) => API.Node[];
getNodesWithoutTags: () => API.Node[];
getNodeTags: () => string[];
getAllAvailableTags: () => string[];
}
export const useNodeStore = create<NodeState>((set, get) => ({
// Initial state
nodes: [],
tags: [],
loading: false,
loadingTags: false,
// Actions
fetchNodes: async () => {
if (get().loading) return;
set({ loading: true });
try {
const { data } = await filterNodeList({ page: 1, size: 999999999 });
set({ nodes: data?.data?.list || [] });
} catch (error) {
// Handle error silently
} finally {
set({ loading: false });
}
},
fetchTags: async () => {
if (get().loadingTags) return;
set({ loadingTags: true });
try {
const { data } = await queryNodeTag();
set({ tags: data?.data?.tags || [] });
} catch (error) {
// Handle error silently
} finally {
set({ loadingTags: false });
}
},
// Getters
getNodeById: (nodeId: number) => {
return get().nodes.find((n) => n.id === nodeId);
},
isProtocolUsedInNodes: (serverId: number, protocolType: string) => {
return get().nodes.some(
(node) => node.server_id === serverId && node.protocol === protocolType,
);
},
isServerReferencedByNodes: (serverId: number) => {
return get().nodes.some((node) => node.server_id === serverId);
},
getNodesByTag: (tag: string) => {
return get().nodes.filter((node) => (node.tags || []).includes(tag));
},
getNodesWithoutTags: () => {
return get().nodes.filter((node) => (node.tags || []).length === 0);
},
getNodeTags: () => {
return Array.from(
new Set(
get()
.nodes.flatMap((node) => (Array.isArray(node.tags) ? node.tags : []))
.filter(Boolean),
),
) as string[];
},
getAllAvailableTags: () => {
const nodeExtractedTags = get().getNodeTags();
const allApiTags = get().tags;
return Array.from(new Set([...allApiTags, ...nodeExtractedTags])).filter(Boolean);
},
}));
export const useNode = () => {
const store = useNodeStore();
// Auto-fetch nodes and tags
if (store.nodes.length === 0 && !store.loading) {
store.fetchNodes();
}
if (store.tags.length === 0 && !store.loadingTags) {
store.fetchTags();
}
return {
nodes: store.nodes,
tags: store.tags,
loading: store.loading,
loadingTags: store.loadingTags,
fetchNodes: store.fetchNodes,
fetchTags: store.fetchTags,
getNodeById: store.getNodeById,
isProtocolUsedInNodes: store.isProtocolUsedInNodes,
isServerReferencedByNodes: store.isServerReferencedByNodes,
getNodesByTag: store.getNodesByTag,
getNodesWithoutTags: store.getNodesWithoutTags,
getNodeTags: store.getNodeTags,
getAllAvailableTags: store.getAllAvailableTags,
};
};
export default useNodeStore;
+104
View File
@@ -0,0 +1,104 @@
import { filterServerList } from '@/services/admin/server';
import { create } from 'zustand';
interface ServerState {
// Data
servers: API.Server[];
// Loading states
loading: boolean;
// Actions
fetchServers: () => Promise<void>;
// Getters
getServerById: (serverId: number) => API.Server | undefined;
getServerName: (serverId?: number) => string;
getServerAddress: (serverId?: number) => string;
getServerEnabledProtocols: (serverId: number) => API.Protocol[];
getProtocolPort: (serverId?: number, protocol?: string) => string;
getAvailableProtocols: (serverId?: number) => Array<{ protocol: string; port: number }>;
}
export const useServerStore = create<ServerState>((set, get) => ({
// Initial state
servers: [],
loading: false,
// Actions
fetchServers: async () => {
if (get().loading) return;
set({ loading: true });
try {
const { data } = await filterServerList({ page: 1, size: 999999999 });
set({ servers: data?.data?.list || [] });
} catch (error) {
// Handle error silently
} finally {
set({ loading: false });
}
},
// Getters
getServerById: (serverId: number) => {
return get().servers.find((s) => s.id === serverId);
},
getServerName: (serverId?: number) => {
if (!serverId) return '—';
const server = get().servers.find((s) => s.id === serverId);
return server?.name ?? `#${serverId}`;
},
getServerAddress: (serverId?: number) => {
if (!serverId) return '—';
const server = get().servers.find((s) => s.id === serverId);
return server?.address ?? '—';
},
getServerEnabledProtocols: (serverId: number) => {
const server = get().servers.find((s) => s.id === serverId);
return server?.protocols?.filter((p) => p.enable !== false) || [];
},
getProtocolPort: (serverId?: number, protocol?: string) => {
if (!serverId || !protocol) return '—';
const enabledProtocols = get().getServerEnabledProtocols(serverId);
const protocolConfig = enabledProtocols.find((p) => p.type === protocol);
return protocolConfig?.port ? String(protocolConfig.port) : '—';
},
getAvailableProtocols: (serverId?: number) => {
if (!serverId) return [];
return get()
.getServerEnabledProtocols(serverId)
.map((p) => ({
protocol: p.type,
port: p.port,
}));
},
}));
export const useServer = () => {
const store = useServerStore();
// Auto-fetch servers
if (store.servers.length === 0 && !store.loading) {
store.fetchServers();
}
return {
servers: store.servers,
loading: store.loading,
fetchServers: store.fetchServers,
getServerById: store.getServerById,
getServerName: store.getServerName,
getServerAddress: store.getServerAddress,
getServerEnabledProtocols: store.getServerEnabledProtocols,
getProtocolPort: store.getProtocolPort,
getAvailableProtocols: store.getAvailableProtocols,
};
};
export default useServerStore;
+68
View File
@@ -0,0 +1,68 @@
import { getSubscribeList } from '@/services/admin/subscribe';
import { create } from 'zustand';
interface SubscribeState {
// Data
subscribes: API.SubscribeItem[];
// Loading states
loading: boolean;
// Actions
fetchSubscribes: () => Promise<void>;
// Getters
getSubscribeName: (subscribeId?: number) => string;
getSubscribeById: (subscribeId: number) => API.SubscribeItem | undefined;
}
export const useSubscribeStore = create<SubscribeState>((set, get) => ({
// Initial state
subscribes: [],
loading: false,
// Actions
fetchSubscribes: async () => {
if (get().loading) return;
set({ loading: true });
try {
const { data } = await getSubscribeList({ page: 1, size: 999999999 });
set({ subscribes: data?.data?.list || [] });
} catch (error) {
// Handle error silently
} finally {
set({ loading: false });
}
},
// Getters
getSubscribeName: (subscribeId?: number) => {
if (!subscribeId) return 'Unknown';
const subscribe = get().subscribes.find((s) => s.id === subscribeId);
return subscribe?.name ?? `Subscribe ${subscribeId}`;
},
getSubscribeById: (subscribeId: number) => {
return get().subscribes.find((s) => s.id === subscribeId);
},
}));
export const useSubscribe = () => {
const store = useSubscribeStore();
// Auto-fetch subscribes
if (store.subscribes.length === 0 && !store.loading) {
store.fetchSubscribes();
}
return {
subscribes: store.subscribes,
loading: store.loading,
fetchSubscribes: store.fetchSubscribes,
getSubscribeName: store.getSubscribeName,
getSubscribeById: store.getSubscribeById,
};
};
export default useSubscribeStore;
+3
View File
@@ -11,6 +11,9 @@ NEXT_PUBLIC_HOME_USER_COUNT=999
NEXT_PUBLIC_HOME_SERVER_COUNT=999
NEXT_PUBLIC_HOME_LOCATION_COUNT=999
# Hidden Tutorial Document
NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT=false # true or false
# Contact Email
NEXT_PUBLIC_EMAIL=support@ppanel.dev
# Community Links
@@ -37,7 +37,7 @@ import { useTranslations } from 'next-intl';
import Image from 'next/image';
import Link from 'next/link';
import { QRCodeCanvas } from 'qrcode.react';
import { useState } from 'react';
import React, { useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { toast } from 'sonner';
import Subscribe from '../subscribe/page';
@@ -75,9 +75,39 @@ export default function Content() {
return data.data?.list || [];
},
});
const [platform, setPlatform] = useState<keyof API.DownloadLink>(
getPlatform() === 'macos' ? 'mac' : (getPlatform() as keyof API.DownloadLink),
);
const availablePlatforms = React.useMemo(() => {
if (!applications || applications.length === 0) return platforms;
const platformsSet = new Set<keyof API.DownloadLink>();
applications.forEach((app) => {
if (app.download_link) {
platforms.forEach((platform) => {
if (app.download_link?.[platform]) {
platformsSet.add(platform);
}
});
}
});
return platforms.filter((platform) => platformsSet.has(platform));
}, [applications]);
const [platform, setPlatform] = useState<keyof API.DownloadLink>(() => {
const detectedPlatform =
getPlatform() === 'macos' ? 'mac' : (getPlatform() as keyof API.DownloadLink);
return detectedPlatform;
});
React.useEffect(() => {
if (availablePlatforms.length > 0 && !availablePlatforms.includes(platform)) {
const firstAvailablePlatform = availablePlatforms[0];
if (firstAvailablePlatform) {
setPlatform(firstAvailablePlatform);
}
}
}, [availablePlatforms, platform]);
const { data } = useQuery({
queryKey: ['getStat'],
@@ -122,31 +152,33 @@ export default function Content() {
</div>
</div>
<div className='flex flex-wrap justify-between gap-4'>
<Tabs
value={platform}
onValueChange={(value) => setPlatform(value as keyof API.DownloadLink)}
className='w-full max-w-full md:w-auto'
>
<TabsList className='flex *:flex-auto'>
{platforms.map((item) => (
<TabsTrigger value={item} key={item} className='px-1 lg:px-3'>
<Icon
icon={`${
{
windows: 'mdi:microsoft-windows',
mac: 'uil:apple',
linux: 'uil:linux',
ios: 'simple-icons:ios',
android: 'uil:android',
harmony: 'simple-icons:harmonyos',
}[item]
}`}
className='size-5'
/>
</TabsTrigger>
))}
</TabsList>
</Tabs>
{availablePlatforms.length > 0 && (
<Tabs
value={platform}
onValueChange={(value) => setPlatform(value as keyof API.DownloadLink)}
className='w-full max-w-full md:w-auto'
>
<TabsList className='flex *:flex-auto'>
{availablePlatforms.map((item) => (
<TabsTrigger value={item} key={item} className='px-1 lg:px-3'>
<Icon
icon={`${
{
windows: 'mdi:microsoft-windows',
mac: 'uil:apple',
linux: 'uil:linux',
ios: 'simple-icons:ios',
android: 'uil:android',
harmony: 'simple-icons:harmonyos',
}[item]
}`}
className='size-5'
/>
</TabsTrigger>
))}
</TabsList>
</Tabs>
)}
{data?.protocol && data?.protocol.length > 1 && (
<Tabs
value={protocol}
@@ -325,9 +357,8 @@ export default function Content() {
<div className='grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6'>
{applications
?.filter((application) => {
if (!application.download_link && !application.scheme) return false;
return (
!!application.download_link?.[platform] || !!application.scheme
return !!(
application.download_link?.[platform] && application.scheme
);
})
.map((application) => {
@@ -1,5 +1,6 @@
'use client';
import { NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT } from '@/config/constants';
import { queryDocumentList } from '@/services/user/document';
import { getTutorialList } from '@/utils/tutorial';
import { useQuery } from '@tanstack/react-query';
@@ -31,6 +32,7 @@ export default function Page() {
const list = await getTutorialList();
return list.get(locale);
},
enabled: NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT !== 'true',
});
return (
+3
View File
@@ -53,3 +53,6 @@ export const NEXT_PUBLIC_HOME_LOCATION_COUNT = (() => {
if (isNaN(numberValue)) return 999;
return numberValue;
})();
export const NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT =
env('NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT') ?? process.env.NEXT_PUBLIC_HIDDEN_TUTORIAL_DOCUMENT;
+27 -4
View File
@@ -504,6 +504,7 @@ declare namespace API {
type Protocol = {
type: string;
port: number;
enable: boolean;
security?: string;
sni?: string;
allow_insecure?: boolean;
@@ -527,10 +528,6 @@ declare namespace API {
reduce_rtt?: boolean;
udp_relay_mode?: string;
congestion_controller?: string;
/** obfs, v2ray-plugin, simple-obfs */
plugin?: string;
/** plugin options, eg: obfs=http;obfs-host=www.bing.com */
plugin_options?: string;
/** mux, eg: off/low/medium/high */
multiplex?: string;
/** padding scheme */
@@ -539,6 +536,32 @@ declare namespace API {
up_mbps?: number;
/** download speed limit */
down_mbps?: number;
/** obfs, 'none', 'http', 'tls' */
obfs?: string;
/** obfs host */
obfs_host?: string;
/** obfs path */
obfs_path?: string;
/** xhttp mode */
xhttp_mode?: string;
/** xhttp extra path */
xhttp_extra?: string;
/** encryption'none', 'mlkem768x25519plus' */
encryption?: string;
/** encryption mode'native', 'xorpub', 'random' */
encryption_mode?: string;
/** encryption rtt'0rtt', '1rtt' */
encryption_rtt?: string;
/** encryption ticket */
encryption_ticket?: string;
/** encryption server padding */
encryption_server_padding?: string;
/** encryption private key */
encryption_private_key?: string;
/** encryption client padding */
encryption_client_padding?: string;
/** encryption password */
encryption_password?: string;
};
type PubilcRegisterConfig = {
+27 -4
View File
@@ -543,6 +543,7 @@ declare namespace API {
type Protocol = {
type: string;
port: number;
enable: boolean;
security?: string;
sni?: string;
allow_insecure?: boolean;
@@ -566,10 +567,6 @@ declare namespace API {
reduce_rtt?: boolean;
udp_relay_mode?: string;
congestion_controller?: string;
/** obfs, v2ray-plugin, simple-obfs */
plugin?: string;
/** plugin options, eg: obfs=http;obfs-host=www.bing.com */
plugin_options?: string;
/** mux, eg: off/low/medium/high */
multiplex?: string;
/** padding scheme */
@@ -578,6 +575,32 @@ declare namespace API {
up_mbps?: number;
/** download speed limit */
down_mbps?: number;
/** obfs, 'none', 'http', 'tls' */
obfs?: string;
/** obfs host */
obfs_host?: string;
/** obfs path */
obfs_path?: string;
/** xhttp mode */
xhttp_mode?: string;
/** xhttp extra path */
xhttp_extra?: string;
/** encryption'none', 'mlkem768x25519plus' */
encryption?: string;
/** encryption mode'native', 'xorpub', 'random' */
encryption_mode?: string;
/** encryption rtt'0rtt', '1rtt' */
encryption_rtt?: string;
/** encryption ticket */
encryption_ticket?: string;
/** encryption server padding */
encryption_server_padding?: string;
/** encryption private key */
encryption_private_key?: string;
/** encryption client padding */
encryption_client_padding?: string;
/** encryption password */
encryption_password?: string;
};
type PubilcRegisterConfig = {
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ppanel-web",
"version": "1.4.3",
"version": "1.4.5",
"private": true,
"homepage": "https://github.com/perfect-panel/ppanel-web",
"bugs": {
@@ -168,7 +168,12 @@ export function MonacoEditor({
/>
{!internalValue?.trim() && placeholder && (
<pre
className='text-muted-foreground pointer-events-none absolute left-7 top-4 text-sm'
className={cn(
'text-muted-foreground pointer-events-none absolute left-7 top-4 text-sm',
{
'left-16': showLineNumbers,
},
)}
style={{ userSelect: 'none' }}
>
{placeholder}