feat(web): visual rule builder with geo, CIDR and wildcard pickers

The rule editor no longer requires writing expr by hand. Conditions are rows of
field + operator + values joined with AND or OR, each row negatable, and the
generated expression is shown live and validated by the engine before a rule is
accepted. Raw expression and YAML editing are still available.

Fields cover the connection (protocol, source/destination IP and port), domains
(TLS SNI, QUIC SNI, DNS query name), HTTP (host, path, method, User-Agent) and
protocol detection. Operators cover CIDR membership, GeoIP countries, GeoSite
categories, port ranges, wildcards, substrings and regular expressions.
Multiple values in a row are OR-ed, so one row holds a whole domain or country
list.

Wildcards compile to the cheapest expression that matches them: *.x.com
becomes endsWith, x.* startsWith, *ad* contains, and only a star in the
middle falls back to a regular expression. Values are validated as they are
typed, including a hint when a star is used with an operator that would match
it literally.

Country and category pickers are backed by the databases the engine actually
loaded, via a new GET /api/v1/geo endpoint (cached, loaded on demand) built on
new listing methods in the geo package. Country names and flags come from
Intl.DisplayNames, so no name table is shipped. Note that the v2geo format has
no AS numbers; the provider groups it does contain (cloudflare, google,
telegram, ...) are listed alongside the countries.

Opening an existing rule parses its expression back into conditions. Anything
the builder cannot represent opens in the expression editor with a warning
rather than being rewritten. ruleset/expr_test.go pins the canonical
expressions the builder generates and compiles them with the real engine, and
the devserver now uses the real ruleset compiler so the same errors show up
during frontend work.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
mei
2026-07-27 08:48:56 +08:00
co-authored by Claude Opus 5
parent 5a7722d1d2
commit f7ad3aac95
52 changed files with 2191 additions and 216 deletions
+116 -17
View File
@@ -10,10 +10,12 @@ import {
RotateCcw,
Save,
Trash2,
Wand2,
} from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import PageHeader from '@/components/PageHeader.vue'
import RuleBuilder from '@/components/rule/RuleBuilder.vue'
import {
Badge,
Button,
@@ -32,6 +34,9 @@ import {
import { toast } from '@/composables/useToast'
import { t } from '@/i18n'
import { api, ApiError } from '@/lib/api'
import { compileRule } from '@/lib/rule/compile'
import { parseRule } from '@/lib/rule/parse'
import { emptyBuilderState, type RuleBuilderState } from '@/lib/rule/types'
import type { MetaInfo, Rule } from '@/lib/types'
const mode = ref('visual')
@@ -49,6 +54,14 @@ const editing = ref<Rule | null>(null)
const editingIndex = ref(-1)
const removing = ref<number>(-1)
// Rule editor state
const editorTab = ref('builder')
const builder = ref<RuleBuilderState>(emptyBuilderState())
const builderUnavailable = ref(false)
const checking = ref(false)
const analyzerNames = computed(() => (meta.value?.analyzers ?? []).map((a) => a.name))
const actionOptions = computed(() => [
{ value: '', label: t('rules.actionNone') },
...(meta.value?.actions ?? []).map((a) => ({ value: a, label: t(`action.${a}`) })),
@@ -175,46 +188,96 @@ function startAdd() {
editingIndex.value = -1
editing.value = { name: '', action: 'block', log: false, expr: '' }
modifierArgs.value = '{}'
builder.value = emptyBuilderState()
builderUnavailable.value = false
editorTab.value = 'builder'
editError.value = ''
}
function startEdit(index: number) {
const rule = rules.value[index]
editingIndex.value = index
editing.value = { ...rules.value[index] }
modifierArgs.value = JSON.stringify(rules.value[index].modifier?.args ?? {}, null, 2)
editing.value = { ...rule }
modifierArgs.value = JSON.stringify(rule.modifier?.args ?? {}, null, 2)
const parsed = parseRule(rule.expr)
builderUnavailable.value = parsed === null
builder.value = parsed ?? emptyBuilderState()
editorTab.value = parsed ? 'builder' : 'expr'
editError.value = ''
}
/**
* Switching tabs keeps both representations in sync: the builder is compiled
* into the expression, and an expression is parsed back when it uses the
* shapes the builder knows.
*/
function switchEditorTab(next: string) {
if (next === editorTab.value || !editing.value) return
if (next === 'expr') {
const expr = compileRule(builder.value)
if (expr) editing.value.expr = expr
} else {
const parsed = parseRule(editing.value.expr)
builderUnavailable.value = parsed === null
if (parsed) builder.value = parsed
}
editorTab.value = next
}
const modifierArgs = ref('{}')
const editError = ref('')
function commitEdit() {
const draftExpr = computed(() =>
editorTab.value === 'builder' ? compileRule(builder.value) : (editing.value?.expr ?? ''),
)
async function commitEdit() {
const draft = editing.value
if (!draft) return
if (!draft || checking.value) return
editError.value = ''
if (!draft.name.trim()) {
editError.value = t('rules.nameRequired')
return
}
if (!draft.expr.trim()) {
const expr = draftExpr.value.trim()
if (!expr) {
editError.value = t('rules.exprRequired')
return
}
draft.expr = expr
if (draft.action === 'modify') {
try {
const args = JSON.parse(modifierArgs.value || '{}') as Record<string, unknown>
draft.modifier = { name: draft.modifier?.name ?? modifierOptions.value[0]?.value ?? '', args }
} catch {
editError.value = 'JSON'
editError.value = t('rules.invalidJson')
return
}
} else {
draft.modifier = null
}
// Let the engine have the final word on the expression before accepting it.
checking.value = true
try {
const res = await api.validateRules({ rules: [{ ...draft, name: draft.name.trim() }] })
if (!res.valid) {
editError.value = res.error ?? t('rules.invalid')
return
}
} catch (e) {
editError.value = e instanceof ApiError ? e.message : String(e)
return
} finally {
checking.value = false
}
const next = [...rules.value]
if (editingIndex.value >= 0) next[editingIndex.value] = draft
else next.push(draft)
rules.value = next
dirty.value = true
editing.value = null
editError.value = ''
}
function remove(index: number) {
@@ -369,9 +432,11 @@ function remove(index: number) {
<Modal
:open="editing !== null"
:title="editingIndex >= 0 ? t('rules.editTitle') : t('rules.addTitle')"
class="sm:max-w-2xl"
@update:open="!$event && ((editing = null), (editError = ''))"
>
<form v-if="editing" class="flex flex-col gap-4" @submit.prevent="commitEdit">
<!-- Submission goes through the footer button: Enter belongs to the tag inputs. -->
<form v-if="editing" class="flex flex-col gap-4" @submit.prevent>
<div class="flex flex-col gap-2">
<Label for="rule-name">{{ t('rules.name') }}</Label>
<Input id="rule-name" v-model="editing.name" :placeholder="t('rules.namePlaceholder')" />
@@ -412,24 +477,58 @@ function remove(index: number) {
</div>
<div class="flex flex-col gap-2">
<Label for="rule-expr">{{ t('rules.expr') }}</Label>
<Textarea
id="rule-expr"
v-model="editing.expr"
spellcheck="false"
:placeholder="t('rules.exprPlaceholder')"
class="min-h-28 font-mono text-xs leading-relaxed"
<div class="flex flex-wrap items-center justify-between gap-2">
<Label>{{ t('rules.conditions') }}</Label>
<Tabs :model-value="editorTab" @update:model-value="switchEditorTab">
<TabsList class="h-8">
<TabsTrigger value="builder" class="text-xs">
<Wand2 />
{{ t('rules.builder.tab') }}
</TabsTrigger>
<TabsTrigger value="expr" class="text-xs">
<FileCode2 />
{{ t('rules.expr') }}
</TabsTrigger>
</TabsList>
</Tabs>
</div>
<p
v-if="builderUnavailable && editorTab === 'expr'"
class="border-drop/40 bg-drop/10 text-drop rounded-md border px-2.5 py-2 text-xs"
>
{{ t('rules.builder.notParsed') }}
</p>
<RuleBuilder
v-if="editorTab === 'builder'"
v-model="builder"
:analyzers="analyzerNames"
/>
<template v-else>
<Textarea
v-model="editing.expr"
spellcheck="false"
:placeholder="t('rules.exprPlaceholder')"
class="min-h-28 font-mono text-xs leading-relaxed"
/>
<p class="text-muted-foreground text-xs">{{ t('rules.exprHint') }}</p>
</template>
</div>
<p v-if="editError" class="text-destructive text-sm">{{ editError }}</p>
<p v-if="editError" class="text-destructive font-mono text-xs break-words">
{{ editError }}
</p>
</form>
<template #footer>
<Button variant="outline" @click="((editing = null), (editError = ''))">
{{ t('common.cancel') }}
</Button>
<Button @click="commitEdit">{{ t('common.save') }}</Button>
<Button :disabled="checking" @click="commitEdit">
<Loader2 v-if="checking" class="size-4 animate-spin" />
{{ t('common.save') }}
</Button>
</template>
</Modal>