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:
@@ -0,0 +1,113 @@
|
||||
import { FIELD_MAP, type FieldDef, type OperatorId } from './fields'
|
||||
import type { Condition, RuleBuilderState } from './types'
|
||||
|
||||
/** Quotes a value as an expr string literal. */
|
||||
export function quote(value: string): string {
|
||||
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
|
||||
}
|
||||
|
||||
const REGEX_SPECIALS = /[.+?^${}()|[\]\\]/g
|
||||
|
||||
/** Converts a `*.example.com` style pattern into an anchored regular expression. */
|
||||
export function wildcardToRegex(pattern: string): string {
|
||||
return `^${pattern.replace(REGEX_SPECIALS, '\\$&').replace(/\*/g, '.*')}$`
|
||||
}
|
||||
|
||||
export interface WildcardExplain {
|
||||
kind: 'exact' | 'suffix' | 'prefix' | 'contains' | 'regex' | 'any'
|
||||
/** The meaningful part of the pattern, e.g. ".example.com" for "*.example.com". */
|
||||
value: string
|
||||
}
|
||||
|
||||
/** Describes how a wildcard pattern will be matched, for the inline hint. */
|
||||
export function explainWildcard(pattern: string): WildcardExplain {
|
||||
const p = pattern.trim()
|
||||
if (p === '*') return { kind: 'any', value: '' }
|
||||
if (!p.includes('*')) return { kind: 'exact', value: p }
|
||||
const starts = p.startsWith('*')
|
||||
const ends = p.endsWith('*')
|
||||
const core = p.replace(/^\*/, '').replace(/\*$/, '')
|
||||
if (core.includes('*')) return { kind: 'regex', value: wildcardToRegex(p) }
|
||||
if (starts && ends) return { kind: 'contains', value: core }
|
||||
if (starts) return { kind: 'suffix', value: core }
|
||||
if (ends) return { kind: 'prefix', value: core }
|
||||
return { kind: 'regex', value: wildcardToRegex(p) }
|
||||
}
|
||||
|
||||
function wildcardTerm(subject: string, pattern: string): string {
|
||||
const info = explainWildcard(pattern)
|
||||
switch (info.kind) {
|
||||
case 'any':
|
||||
return `${subject} != ""`
|
||||
case 'exact':
|
||||
return `${subject} == ${quote(info.value)}`
|
||||
case 'suffix':
|
||||
return `${subject} endsWith ${quote(info.value)}`
|
||||
case 'prefix':
|
||||
return `${subject} startsWith ${quote(info.value)}`
|
||||
case 'contains':
|
||||
return `${subject} contains ${quote(info.value)}`
|
||||
case 'regex':
|
||||
return `${subject} matches ${quote(info.value)}`
|
||||
}
|
||||
}
|
||||
|
||||
/** Builds the expression for one value of a condition. */
|
||||
function term(field: FieldDef, op: OperatorId, subject: string, value: string): string {
|
||||
const v = value.trim()
|
||||
switch (op) {
|
||||
case 'is':
|
||||
return field.type === 'port' ? `${subject} == ${v}` : `${subject} == ${quote(v)}`
|
||||
case 'subdomain':
|
||||
return `(${subject} == ${quote(v)} || ${subject} endsWith ${quote('.' + v)})`
|
||||
case 'wildcard':
|
||||
return wildcardTerm(subject, v)
|
||||
case 'contains':
|
||||
case 'startsWith':
|
||||
case 'endsWith':
|
||||
return `${subject} ${op} ${quote(v)}`
|
||||
case 'regex':
|
||||
return `${subject} matches ${quote(v)}`
|
||||
case 'geosite':
|
||||
return `geosite(${subject}, ${quote(v.toLowerCase())})`
|
||||
case 'cidr':
|
||||
return `cidr(${subject}, ${quote(v)})`
|
||||
case 'geoip':
|
||||
return `geoip(${subject}, ${quote(v.toLowerCase())})`
|
||||
case 'detected':
|
||||
return `${v} != nil`
|
||||
case 'range':
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/** Compiles a single condition into an expression, or "" when incomplete. */
|
||||
export function compileCondition(condition: Condition): string {
|
||||
const field = FIELD_MAP[condition.field]
|
||||
if (!field) return ''
|
||||
const values = condition.values.map((v) => v.trim()).filter(Boolean)
|
||||
|
||||
let body: string
|
||||
if (condition.op === 'range') {
|
||||
const [from, to] = condition.values
|
||||
if (!from?.trim() || !to?.trim()) return ''
|
||||
body = `(${field.expr} >= ${from.trim()} && ${field.expr} <= ${to.trim()})`
|
||||
} else {
|
||||
if (values.length === 0) return ''
|
||||
const subject = field.iter ? (field.item as string) : (field.expr as string)
|
||||
const terms = values.map((v) => term(field, condition.op, subject, v))
|
||||
const joined = terms.length > 1 ? `(${terms.join(' || ')})` : terms[0]
|
||||
body = field.iter ? `any(${field.iter}, {${joined}})` : joined
|
||||
}
|
||||
|
||||
if (!condition.negate) return body
|
||||
return body.startsWith('(') && body.endsWith(')') ? `!${body}` : `!(${body})`
|
||||
}
|
||||
|
||||
/** Compiles the whole builder state into a rule expression. */
|
||||
export function compileRule(state: RuleBuilderState): string {
|
||||
const parts = state.conditions.map(compileCondition).filter(Boolean)
|
||||
if (parts.length === 0) return ''
|
||||
if (parts.length === 1) return parts[0]
|
||||
return parts.join(state.mode === 'and' ? ' && ' : ' || ')
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Catalog of the fields and operators the visual rule builder offers.
|
||||
*
|
||||
* Every field maps to a snippet of the expr expression language used by the
|
||||
* engine. Optional chaining (`a?.b`) keeps rules safe when an analyzer did not
|
||||
* produce any property for a stream, and `string(...)` turns a missing value
|
||||
* into an empty string instead of an error.
|
||||
*/
|
||||
|
||||
export type ValueType = 'proto' | 'ip' | 'port' | 'domain' | 'text' | 'analyzer'
|
||||
|
||||
export type OperatorId =
|
||||
| 'is'
|
||||
| 'subdomain'
|
||||
| 'wildcard'
|
||||
| 'contains'
|
||||
| 'startsWith'
|
||||
| 'endsWith'
|
||||
| 'regex'
|
||||
| 'geosite'
|
||||
| 'cidr'
|
||||
| 'geoip'
|
||||
| 'range'
|
||||
| 'detected'
|
||||
|
||||
export interface FieldDef {
|
||||
key: string
|
||||
/** Group used to organise the field picker. */
|
||||
group: 'basic' | 'domain' | 'http' | 'protocol'
|
||||
type: ValueType
|
||||
/** Expression evaluating to the value, already coerced to a string. */
|
||||
expr?: string
|
||||
/** Analyzer this field depends on, shown as a hint in the UI. */
|
||||
analyzer?: string
|
||||
/**
|
||||
* Set for fields that live in an array: `iter` is the list expression and
|
||||
* `item` the expression of a single element inside the predicate.
|
||||
*/
|
||||
iter?: string
|
||||
item?: string
|
||||
}
|
||||
|
||||
export const FIELDS: FieldDef[] = [
|
||||
{ key: 'proto', group: 'basic', type: 'proto', expr: 'proto' },
|
||||
{ key: 'ip.dst', group: 'basic', type: 'ip', expr: 'ip.dst' },
|
||||
{ key: 'ip.src', group: 'basic', type: 'ip', expr: 'ip.src' },
|
||||
{ key: 'port.dst', group: 'basic', type: 'port', expr: 'port.dst' },
|
||||
{ key: 'port.src', group: 'basic', type: 'port', expr: 'port.src' },
|
||||
|
||||
{ key: 'tls.sni', group: 'domain', type: 'domain', expr: 'string(tls?.req?.sni)', analyzer: 'tls' },
|
||||
{
|
||||
key: 'quic.sni',
|
||||
group: 'domain',
|
||||
type: 'domain',
|
||||
expr: 'string(quic?.req?.sni)',
|
||||
analyzer: 'quic',
|
||||
},
|
||||
{
|
||||
key: 'dns.name',
|
||||
group: 'domain',
|
||||
type: 'domain',
|
||||
analyzer: 'dns',
|
||||
iter: 'dns?.questions ?? []',
|
||||
item: 'string(.name)',
|
||||
},
|
||||
|
||||
{
|
||||
key: 'http.host',
|
||||
group: 'http',
|
||||
type: 'domain',
|
||||
expr: 'string(http?.req?.headers?.host)',
|
||||
analyzer: 'http',
|
||||
},
|
||||
{ key: 'http.path', group: 'http', type: 'text', expr: 'string(http?.req?.path)', analyzer: 'http' },
|
||||
{
|
||||
key: 'http.method',
|
||||
group: 'http',
|
||||
type: 'text',
|
||||
expr: 'string(http?.req?.method)',
|
||||
analyzer: 'http',
|
||||
},
|
||||
{
|
||||
key: 'http.ua',
|
||||
group: 'http',
|
||||
type: 'text',
|
||||
expr: 'string(get(http?.req?.headers, "user-agent"))',
|
||||
analyzer: 'http',
|
||||
},
|
||||
|
||||
{ key: 'analyzer', group: 'protocol', type: 'analyzer' },
|
||||
]
|
||||
|
||||
export const FIELD_MAP: Record<string, FieldDef> = Object.fromEntries(
|
||||
FIELDS.map((f) => [f.key, f]),
|
||||
)
|
||||
|
||||
/** Operators offered for each value type, in menu order. */
|
||||
export const OPERATORS: Record<ValueType, OperatorId[]> = {
|
||||
proto: ['is'],
|
||||
ip: ['cidr', 'geoip', 'is'],
|
||||
port: ['is', 'range'],
|
||||
domain: ['subdomain', 'wildcard', 'is', 'contains', 'endsWith', 'startsWith', 'regex', 'geosite'],
|
||||
text: ['contains', 'is', 'startsWith', 'endsWith', 'regex'],
|
||||
analyzer: ['detected'],
|
||||
}
|
||||
|
||||
/** Operators whose value is picked from a list rather than typed. */
|
||||
export const PICKER_OPERATORS: Partial<Record<OperatorId, 'geoip' | 'geosite'>> = {
|
||||
geoip: 'geoip',
|
||||
geosite: 'geosite',
|
||||
}
|
||||
|
||||
export const PROTO_VALUES = ['tcp', 'udp']
|
||||
|
||||
/** `range` takes exactly two values (from and to); everything else is a list. */
|
||||
export function isRangeOperator(op: OperatorId): boolean {
|
||||
return op === 'range'
|
||||
}
|
||||
|
||||
export function defaultOperator(type: ValueType): OperatorId {
|
||||
return OPERATORS[type][0]
|
||||
}
|
||||
|
||||
export function operatorsFor(field: FieldDef): OperatorId[] {
|
||||
return OPERATORS[field.type]
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
import { FIELDS, type FieldDef, type OperatorId } from './fields'
|
||||
import { newCondition } from './types'
|
||||
import type { Condition, RuleBuilderState } from './types'
|
||||
|
||||
/**
|
||||
* Best-effort conversion of an expression back into builder state.
|
||||
*
|
||||
* It understands the canonical shapes produced by compile.ts, which covers
|
||||
* every rule created through the builder. Hand written expressions that use
|
||||
* anything else simply return null, and the UI falls back to the expression
|
||||
* editor instead of silently rewriting them.
|
||||
*/
|
||||
export function parseRule(expr: string): RuleBuilderState | null {
|
||||
const source = expr.trim()
|
||||
if (!source) return null
|
||||
|
||||
let mode: 'and' | 'or' = 'and'
|
||||
let parts = splitTop(source, '&&')
|
||||
if (parts.length === 1) {
|
||||
const or = splitTop(source, '||')
|
||||
if (or.length > 1) {
|
||||
mode = 'or'
|
||||
parts = or
|
||||
}
|
||||
}
|
||||
|
||||
const conditions: Condition[] = []
|
||||
for (const part of parts) {
|
||||
const condition = parseCondition(part)
|
||||
if (!condition) return null
|
||||
conditions.push(condition)
|
||||
}
|
||||
return { mode, conditions }
|
||||
}
|
||||
|
||||
function parseCondition(input: string): Condition | null {
|
||||
let source = input.trim()
|
||||
let negate = false
|
||||
if (source.startsWith('!')) {
|
||||
negate = true
|
||||
source = source.slice(1).trim()
|
||||
}
|
||||
|
||||
// A single value, including the parenthesised "domain or subdomain" form.
|
||||
const single = parseTerm(source)
|
||||
if (single) {
|
||||
return newCondition({ field: single.field.key, op: single.op, negate, values: [single.value] })
|
||||
}
|
||||
|
||||
const body = unwrap(source)
|
||||
|
||||
// Array fields: any(<iter>, {<predicate>})
|
||||
const anyMatch = matchCall(body, 'any')
|
||||
if (anyMatch !== null) {
|
||||
const [iter, closure] = splitTop(anyMatch, ',').map((s) => s.trim())
|
||||
if (!closure?.startsWith('{') || !closure.endsWith('}')) return null
|
||||
const field = FIELDS.find((f) => f.iter === iter)
|
||||
if (!field) return null
|
||||
return finish(field, closure.slice(1, -1).trim(), negate, field.item as string)
|
||||
}
|
||||
|
||||
// Port range: (port.dst >= 1 && port.dst <= 2)
|
||||
const range = splitTop(body, '&&')
|
||||
if (range.length === 2) {
|
||||
const from = /^(\S+)\s*>=\s*(\d+)$/.exec(range[0].trim())
|
||||
const to = /^(\S+)\s*<=\s*(\d+)$/.exec(range[1].trim())
|
||||
if (from && to && from[1] === to[1]) {
|
||||
const field = FIELDS.find((f) => f.expr === from[1] && f.type === 'port')
|
||||
if (!field) return null
|
||||
return newCondition({ field: field.key, op: 'range', negate, values: [from[2], to[2]] })
|
||||
}
|
||||
return null
|
||||
}
|
||||
if (range.length > 1) return null
|
||||
|
||||
return finish(null, body, negate)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the values of a condition, which are OR-ed together and must all use
|
||||
* the same field and operator.
|
||||
*/
|
||||
function finish(
|
||||
expected: FieldDef | null,
|
||||
body: string,
|
||||
negate: boolean,
|
||||
subject?: string,
|
||||
): Condition | null {
|
||||
const single = parseTerm(body.trim(), subject)
|
||||
if (single && (!expected || single.field.key === expected.key)) {
|
||||
return newCondition({ field: single.field.key, op: single.op, negate, values: [single.value] })
|
||||
}
|
||||
|
||||
const parts = splitTop(unwrap(body), '||')
|
||||
if (parts.length < 2) return null
|
||||
|
||||
const terms: ParsedTerm[] = []
|
||||
let field = expected
|
||||
for (const part of parts) {
|
||||
const parsed = parseTerm(part.trim(), subject)
|
||||
if (!parsed) return null
|
||||
if (!field) field = parsed.field
|
||||
if (parsed.field.key !== field.key) return null
|
||||
terms.push(parsed)
|
||||
}
|
||||
if (!field) return null
|
||||
|
||||
const ops = new Set(terms.map((t) => t.op))
|
||||
if (ops.size === 1) {
|
||||
return newCondition({
|
||||
field: field.key,
|
||||
op: terms[0].op,
|
||||
negate,
|
||||
values: terms.map((t) => t.value),
|
||||
})
|
||||
}
|
||||
|
||||
// Values of a wildcard condition compile to different operators depending on
|
||||
// where the star sits, so fold mixed operators back into wildcard patterns.
|
||||
const patterns = terms.map((t) => toWildcard(t.op, t.value))
|
||||
if (patterns.some((p) => p === null)) return null
|
||||
return newCondition({ field: field.key, op: 'wildcard', negate, values: patterns as string[] })
|
||||
}
|
||||
|
||||
/** Inverse of the wildcard compilation, used when a condition mixes operators. */
|
||||
function toWildcard(op: OperatorId, value: string): string | null {
|
||||
switch (op) {
|
||||
case 'wildcard':
|
||||
return value
|
||||
case 'is':
|
||||
return value.includes('*') ? null : value
|
||||
case 'endsWith':
|
||||
return `*${value}`
|
||||
case 'startsWith':
|
||||
return `${value}*`
|
||||
case 'contains':
|
||||
return `*${value}*`
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
interface ParsedTerm {
|
||||
field: FieldDef
|
||||
subject: string
|
||||
op: OperatorId
|
||||
value: string
|
||||
}
|
||||
|
||||
const CALL_OPS: Record<string, OperatorId> = {
|
||||
geoip: 'geoip',
|
||||
geosite: 'geosite',
|
||||
cidr: 'cidr',
|
||||
}
|
||||
|
||||
const COMPARE_OPS: Record<string, OperatorId> = {
|
||||
'==': 'is',
|
||||
contains: 'contains',
|
||||
startsWith: 'startsWith',
|
||||
endsWith: 'endsWith',
|
||||
matches: 'regex',
|
||||
}
|
||||
|
||||
/** All expressions that can appear on the left hand side of a comparison. */
|
||||
function subjects(expected?: string): { subject: string; field: FieldDef }[] {
|
||||
const out: { subject: string; field: FieldDef }[] = []
|
||||
for (const field of FIELDS) {
|
||||
if (field.item) out.push({ subject: field.item, field })
|
||||
if (field.expr) out.push({ subject: field.expr, field })
|
||||
}
|
||||
// Longest match wins, but the subject already established for the condition
|
||||
// is always tried first so that ambiguous fields stay stable.
|
||||
return out.sort(
|
||||
(a, b) =>
|
||||
Number(b.subject === expected) - Number(a.subject === expected) ||
|
||||
b.subject.length - a.subject.length,
|
||||
)
|
||||
}
|
||||
|
||||
function parseTerm(input: string, expected?: string): ParsedTerm | null {
|
||||
const source = input.trim()
|
||||
|
||||
// Analyzer presence: `tls != nil`
|
||||
const detected = /^([a-z][\w]*)\s*!=\s*nil$/.exec(source)
|
||||
if (detected) {
|
||||
const field = FIELDS.find((f) => f.type === 'analyzer')
|
||||
if (field) return { field, subject: '', op: 'detected', value: detected[1] }
|
||||
}
|
||||
|
||||
// Domain-or-subdomain: (S == "v" || S endsWith ".v")
|
||||
if (source.startsWith('(') && isWrapped(source)) {
|
||||
const inner = splitTop(unwrap(source), '||')
|
||||
if (inner.length === 2) {
|
||||
const a = parseTerm(inner[0].trim(), expected)
|
||||
const b = parseTerm(inner[1].trim(), expected)
|
||||
if (
|
||||
a &&
|
||||
b &&
|
||||
a.op === 'is' &&
|
||||
b.op === 'endsWith' &&
|
||||
a.field.key === b.field.key &&
|
||||
b.value === `.${a.value}`
|
||||
) {
|
||||
return { ...a, op: 'subdomain' }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
for (const [name, op] of Object.entries(CALL_OPS)) {
|
||||
const args = matchCall(source, name)
|
||||
if (args === null) continue
|
||||
const parts = splitTop(args, ',').map((s) => s.trim())
|
||||
if (parts.length !== 2) return null
|
||||
const entry = subjects(expected).find((s) => s.subject === parts[0])
|
||||
const value = unquote(parts[1])
|
||||
if (!entry || value === null) return null
|
||||
return { field: entry.field, subject: entry.subject, op, value }
|
||||
}
|
||||
|
||||
for (const { subject, field } of subjects(expected)) {
|
||||
if (!source.startsWith(subject)) continue
|
||||
const rest = source.slice(subject.length).trim()
|
||||
// Wildcard "*" compiles to `S != ""`.
|
||||
if (rest === '!= ""') return { field, subject, op: 'wildcard', value: '*' }
|
||||
for (const [token, op] of Object.entries(COMPARE_OPS)) {
|
||||
if (!rest.startsWith(token)) continue
|
||||
const literal = rest.slice(token.length).trim()
|
||||
if (field.type === 'port' && /^\d+$/.test(literal) && op === 'is') {
|
||||
return { field, subject, op, value: literal }
|
||||
}
|
||||
const value = unquote(literal)
|
||||
if (value === null) continue
|
||||
return { field, subject, op, value }
|
||||
}
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Returns the arguments of `name(...)` when the input is exactly that call. */
|
||||
function matchCall(source: string, name: string): string | null {
|
||||
const prefix = `${name}(`
|
||||
if (!source.startsWith(prefix) || !source.endsWith(')')) return null
|
||||
const args = source.slice(prefix.length, -1)
|
||||
return balanced(args) ? args : null
|
||||
}
|
||||
|
||||
function unquote(literal: string): string | null {
|
||||
if (literal.length < 2 || literal[0] !== '"' || literal[literal.length - 1] !== '"') return null
|
||||
const body = literal.slice(1, -1)
|
||||
let out = ''
|
||||
for (let i = 0; i < body.length; i++) {
|
||||
if (body[i] === '\\' && i + 1 < body.length) {
|
||||
i++
|
||||
out += body[i]
|
||||
} else if (body[i] === '"') {
|
||||
return null
|
||||
} else {
|
||||
out += body[i]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** Splits on a top level operator, ignoring anything nested or quoted. */
|
||||
export function splitTop(source: string, operator: string): string[] {
|
||||
const parts: string[] = []
|
||||
let depth = 0
|
||||
let quoted = false
|
||||
let start = 0
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const ch = source[i]
|
||||
if (quoted) {
|
||||
if (ch === '\\') i++
|
||||
else if (ch === '"') quoted = false
|
||||
continue
|
||||
}
|
||||
if (ch === '"') quoted = true
|
||||
else if (ch === '(' || ch === '[' || ch === '{') depth++
|
||||
else if (ch === ')' || ch === ']' || ch === '}') depth--
|
||||
else if (depth === 0 && source.startsWith(operator, i)) {
|
||||
parts.push(source.slice(start, i))
|
||||
i += operator.length - 1
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
parts.push(source.slice(start))
|
||||
return parts.map((p) => p.trim()).filter((p) => p.length > 0)
|
||||
}
|
||||
|
||||
function balanced(source: string): boolean {
|
||||
let depth = 0
|
||||
let quoted = false
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const ch = source[i]
|
||||
if (quoted) {
|
||||
if (ch === '\\') i++
|
||||
else if (ch === '"') quoted = false
|
||||
continue
|
||||
}
|
||||
if (ch === '"') quoted = true
|
||||
else if (ch === '(' || ch === '[' || ch === '{') depth++
|
||||
else if (ch === ')' || ch === ']' || ch === '}') {
|
||||
depth--
|
||||
if (depth < 0) return false
|
||||
}
|
||||
}
|
||||
return depth === 0 && !quoted
|
||||
}
|
||||
|
||||
/** True when the whole string is wrapped in one pair of parentheses. */
|
||||
function isWrapped(source: string): boolean {
|
||||
if (!source.startsWith('(') || !source.endsWith(')')) return false
|
||||
return balanced(source.slice(1, -1))
|
||||
}
|
||||
|
||||
function unwrap(source: string): string {
|
||||
let out = source.trim()
|
||||
while (isWrapped(out)) out = out.slice(1, -1).trim()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { OperatorId } from './fields'
|
||||
|
||||
export type MatchMode = 'and' | 'or'
|
||||
|
||||
export interface Condition {
|
||||
id: string
|
||||
field: string
|
||||
op: OperatorId
|
||||
negate: boolean
|
||||
/** One entry per value; the `range` operator uses exactly two. */
|
||||
values: string[]
|
||||
}
|
||||
|
||||
export interface RuleBuilderState {
|
||||
mode: MatchMode
|
||||
conditions: Condition[]
|
||||
}
|
||||
|
||||
let counter = 0
|
||||
|
||||
export function newCondition(partial: Partial<Condition> = {}): Condition {
|
||||
counter += 1
|
||||
return {
|
||||
id: `c${counter}`,
|
||||
field: 'tls.sni',
|
||||
op: 'subdomain',
|
||||
negate: false,
|
||||
values: [],
|
||||
...partial,
|
||||
}
|
||||
}
|
||||
|
||||
export function emptyBuilderState(): RuleBuilderState {
|
||||
return { mode: 'and', conditions: [newCondition()] }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { t } from '@/i18n'
|
||||
|
||||
import type { OperatorId, ValueType } from './fields'
|
||||
|
||||
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/
|
||||
|
||||
export function isIPv4(value: string): boolean {
|
||||
const m = IPV4.exec(value)
|
||||
return m ? m.slice(1).every((part) => Number(part) <= 255 && String(Number(part)) === part) : false
|
||||
}
|
||||
|
||||
export function isIPv6(value: string): boolean {
|
||||
if (!value.includes(':')) return false
|
||||
// Reject obvious garbage; the engine does the authoritative parsing.
|
||||
if (!/^[0-9a-fA-F:.]+$/.test(value)) return false
|
||||
return (value.match(/::/g) ?? []).length <= 1 && value.split(':').length <= 9
|
||||
}
|
||||
|
||||
export function isIP(value: string): boolean {
|
||||
return isIPv4(value) || isIPv6(value)
|
||||
}
|
||||
|
||||
export function isCIDR(value: string): boolean {
|
||||
const slash = value.lastIndexOf('/')
|
||||
if (slash < 0) return false
|
||||
const ip = value.slice(0, slash)
|
||||
const bits = value.slice(slash + 1)
|
||||
if (!/^\d{1,3}$/.test(bits)) return false
|
||||
const prefix = Number(bits)
|
||||
if (isIPv4(ip)) return prefix <= 32
|
||||
if (isIPv6(ip)) return prefix <= 128
|
||||
return false
|
||||
}
|
||||
|
||||
export function isPort(value: string): boolean {
|
||||
return /^\d{1,5}$/.test(value) && Number(value) <= 65535
|
||||
}
|
||||
|
||||
/** Returns an error message for a value, or "" when it is acceptable. */
|
||||
export function validateValue(type: ValueType, op: OperatorId, value: string): string {
|
||||
const v = value.trim()
|
||||
if (!v) return ''
|
||||
switch (op) {
|
||||
case 'cidr':
|
||||
return isCIDR(v) ? '' : t('rules.invalidCidr')
|
||||
case 'regex':
|
||||
try {
|
||||
new RegExp(v)
|
||||
return ''
|
||||
} catch {
|
||||
return t('rules.invalidRegex')
|
||||
}
|
||||
case 'geoip':
|
||||
case 'geosite':
|
||||
return /^[a-z0-9-]+(@[a-z0-9-]+)*$/i.test(v) ? '' : t('rules.invalidGeo')
|
||||
case 'wildcard':
|
||||
return /^[a-z0-9.*_-]+$/i.test(v) ? '' : t('rules.invalidDomain')
|
||||
default:
|
||||
break
|
||||
}
|
||||
// A star only means something with the wildcard operator; anywhere else it
|
||||
// would be matched literally, which is never what the user meant.
|
||||
if ((type === 'domain' || type === 'text') && v.includes('*')) {
|
||||
return t('rules.starHint')
|
||||
}
|
||||
switch (type) {
|
||||
case 'ip':
|
||||
return isIP(v) ? '' : t('rules.invalidIp')
|
||||
case 'port':
|
||||
return isPort(v) ? '' : t('rules.invalidPort')
|
||||
case 'domain':
|
||||
return /^[a-z0-9.*_-]+$/i.test(v) ? '' : t('rules.invalidDomain')
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user