mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-01 06:36:38 +08:00
feat(frontend): create orchestrated waf rules
This commit is contained in:
@@ -127,11 +127,7 @@ export function WafSection({ route, onSavingChange }: WafSectionProps) {
|
||||
<span className="block text-sm font-semibold">{group.name}</span>
|
||||
<span className="mt-1 block text-xs text-muted-foreground">
|
||||
{group.enabled ? '启用中' : '已停用'} ·{' '}
|
||||
{group.ip_whitelist.length +
|
||||
group.ip_blacklist.length +
|
||||
group.country_whitelist.length +
|
||||
group.country_blacklist.length}{' '}
|
||||
条规则
|
||||
{group.graph.nodes.length} 个节点
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
@@ -145,4 +141,4 @@ export function WafSection({ route, onSavingChange }: WafSectionProps) {
|
||||
)}
|
||||
</SectionShell>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
'use client';
|
||||
|
||||
import {useEffect, useState} from 'react';
|
||||
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {Field, FieldGroup, FieldLabel} from '@/components/ui/field';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {Spinner} from '@/components/ui/spinner';
|
||||
|
||||
interface CreateRuleDialogProps {
|
||||
open: boolean;
|
||||
pending: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onCreate: (name: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function CreateRuleDialog({
|
||||
open,
|
||||
pending,
|
||||
onOpenChange,
|
||||
onCreate,
|
||||
}: CreateRuleDialogProps) {
|
||||
const [name, setName] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setName('');
|
||||
}, [open]);
|
||||
|
||||
const trimmedName = name.trim();
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent>
|
||||
<form
|
||||
className="flex flex-col gap-4"
|
||||
onSubmit={async (event) => {
|
||||
event.preventDefault();
|
||||
if (!trimmedName || pending) return;
|
||||
await onCreate(trimmedName);
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>新建 WAF 规则</DialogTitle>
|
||||
<DialogDescription>
|
||||
创建后将进入编排页面,通过处理单元配置规则执行流程。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="waf-rule-name">规则名称</FieldLabel>
|
||||
<Input
|
||||
id="waf-rule-name"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
placeholder="例如:入口防护"
|
||||
autoComplete="off"
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={pending}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="submit" disabled={!trimmedName || pending}>
|
||||
{pending ? <Spinner data-icon="inline-start" /> : null}
|
||||
创建并编排
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,375 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import {useEffect, useMemo, useState} from 'react';
|
||||
import {zodResolver} from '@hookform/resolvers/zod';
|
||||
import {Plus} from 'lucide-react';
|
||||
import {useForm} from 'react-hook-form';
|
||||
import {z} from 'zod';
|
||||
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage,} from '@/components/ui/form';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle,} from '@/components/ui/sheet';
|
||||
import {Switch} from '@/components/ui/switch';
|
||||
import {Tabs, TabsContent, TabsList, TabsTrigger} from '@/components/ui/tabs';
|
||||
import {Textarea} from '@/components/ui/textarea';
|
||||
import type {WAFIPGroup, WAFRuleGroup, WAFRuleGroupPayload} from '@/lib/services/openflare';
|
||||
|
||||
import {
|
||||
buildCountryOptions,
|
||||
buildRuleGroupDraft,
|
||||
countRuleEntries,
|
||||
emptyRuleGroupDraft,
|
||||
formatCountryItem,
|
||||
getListFieldKey,
|
||||
type ListFieldKey,
|
||||
normalizeItems,
|
||||
textToList,
|
||||
updateDraftList,
|
||||
} from './helpers';
|
||||
import {PowConfigPanel} from './pow-config-panel';
|
||||
import {RuleEntryDialog, type RuleEntryFormValues} from './rule-entry-dialog';
|
||||
import {RuleListSection} from './rule-list-section';
|
||||
|
||||
const ruleGroupSchema = z.object({
|
||||
name: z.string().trim().min(1, '请输入规则组名称').max(255, '名称不能超过 255 个字符'),
|
||||
enabled: z.boolean(),
|
||||
block_status_code: z.number().int().min(400).max(599),
|
||||
block_response_body: z.string(),
|
||||
pow_enabled: z.boolean(),
|
||||
});
|
||||
|
||||
type RuleGroupFormValues = z.infer<typeof ruleGroupSchema>;
|
||||
|
||||
interface RuleGroupSheetProps {
|
||||
open: boolean;
|
||||
group: WAFRuleGroup | null;
|
||||
ipGroups: WAFIPGroup[];
|
||||
submitting: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (payload: WAFRuleGroupPayload) => Promise<void>;
|
||||
}
|
||||
|
||||
export function RuleGroupSheet({
|
||||
open,
|
||||
group,
|
||||
ipGroups,
|
||||
submitting,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: RuleGroupSheetProps) {
|
||||
const [listsDraft, setListsDraft] = useState<WAFRuleGroupPayload>(emptyRuleGroupDraft);
|
||||
const [ruleEntryOpen, setRuleEntryOpen] = useState(false);
|
||||
|
||||
const countryOptions = useMemo(() => buildCountryOptions(), []);
|
||||
const countryLabelMap = useMemo(
|
||||
() => new Map(countryOptions.map((option) => [option.code, option.label])),
|
||||
[countryOptions],
|
||||
);
|
||||
|
||||
const form = useForm<RuleGroupFormValues>({
|
||||
resolver: zodResolver(ruleGroupSchema),
|
||||
defaultValues: {
|
||||
name: '',
|
||||
enabled: true,
|
||||
block_status_code: 418,
|
||||
block_response_body: '',
|
||||
pow_enabled: false,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const draft = buildRuleGroupDraft(group);
|
||||
setListsDraft(draft);
|
||||
form.reset({
|
||||
name: draft.name,
|
||||
enabled: draft.enabled,
|
||||
block_status_code: draft.block_status_code,
|
||||
block_response_body: draft.block_response_body,
|
||||
pow_enabled: draft.pow_enabled,
|
||||
});
|
||||
setRuleEntryOpen(false);
|
||||
}, [form, group, open]);
|
||||
|
||||
const ipGroupByID = new Map(ipGroups.map((item) => [item.id, item]));
|
||||
const whitelistGroupItems = listsDraft.ip_whitelist_group_ids
|
||||
.map((id) => ipGroupByID.get(id))
|
||||
.filter((item): item is WAFIPGroup => Boolean(item));
|
||||
const blacklistGroupItems = listsDraft.ip_blacklist_group_ids
|
||||
.map((id) => ipGroupByID.get(id))
|
||||
.filter((item): item is WAFIPGroup => Boolean(item));
|
||||
|
||||
const removeRuleItem = (key: ListFieldKey, value: string) => {
|
||||
setListsDraft((current) =>
|
||||
updateDraftList(current, key, (items) => items.filter((item) => item !== value)),
|
||||
);
|
||||
};
|
||||
|
||||
const removeRuleGroup = (key: ListFieldKey, id: number) => {
|
||||
setListsDraft((current) =>
|
||||
updateDraftList(current, key, (items) =>
|
||||
items.filter((item) => item !== String(id)),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const applyRuleEntry = (entry: RuleEntryFormValues) => {
|
||||
const values =
|
||||
entry.dimension === 'ip'
|
||||
? textToList(entry.ipValue)
|
||||
: entry.dimension === 'ip_group'
|
||||
? entry.ipGroupIDs.map(String)
|
||||
: normalizeItems(entry.countryValues);
|
||||
|
||||
const listKey = getListFieldKey(entry.listType, entry.dimension);
|
||||
setListsDraft((current) =>
|
||||
updateDraftList(current, listKey, (items) =>
|
||||
normalizeItems([...items, ...values]),
|
||||
),
|
||||
);
|
||||
setRuleEntryOpen(false);
|
||||
};
|
||||
|
||||
const handleSubmit = form.handleSubmit(async (values) => {
|
||||
const payload: WAFRuleGroupPayload = {
|
||||
...listsDraft,
|
||||
name: values.name,
|
||||
enabled: values.enabled,
|
||||
block_status_code: values.block_status_code,
|
||||
block_response_body: values.block_response_body,
|
||||
pow_enabled: values.pow_enabled,
|
||||
};
|
||||
try {
|
||||
await onSubmit(payload);
|
||||
onOpenChange(false);
|
||||
} catch (error) {
|
||||
form.setError('root', {
|
||||
message: error instanceof Error ? error.message : '保存失败',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const isGlobal = group?.is_global ?? false;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
<SheetContent side="right" className="flex h-svh w-full flex-col gap-0 p-0 sm:max-w-4xl">
|
||||
<SheetHeader className="border-b px-4 py-4">
|
||||
<SheetTitle>{group ? `编辑 ${group.name}` : '新建规则组'}</SheetTitle>
|
||||
<SheetDescription>
|
||||
白名单命中后直接放行;未命中白名单时继续判断黑名单。当前规则数{' '}
|
||||
{countRuleEntries(listsDraft)} 条。
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form
|
||||
id="rule-group-form"
|
||||
onSubmit={handleSubmit}
|
||||
className="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
<div className="flex-1 space-y-4 overflow-y-auto px-4 py-4">
|
||||
<Tabs defaultValue="basic">
|
||||
<TabsList className="grid w-full grid-cols-4">
|
||||
<TabsTrigger value="basic">基本信息</TabsTrigger>
|
||||
<TabsTrigger value="lists">黑白名单</TabsTrigger>
|
||||
<TabsTrigger value="pow">PoW</TabsTrigger>
|
||||
<TabsTrigger value="block">拦截返回</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="basic" className="mt-4 space-y-4">
|
||||
<div className="grid gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="enabled"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex items-center justify-between rounded-lg border border-dashed p-4">
|
||||
<div className="space-y-0.5">
|
||||
<FormLabel>启用规则组</FormLabel>
|
||||
<FormDescription>关闭后保留配置,但不会参与匹配。</FormDescription>
|
||||
</div>
|
||||
<FormControl>
|
||||
<Switch checked={field.value} onCheckedChange={field.onChange} />
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>规则组名称</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} disabled={isGlobal} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="lists" className="mt-4 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
通过弹窗添加 IP、IP 组或地域规则。
|
||||
</p>
|
||||
<Button type="button" size="sm" onClick={() => setRuleEntryOpen(true)}>
|
||||
<Plus className="mr-1 size-3.5" />
|
||||
添加规则
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-4 xl:grid-cols-2">
|
||||
<RuleListSection
|
||||
title="IP 白名单"
|
||||
description="命中后直接放行,不再继续判断黑名单。"
|
||||
items={listsDraft.ip_whitelist}
|
||||
groupItems={whitelistGroupItems}
|
||||
tone="whitelist"
|
||||
emptyText="暂无 IP 白名单规则。"
|
||||
onRemove={(item) => removeRuleItem('ip_whitelist', item)}
|
||||
onRemoveGroup={(id) => removeRuleGroup('ip_whitelist_group_ids', id)}
|
||||
/>
|
||||
<RuleListSection
|
||||
title="IP 黑名单"
|
||||
description="未命中白名单时,命中这些 IP / IP 段将被拦截。"
|
||||
items={listsDraft.ip_blacklist}
|
||||
groupItems={blacklistGroupItems}
|
||||
tone="blacklist"
|
||||
emptyText="暂无 IP 黑名单规则。"
|
||||
onRemove={(item) => removeRuleItem('ip_blacklist', item)}
|
||||
onRemoveGroup={(id) => removeRuleGroup('ip_blacklist_group_ids', id)}
|
||||
/>
|
||||
<RuleListSection
|
||||
title="地域白名单"
|
||||
description="显示格式为国家代码与中文名,命中后直接放行。"
|
||||
items={listsDraft.country_whitelist.map((code) =>
|
||||
formatCountryItem(code, countryLabelMap),
|
||||
)}
|
||||
tone="whitelist"
|
||||
emptyText="暂无地域白名单规则。"
|
||||
onRemove={(item) => {
|
||||
const code = item.split(' ')[0] ?? item;
|
||||
removeRuleItem('country_whitelist', code);
|
||||
}}
|
||||
/>
|
||||
<RuleListSection
|
||||
title="地域黑名单"
|
||||
description="当请求未命中白名单时,命中这些地域将被拦截。"
|
||||
items={listsDraft.country_blacklist.map((code) =>
|
||||
formatCountryItem(code, countryLabelMap),
|
||||
)}
|
||||
tone="blacklist"
|
||||
emptyText="暂无地域黑名单规则。"
|
||||
onRemove={(item) => {
|
||||
const code = item.split(' ')[0] ?? item;
|
||||
removeRuleItem('country_blacklist', code);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="pow" className="mt-4">
|
||||
<PowConfigPanel
|
||||
enabled={form.watch('pow_enabled')}
|
||||
config={listsDraft.pow_config}
|
||||
onChange={(enabled, config) => {
|
||||
form.setValue('pow_enabled', enabled);
|
||||
setListsDraft((current) => ({
|
||||
...current,
|
||||
pow_enabled: enabled,
|
||||
pow_config: config,
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="block" className="mt-4 space-y-4">
|
||||
<div className="grid gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="block_status_code"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>拦截状态码</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
min={400}
|
||||
max={599}
|
||||
value={field.value}
|
||||
onChange={(event) =>
|
||||
field.onChange(Number(event.target.value))
|
||||
}
|
||||
/>
|
||||
</FormControl>
|
||||
<div className="flex flex-wrap gap-2 pt-2">
|
||||
{[403, 418, 451, 503].map((code) => (
|
||||
<Button
|
||||
key={code}
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={field.value === code ? 'default' : 'outline'}
|
||||
onClick={() => field.onChange(code)}
|
||||
>
|
||||
{code}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="block_response_body"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>拦截页面</FormLabel>
|
||||
<FormControl>
|
||||
<Textarea
|
||||
className="min-h-48"
|
||||
placeholder="<html><body><h1>Request blocked</h1></body></html>"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormDescription>留空时只返回状态码。</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{form.formState.errors.root ? (
|
||||
<p className="text-sm text-destructive">{form.formState.errors.root.message}</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<SheetFooter className="flex-row justify-end border-t px-4 py-4">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="submit" disabled={submitting}>
|
||||
{submitting ? '保存中...' : '保存规则组'}
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
<RuleEntryDialog
|
||||
open={ruleEntryOpen}
|
||||
countryOptions={countryOptions}
|
||||
ipGroups={ipGroups}
|
||||
onOpenChange={setRuleEntryOpen}
|
||||
onSubmit={applyRuleEntry}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -7,21 +7,20 @@ import {Button} from '@/components/ui/button';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {Table, TableBody, TableCell, TableHead, TableHeader, TableRow,} from '@/components/ui/table';
|
||||
import type {WAFRuleGroup} from '@/lib/services/openflare';
|
||||
import type {WAFRule} from '@/lib/services/openflare';
|
||||
import {formatDateTime} from '@/lib/utils';
|
||||
|
||||
import {countRuleEntries} from './helpers';
|
||||
|
||||
interface RuleGroupsTableProps {
|
||||
groups: WAFRuleGroup[];
|
||||
onEdit: (group: WAFRuleGroup) => void;
|
||||
onDelete: (group: WAFRuleGroup) => void;
|
||||
onBindSites: (group: WAFRuleGroup) => void;
|
||||
groups: WAFRule[];
|
||||
onEdit: (group: WAFRule) => void;
|
||||
onDelete: (group: WAFRule) => void;
|
||||
onBindSites: (group: WAFRule) => void;
|
||||
}
|
||||
|
||||
export function RuleGroupsTable({
|
||||
@@ -37,7 +36,7 @@ export function RuleGroupsTable({
|
||||
<TableHead>名称</TableHead>
|
||||
<TableHead>类型</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>规则数</TableHead>
|
||||
<TableHead>节点数</TableHead>
|
||||
<TableHead>应用范围</TableHead>
|
||||
<TableHead>更新时间</TableHead>
|
||||
<TableHead className="w-[80px] text-right">操作</TableHead>
|
||||
@@ -64,7 +63,7 @@ export function RuleGroupsTable({
|
||||
{group.enabled ? '启用' : '停用'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{countRuleEntries(group)}</TableCell>
|
||||
<TableCell>{group.graph.nodes.length}</TableCell>
|
||||
<TableCell>
|
||||
{group.is_global
|
||||
? '全部网站'
|
||||
@@ -77,30 +76,34 @@ export function RuleGroupsTable({
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="size-8">
|
||||
<MoreHorizontal className="size-4" />
|
||||
<MoreHorizontal />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => onEdit(group)}>
|
||||
<Pencil className="size-4 mr-2" />
|
||||
编辑
|
||||
</DropdownMenuItem>
|
||||
{!group.is_global ? (
|
||||
<DropdownMenuItem onClick={() => onBindSites(group)}>
|
||||
<Users className="size-4 mr-2" />
|
||||
绑定网站
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={() => onEdit(group)}>
|
||||
<Pencil />
|
||||
编排
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{!group.is_global ? (
|
||||
<DropdownMenuItem onClick={() => onBindSites(group)}>
|
||||
<Users />
|
||||
绑定网站
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
</DropdownMenuGroup>
|
||||
{!group.is_global ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onClick={() => onDelete(group)}
|
||||
>
|
||||
<Trash2 className="size-4 mr-2" />
|
||||
删除
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => onDelete(group)}
|
||||
>
|
||||
<Trash2 />
|
||||
删除
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</DropdownMenuContent>
|
||||
|
||||
@@ -7,10 +7,10 @@ import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle,} from '@/components/ui/sheet';
|
||||
import {cn} from '@/lib/utils';
|
||||
import type {ProxyRouteItem, WAFRuleGroup} from '@/lib/services/openflare';
|
||||
import type {ProxyRouteItem, WAFRule} from '@/lib/services/openflare';
|
||||
|
||||
interface SiteBindingSheetProps {
|
||||
group: WAFRuleGroup | null;
|
||||
group: WAFRule | null;
|
||||
routes: ProxyRouteItem[];
|
||||
open: boolean;
|
||||
pending: boolean;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query';
|
||||
import {Loader2, Plus, RefreshCw, Shield} from 'lucide-react';
|
||||
import {useRouter} from 'next/navigation';
|
||||
import {useState} from 'react';
|
||||
import {toast} from 'sonner';
|
||||
|
||||
@@ -20,35 +21,29 @@ import {Card, CardContent, CardDescription, CardHeader, CardTitle,} from '@/comp
|
||||
import {EmptyStateWithBorder} from '@/components/layout/empty';
|
||||
import {ErrorInline} from '@/components/layout/error';
|
||||
import {LoadingStateWithBorder} from '@/components/layout/loading';
|
||||
import type {WAFRuleGroup, WAFRuleGroupPayload} from '@/lib/services/openflare';
|
||||
import type {WAFRule} from '@/lib/services/openflare';
|
||||
import {ProxyRouteService, WafService} from '@/lib/services/openflare';
|
||||
|
||||
import {CreateRuleDialog} from './components/create-rule-dialog';
|
||||
import {getErrorMessage} from './components/helpers';
|
||||
import {RuleGroupSheet} from './components/rule-group-sheet';
|
||||
import {RuleGroupsTable} from './components/rule-groups-table';
|
||||
import {SiteBindingSheet} from './components/site-binding-sheet';
|
||||
|
||||
const ruleGroupsQueryKey = ['openflare', 'waf', 'rule-groups'];
|
||||
const ipGroupsQueryKey = ['openflare', 'waf', 'ip-groups'];
|
||||
const routesQueryKey = ['openflare', 'proxy-routes'];
|
||||
|
||||
export default function WafPage() {
|
||||
const router = useRouter();
|
||||
const queryClient = useQueryClient();
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [editingGroup, setEditingGroup] = useState<WAFRuleGroup | null>(null);
|
||||
const [deleteTarget, setDeleteTarget] = useState<WAFRuleGroup | null>(null);
|
||||
const [bindingGroup, setBindingGroup] = useState<WAFRuleGroup | null>(null);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<WAFRule | null>(null);
|
||||
const [bindingGroup, setBindingGroup] = useState<WAFRule | null>(null);
|
||||
|
||||
const groupsQuery = useQuery({
|
||||
queryKey: ruleGroupsQueryKey,
|
||||
queryFn: () => WafService.listRuleGroups(),
|
||||
});
|
||||
|
||||
const ipGroupsQuery = useQuery({
|
||||
queryKey: ipGroupsQueryKey,
|
||||
queryFn: () => WafService.listIPGroups(),
|
||||
});
|
||||
|
||||
const routesQuery = useQuery({
|
||||
queryKey: routesQueryKey,
|
||||
queryFn: () => ProxyRouteService.list(),
|
||||
@@ -57,29 +52,16 @@ export default function WafPage() {
|
||||
const invalidate = async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ruleGroupsQueryKey }),
|
||||
queryClient.invalidateQueries({ queryKey: ipGroupsQueryKey }),
|
||||
queryClient.invalidateQueries({ queryKey: ['openflare', 'config-versions', 'diff'] }),
|
||||
]);
|
||||
};
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
group,
|
||||
payload,
|
||||
}: {
|
||||
group: WAFRuleGroup | null;
|
||||
payload: WAFRuleGroupPayload;
|
||||
}) => {
|
||||
if (group) {
|
||||
return WafService.updateRuleGroup(group.id, payload);
|
||||
}
|
||||
return WafService.createRuleGroup(payload);
|
||||
},
|
||||
onSuccess: async () => {
|
||||
toast.success(editingGroup ? '规则组已更新' : '规则组已创建');
|
||||
setEditingGroup(null);
|
||||
setEditorOpen(false);
|
||||
await invalidate();
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (name: string) => WafService.createRule({name}),
|
||||
onSuccess: (rule) => {
|
||||
toast.success('规则已创建');
|
||||
setCreateOpen(false);
|
||||
router.push(`/waf/rules/editor?id=${rule.id}`);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(getErrorMessage(error));
|
||||
@@ -115,32 +97,21 @@ export default function WafPage() {
|
||||
void queryClient.invalidateQueries({ queryKey: ruleGroupsQueryKey });
|
||||
};
|
||||
|
||||
const handleCreate = () => {
|
||||
setEditingGroup(null);
|
||||
setEditorOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (group: WAFRuleGroup) => {
|
||||
setEditingGroup(group);
|
||||
setEditorOpen(true);
|
||||
};
|
||||
|
||||
const groups = groupsQuery.data ?? [];
|
||||
const loading = groupsQuery.isLoading || ipGroupsQuery.isLoading || routesQuery.isLoading;
|
||||
const error =
|
||||
groupsQuery.error ?? ipGroupsQuery.error ?? routesQuery.error ?? null;
|
||||
const loading = groupsQuery.isLoading || routesQuery.isLoading;
|
||||
const error = groupsQuery.error ?? routesQuery.error ?? null;
|
||||
|
||||
return (
|
||||
<div className="py-6 px-1 space-y-6">
|
||||
<div className="w-full py-6 px-1 space-y-6">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="size-5 text-primary" />
|
||||
<h1 className="text-2xl font-semibold tracking-tight">WAF</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="secondary" size="sm" className="h-7 text-xs" onClick={handleCreate}>
|
||||
<Plus className="size-3.5 mr-1" />
|
||||
新建规则组
|
||||
<Button variant="secondary" size="sm" onClick={() => setCreateOpen(true)}>
|
||||
<Plus data-icon="inline-start" />
|
||||
新建规则
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -151,7 +122,7 @@ export default function WafPage() {
|
||||
<div>
|
||||
<CardTitle className="text-base font-semibold">规则组</CardTitle>
|
||||
<CardDescription>
|
||||
按规则组维护 WAF 与 PoW 防护规则,全局规则组始终应用到所有网站。
|
||||
使用可视化流程编排 WAF 防护规则;全局规则始终应用到所有网站。
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button
|
||||
@@ -189,7 +160,7 @@ export default function WafPage() {
|
||||
) : (
|
||||
<RuleGroupsTable
|
||||
groups={groups}
|
||||
onEdit={handleEdit}
|
||||
onEdit={(rule) => router.push(`/waf/rules/editor?id=${rule.id}`)}
|
||||
onDelete={setDeleteTarget}
|
||||
onBindSites={setBindingGroup}
|
||||
/>
|
||||
@@ -197,17 +168,12 @@ export default function WafPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<RuleGroupSheet
|
||||
open={editorOpen}
|
||||
group={editingGroup}
|
||||
ipGroups={ipGroupsQuery.data ?? []}
|
||||
submitting={saveMutation.isPending}
|
||||
onOpenChange={(open) => {
|
||||
setEditorOpen(open);
|
||||
if (!open) setEditingGroup(null);
|
||||
}}
|
||||
onSubmit={async (payload) => {
|
||||
await saveMutation.mutateAsync({ group: editingGroup, payload });
|
||||
<CreateRuleDialog
|
||||
open={createOpen}
|
||||
pending={createMutation.isPending}
|
||||
onOpenChange={setCreateOpen}
|
||||
onCreate={async (name) => {
|
||||
await createMutation.mutateAsync(name);
|
||||
}}
|
||||
/>
|
||||
|
||||
|
||||
@@ -211,6 +211,9 @@ export type {
|
||||
ApplyLogList,
|
||||
DashboardOverview,
|
||||
WAFIPGroup,
|
||||
WAFRule,
|
||||
WAFRuleGraph,
|
||||
WAFRuleNode,
|
||||
WAFRuleGroup,
|
||||
WAFSiteRuleGroups,
|
||||
TlsCertificateItem,
|
||||
|
||||
@@ -70,6 +70,12 @@ export type {
|
||||
WAFIPGroupSyncResult,
|
||||
WAFIPGroupSubscriptionFormat,
|
||||
WAFIPGroupType,
|
||||
WAFCreateRulePayload,
|
||||
WAFRule,
|
||||
WAFRuleEdge,
|
||||
WAFRuleGraph,
|
||||
WAFRuleNode,
|
||||
WAFSaveRuleGraphPayload,
|
||||
WAFRuleGroup,
|
||||
WAFRuleGroupPayload,
|
||||
WAFSiteRuleGroups,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type {XYPosition} from '@xyflow/react';
|
||||
|
||||
export type ReleaseChannel = 'stable' | 'preview';
|
||||
|
||||
export type NodeType = 'edge_node' | 'tunnel_relay' | 'tunnel_client';
|
||||
@@ -689,11 +691,65 @@ export interface OpenFlarePublicStatus {
|
||||
system_name: string;
|
||||
}
|
||||
|
||||
export interface WAFRuleGroup {
|
||||
export interface IPMatchConfig {
|
||||
ips: string[];
|
||||
cidrs: string[];
|
||||
ip_group_ids: number[];
|
||||
}
|
||||
|
||||
export interface GeoMatchConfig {
|
||||
countries: string[];
|
||||
regions: string[];
|
||||
}
|
||||
|
||||
export interface PoWNodeConfig {
|
||||
algorithm: 'fast' | 'slow';
|
||||
difficulty: number;
|
||||
session_ttl: number;
|
||||
challenge_ttl: number;
|
||||
}
|
||||
|
||||
export interface BlockNodeConfig {
|
||||
status_code: number;
|
||||
response_body: string;
|
||||
}
|
||||
|
||||
export type WAFRuleNode =
|
||||
| {id: string; type: 'start'; position: XYPosition; config: Record<string, never>}
|
||||
| {id: string; type: 'ip_match'; position: XYPosition; config: IPMatchConfig}
|
||||
| {id: string; type: 'geo_match'; position: XYPosition; config: GeoMatchConfig}
|
||||
| {id: string; type: 'pow'; position: XYPosition; config: PoWNodeConfig}
|
||||
| {id: string; type: 'allow'; position: XYPosition; config: Record<string, never>}
|
||||
| {id: string; type: 'block'; position: XYPosition; config: BlockNodeConfig};
|
||||
|
||||
export interface WAFRuleEdge {
|
||||
id: string;
|
||||
source: string;
|
||||
source_handle: string;
|
||||
target: string;
|
||||
}
|
||||
|
||||
export interface WAFRuleGraph {
|
||||
schema_version: number;
|
||||
nodes: WAFRuleNode[];
|
||||
edges: WAFRuleEdge[];
|
||||
}
|
||||
|
||||
export interface WAFRule {
|
||||
id: number;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
is_global: boolean;
|
||||
graph: WAFRuleGraph;
|
||||
revision: number;
|
||||
applied_site_ids: number[];
|
||||
applied_site_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** @deprecated Legacy fixed-chain rule shape retained for untouched binding consumers. */
|
||||
export interface WAFRuleGroup extends WAFRule {
|
||||
block_status_code: number;
|
||||
block_response_body: string;
|
||||
ip_whitelist: string[];
|
||||
@@ -706,10 +762,15 @@ export interface WAFRuleGroup {
|
||||
region_blacklist: string[];
|
||||
pow_enabled: boolean;
|
||||
pow_config: ProxyRoutePoWConfig;
|
||||
applied_site_ids: number[];
|
||||
applied_site_count: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface WAFCreateRulePayload {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface WAFSaveRuleGraphPayload {
|
||||
revision: number;
|
||||
graph: WAFRuleGraph;
|
||||
}
|
||||
|
||||
export interface WAFRuleGroupPayload {
|
||||
@@ -731,9 +792,9 @@ export interface WAFRuleGroupPayload {
|
||||
|
||||
export interface WAFSiteRuleGroups {
|
||||
route_id: number;
|
||||
global_rule_group: WAFRuleGroup | null;
|
||||
rule_groups: WAFRuleGroup[];
|
||||
applied_rule_groups: WAFRuleGroup[];
|
||||
global_rule_group: WAFRule | null;
|
||||
rule_groups: WAFRule[];
|
||||
applied_rule_groups: WAFRule[];
|
||||
applied_ids: number[];
|
||||
}
|
||||
|
||||
|
||||
@@ -5,39 +5,40 @@ import type {
|
||||
WAFIPGroupAutoTestResult,
|
||||
WAFIPGroupPayload,
|
||||
WAFIPGroupSyncResult,
|
||||
WAFRuleGroup,
|
||||
WAFRuleGroupPayload,
|
||||
WAFCreateRulePayload,
|
||||
WAFRule,
|
||||
WAFSaveRuleGraphPayload,
|
||||
WAFSiteRuleGroups,
|
||||
} from './types';
|
||||
|
||||
export class WafService extends OpenFlareBaseService {
|
||||
protected static override readonly basePath: string = '/api/v1/d/waf';
|
||||
|
||||
static async listRuleGroups(): Promise<WAFRuleGroup[]> {
|
||||
return this.get<WAFRuleGroup[]>('/rule-groups');
|
||||
static async listRuleGroups(): Promise<WAFRule[]> {
|
||||
return this.get<WAFRule[]>('/rule-groups');
|
||||
}
|
||||
|
||||
static async getRuleGroup(id: number): Promise<WAFRuleGroup> {
|
||||
return this.get<WAFRuleGroup>(`/rule-groups/${id}`);
|
||||
static async getRule(id: number): Promise<WAFRule> {
|
||||
return this.get<WAFRule>(`/rule-groups/${id}`);
|
||||
}
|
||||
|
||||
static async createRuleGroup(payload: WAFRuleGroupPayload): Promise<WAFRuleGroup> {
|
||||
return this.post<WAFRuleGroup>('/rule-groups', payload);
|
||||
static async createRule(payload: WAFCreateRulePayload): Promise<WAFRule> {
|
||||
return this.post<WAFRule>('/rule-groups', payload);
|
||||
}
|
||||
|
||||
static async updateRuleGroup(
|
||||
static async saveRuleGraph(
|
||||
id: number,
|
||||
payload: WAFRuleGroupPayload,
|
||||
): Promise<WAFRuleGroup> {
|
||||
return this.post<WAFRuleGroup>(`/rule-groups/${id}/update`, payload);
|
||||
payload: WAFSaveRuleGraphPayload,
|
||||
): Promise<WAFRule> {
|
||||
return this.post<WAFRule>(`/rule-groups/${id}/graph`, payload);
|
||||
}
|
||||
|
||||
static async deleteRuleGroup(id: number): Promise<void> {
|
||||
return this.post<void>(`/rule-groups/${id}/delete`);
|
||||
}
|
||||
|
||||
static async updateRuleGroupSites(id: number, ids: number[]): Promise<WAFRuleGroup> {
|
||||
return this.post<WAFRuleGroup>(`/rule-groups/${id}/sites`, { ids });
|
||||
static async updateRuleGroupSites(id: number, ids: number[]): Promise<WAFRule> {
|
||||
return this.post<WAFRule>(`/rule-groups/${id}/sites`, { ids });
|
||||
}
|
||||
|
||||
static async listSiteRuleGroups(routeId: number): Promise<WAFSiteRuleGroups> {
|
||||
@@ -82,4 +83,4 @@ export class WafService extends OpenFlareBaseService {
|
||||
static async syncIPGroup(id: number): Promise<WAFIPGroupSyncResult> {
|
||||
return this.post<WAFIPGroupSyncResult>(`/ip-groups/${id}/sync`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/react-virtual": "^3.13.16",
|
||||
"@uiw/react-codemirror": "^4.25.10",
|
||||
"@xyflow/react": "^12.11.2",
|
||||
"axios": "^1.15.0",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
Generated
+146
@@ -104,6 +104,9 @@ importers:
|
||||
'@uiw/react-codemirror':
|
||||
specifier: ^4.25.10
|
||||
version: 4.25.10(@babel/runtime@7.28.4)(@codemirror/autocomplete@6.20.3)(@codemirror/language@6.12.3)(@codemirror/lint@6.9.6)(@codemirror/search@6.7.0)(@codemirror/state@6.6.0)(@codemirror/theme-one-dark@6.1.3)(@codemirror/view@6.43.0)(codemirror@6.0.2)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
'@xyflow/react':
|
||||
specifier: ^12.11.2
|
||||
version: 12.11.2(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
axios:
|
||||
specifier: ^1.15.0
|
||||
version: 1.15.0
|
||||
@@ -1849,6 +1852,9 @@ packages:
|
||||
'@types/d3-color@3.1.3':
|
||||
resolution: {integrity: sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==}
|
||||
|
||||
'@types/d3-drag@3.0.7':
|
||||
resolution: {integrity: sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ==}
|
||||
|
||||
'@types/d3-ease@3.0.2':
|
||||
resolution: {integrity: sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==}
|
||||
|
||||
@@ -1861,6 +1867,9 @@ packages:
|
||||
'@types/d3-scale@4.0.9':
|
||||
resolution: {integrity: sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==}
|
||||
|
||||
'@types/d3-selection@3.0.11':
|
||||
resolution: {integrity: sha512-bhAXu23DJWsrI45xafYpkQ4NtcKMwWnAC/vKrd2l+nxMFuvOT3XMYTIj2opv8vq8AO5Yh7Qac/nSeP/3zjTK0w==}
|
||||
|
||||
'@types/d3-shape@3.1.7':
|
||||
resolution: {integrity: sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==}
|
||||
|
||||
@@ -1870,6 +1879,12 @@ packages:
|
||||
'@types/d3-timer@3.0.2':
|
||||
resolution: {integrity: sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==}
|
||||
|
||||
'@types/d3-transition@3.0.9':
|
||||
resolution: {integrity: sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg==}
|
||||
|
||||
'@types/d3-zoom@3.0.8':
|
||||
resolution: {integrity: sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw==}
|
||||
|
||||
'@types/debug@4.1.12':
|
||||
resolution: {integrity: sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==}
|
||||
|
||||
@@ -2143,6 +2158,22 @@ packages:
|
||||
'@vitest/utils@4.1.10':
|
||||
resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==}
|
||||
|
||||
'@xyflow/react@12.11.2':
|
||||
resolution: {integrity: sha512-eLAlDWJfWnQEhJwGMjlWdAXO9eYllKpliUmPQlAmOLxz6mExXuzMVDUKLMquixgkrtmMFFtug3jGKmYYld12cA==}
|
||||
peerDependencies:
|
||||
'@types/react': '>=17'
|
||||
'@types/react-dom': '>=17'
|
||||
react: '>=17'
|
||||
react-dom: '>=17'
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
'@types/react-dom':
|
||||
optional: true
|
||||
|
||||
'@xyflow/system@0.0.79':
|
||||
resolution: {integrity: sha512-czLyOh91NF0hIzbNzwi8I6GlqG23BHh2435OddfI6uiaLH3xdrdygO93gqgH1Bv9mhy8XPFQJOBn1FTq4LvEWA==}
|
||||
|
||||
acorn-jsx@5.3.2:
|
||||
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
|
||||
peerDependencies:
|
||||
@@ -2323,6 +2354,9 @@ packages:
|
||||
class-variance-authority@0.7.1:
|
||||
resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}
|
||||
|
||||
classcat@5.0.5:
|
||||
resolution: {integrity: sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w==}
|
||||
|
||||
client-only@0.0.1:
|
||||
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
|
||||
|
||||
@@ -2395,6 +2429,14 @@ packages:
|
||||
resolution: {integrity: sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
d3-dispatch@3.0.1:
|
||||
resolution: {integrity: sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
d3-drag@3.0.0:
|
||||
resolution: {integrity: sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
d3-ease@3.0.1:
|
||||
resolution: {integrity: sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -2415,6 +2457,10 @@ packages:
|
||||
resolution: {integrity: sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
d3-selection@3.0.0:
|
||||
resolution: {integrity: sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
d3-shape@3.2.0:
|
||||
resolution: {integrity: sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==}
|
||||
engines: {node: '>=12'}
|
||||
@@ -2431,6 +2477,16 @@ packages:
|
||||
resolution: {integrity: sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
d3-transition@3.0.1:
|
||||
resolution: {integrity: sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==}
|
||||
engines: {node: '>=12'}
|
||||
peerDependencies:
|
||||
d3-selection: 2 - 3
|
||||
|
||||
d3-zoom@3.0.0:
|
||||
resolution: {integrity: sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
damerau-levenshtein@1.0.8:
|
||||
resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}
|
||||
|
||||
@@ -4486,6 +4542,21 @@ packages:
|
||||
zrender@6.1.0:
|
||||
resolution: {integrity: sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==}
|
||||
|
||||
zustand@4.5.7:
|
||||
resolution: {integrity: sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==}
|
||||
engines: {node: '>=12.7.0'}
|
||||
peerDependencies:
|
||||
'@types/react': '>=16.8'
|
||||
immer: '>=9.0.6'
|
||||
react: '>=16.8'
|
||||
peerDependenciesMeta:
|
||||
'@types/react':
|
||||
optional: true
|
||||
immer:
|
||||
optional: true
|
||||
react:
|
||||
optional: true
|
||||
|
||||
zwitch@2.0.4:
|
||||
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
|
||||
|
||||
@@ -6002,6 +6073,10 @@ snapshots:
|
||||
|
||||
'@types/d3-color@3.1.3': {}
|
||||
|
||||
'@types/d3-drag@3.0.7':
|
||||
dependencies:
|
||||
'@types/d3-selection': 3.0.11
|
||||
|
||||
'@types/d3-ease@3.0.2': {}
|
||||
|
||||
'@types/d3-interpolate@3.0.4':
|
||||
@@ -6014,6 +6089,8 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/d3-time': 3.0.4
|
||||
|
||||
'@types/d3-selection@3.0.11': {}
|
||||
|
||||
'@types/d3-shape@3.1.7':
|
||||
dependencies:
|
||||
'@types/d3-path': 3.1.1
|
||||
@@ -6022,6 +6099,15 @@ snapshots:
|
||||
|
||||
'@types/d3-timer@3.0.2': {}
|
||||
|
||||
'@types/d3-transition@3.0.9':
|
||||
dependencies:
|
||||
'@types/d3-selection': 3.0.11
|
||||
|
||||
'@types/d3-zoom@3.0.8':
|
||||
dependencies:
|
||||
'@types/d3-interpolate': 3.0.4
|
||||
'@types/d3-selection': 3.0.11
|
||||
|
||||
'@types/debug@4.1.12':
|
||||
dependencies:
|
||||
'@types/ms': 2.1.0
|
||||
@@ -6296,6 +6382,31 @@ snapshots:
|
||||
convert-source-map: 2.0.0
|
||||
tinyrainbow: 3.1.0
|
||||
|
||||
'@xyflow/react@12.11.2(@types/react-dom@19.2.2(@types/react@19.2.2))(@types/react@19.2.2)(react-dom@19.2.3(react@19.2.3))(react@19.2.3)':
|
||||
dependencies:
|
||||
'@xyflow/system': 0.0.79
|
||||
classcat: 5.0.5
|
||||
react: 19.2.3
|
||||
react-dom: 19.2.3(react@19.2.3)
|
||||
zustand: 4.5.7(@types/react@19.2.2)(react@19.2.3)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.2
|
||||
'@types/react-dom': 19.2.2(@types/react@19.2.2)
|
||||
transitivePeerDependencies:
|
||||
- immer
|
||||
|
||||
'@xyflow/system@0.0.79':
|
||||
dependencies:
|
||||
'@types/d3-drag': 3.0.7
|
||||
'@types/d3-interpolate': 3.0.4
|
||||
'@types/d3-selection': 3.0.11
|
||||
'@types/d3-transition': 3.0.9
|
||||
'@types/d3-zoom': 3.0.8
|
||||
d3-drag: 3.0.0
|
||||
d3-interpolate: 3.0.1
|
||||
d3-selection: 3.0.0
|
||||
d3-zoom: 3.0.0
|
||||
|
||||
acorn-jsx@5.3.2(acorn@8.15.0):
|
||||
dependencies:
|
||||
acorn: 8.15.0
|
||||
@@ -6504,6 +6615,8 @@ snapshots:
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
|
||||
classcat@5.0.5: {}
|
||||
|
||||
client-only@0.0.1: {}
|
||||
|
||||
clsx@2.1.1: {}
|
||||
@@ -6579,6 +6692,13 @@ snapshots:
|
||||
|
||||
d3-color@3.1.0: {}
|
||||
|
||||
d3-dispatch@3.0.1: {}
|
||||
|
||||
d3-drag@3.0.0:
|
||||
dependencies:
|
||||
d3-dispatch: 3.0.1
|
||||
d3-selection: 3.0.0
|
||||
|
||||
d3-ease@3.0.1: {}
|
||||
|
||||
d3-format@3.1.0: {}
|
||||
@@ -6597,6 +6717,8 @@ snapshots:
|
||||
d3-time: 3.1.0
|
||||
d3-time-format: 4.1.0
|
||||
|
||||
d3-selection@3.0.0: {}
|
||||
|
||||
d3-shape@3.2.0:
|
||||
dependencies:
|
||||
d3-path: 3.1.0
|
||||
@@ -6611,6 +6733,23 @@ snapshots:
|
||||
|
||||
d3-timer@3.0.1: {}
|
||||
|
||||
d3-transition@3.0.1(d3-selection@3.0.0):
|
||||
dependencies:
|
||||
d3-color: 3.1.0
|
||||
d3-dispatch: 3.0.1
|
||||
d3-ease: 3.0.1
|
||||
d3-interpolate: 3.0.1
|
||||
d3-selection: 3.0.0
|
||||
d3-timer: 3.0.1
|
||||
|
||||
d3-zoom@3.0.0:
|
||||
dependencies:
|
||||
d3-dispatch: 3.0.1
|
||||
d3-drag: 3.0.0
|
||||
d3-interpolate: 3.0.1
|
||||
d3-selection: 3.0.0
|
||||
d3-transition: 3.0.1(d3-selection@3.0.0)
|
||||
|
||||
damerau-levenshtein@1.0.8: {}
|
||||
|
||||
data-urls@7.0.0:
|
||||
@@ -9213,4 +9352,11 @@ snapshots:
|
||||
dependencies:
|
||||
tslib: 2.3.0
|
||||
|
||||
zustand@4.5.7(@types/react@19.2.2)(react@19.2.3):
|
||||
dependencies:
|
||||
use-sync-external-store: 1.6.0(react@19.2.3)
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.2
|
||||
react: 19.2.3
|
||||
|
||||
zwitch@2.0.4: {}
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import {QueryClient, QueryClientProvider} from '@tanstack/react-query';
|
||||
import {fireEvent, render, screen, waitFor} from '@testing-library/react';
|
||||
import type {AxiosResponse} from 'axios';
|
||||
import {createElement} from 'react';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import WafPage from '@/app/(main)/waf/page';
|
||||
import apiClient from '@/lib/services/core/api-client';
|
||||
import {ProxyRouteService, WafService} from '@/lib/services/openflare';
|
||||
import type {WAFSiteRuleGroups} from '@/lib/services/openflare';
|
||||
import {WafService as DirectWafService} from '@/lib/services/openflare/waf.service';
|
||||
|
||||
const pushMock = vi.fn();
|
||||
|
||||
vi.mock('next/navigation', () => ({
|
||||
useRouter: () => ({push: pushMock}),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/services/core/api-client', () => ({
|
||||
default: {
|
||||
post: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/services/openflare', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/services/openflare')>();
|
||||
return {
|
||||
...actual,
|
||||
WafService: {
|
||||
...actual.WafService,
|
||||
listRuleGroups: vi.fn(),
|
||||
listIPGroups: vi.fn(),
|
||||
createRule: vi.fn(),
|
||||
deleteRuleGroup: vi.fn(),
|
||||
updateRuleGroupSites: vi.fn(),
|
||||
},
|
||||
ProxyRouteService: {
|
||||
...actual.ProxyRouteService,
|
||||
list: vi.fn(),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const graph = {
|
||||
schema_version: 1,
|
||||
nodes: [
|
||||
{id: 'start', type: 'start' as const, position: {x: 0, y: 0}, config: {}},
|
||||
{id: 'allow', type: 'allow' as const, position: {x: 200, y: 0}, config: {}},
|
||||
],
|
||||
edges: [{id: 'edge', source: 'start', source_handle: 'next', target: 'allow'}],
|
||||
};
|
||||
|
||||
const ruleSummary = {
|
||||
id: 17,
|
||||
name: '入口防护',
|
||||
enabled: false,
|
||||
is_global: false,
|
||||
graph,
|
||||
revision: 1,
|
||||
applied_site_ids: [],
|
||||
applied_site_count: 0,
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
};
|
||||
|
||||
// The binding API returns graph-backed rule summaries, not obsolete fixed-chain fields.
|
||||
const siteRuleGroupsFixture: WAFSiteRuleGroups = {
|
||||
route_id: 9,
|
||||
global_rule_group: null,
|
||||
rule_groups: [ruleSummary],
|
||||
applied_rule_groups: [ruleSummary],
|
||||
applied_ids: [17],
|
||||
};
|
||||
|
||||
describe('WafService rule graph API', () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(apiClient.post).mockReset();
|
||||
});
|
||||
|
||||
it('models site bindings with graph-backed rule summaries', () => {
|
||||
expect(siteRuleGroupsFixture.rule_groups[0]?.graph.nodes).toHaveLength(2);
|
||||
expect(siteRuleGroupsFixture.applied_ids).toEqual([17]);
|
||||
});
|
||||
|
||||
it('creates a rule with a name-only payload', async () => {
|
||||
vi.mocked(apiClient.post).mockResolvedValue({
|
||||
data: {error_msg: '', data: {id: 17, name: '入口防护', graph}},
|
||||
} as AxiosResponse);
|
||||
|
||||
await DirectWafService.createRule({name: '入口防护'});
|
||||
|
||||
expect(apiClient.post).toHaveBeenCalledWith(
|
||||
'/api/v1/d/waf/rule-groups',
|
||||
{name: '入口防护'},
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
it('saves the graph together with its current revision', async () => {
|
||||
vi.mocked(apiClient.post).mockResolvedValue({
|
||||
data: {error_msg: '', data: {id: 17, revision: 4, graph}},
|
||||
} as AxiosResponse);
|
||||
|
||||
await DirectWafService.saveRuleGraph(17, {revision: 3, graph});
|
||||
|
||||
expect(apiClient.post).toHaveBeenCalledWith(
|
||||
'/api/v1/d/waf/rule-groups/17/graph',
|
||||
{revision: 3, graph},
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WAF rule creation flow', () => {
|
||||
beforeEach(() => {
|
||||
pushMock.mockReset();
|
||||
vi.mocked(WafService.listRuleGroups).mockReset();
|
||||
vi.mocked(WafService.listRuleGroups).mockResolvedValue([]);
|
||||
vi.mocked(WafService.listIPGroups).mockReset();
|
||||
vi.mocked(WafService.listIPGroups).mockResolvedValue([]);
|
||||
vi.mocked(ProxyRouteService.list).mockReset();
|
||||
vi.mocked(ProxyRouteService.list).mockResolvedValue([]);
|
||||
vi.mocked(WafService.createRule).mockReset();
|
||||
vi.mocked(WafService.createRule).mockResolvedValue(ruleSummary);
|
||||
});
|
||||
|
||||
it('creates by name and navigates directly to the graph editor', async () => {
|
||||
const client = new QueryClient({
|
||||
defaultOptions: {queries: {retry: false, gcTime: 0}},
|
||||
});
|
||||
render(
|
||||
createElement(
|
||||
QueryClientProvider,
|
||||
{client},
|
||||
createElement(WafPage),
|
||||
),
|
||||
);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', {name: '新建规则'}));
|
||||
expect(screen.queryByText('IP 白名单')).not.toBeInTheDocument();
|
||||
fireEvent.change(screen.getByRole('textbox', {name: '规则名称'}), {
|
||||
target: {value: '入口防护'},
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', {name: '创建并编排'}));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(WafService.createRule).toHaveBeenCalledWith({name: '入口防护'});
|
||||
expect(pushMock).toHaveBeenCalledWith('/waf/rules/editor?id=17');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user