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:
+71
-13
@@ -13,13 +13,22 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/apernet/OpenGFW/analyzer"
|
||||
"github.com/apernet/OpenGFW/analyzer/tcp"
|
||||
"github.com/apernet/OpenGFW/analyzer/udp"
|
||||
"github.com/apernet/OpenGFW/modifier"
|
||||
modUDP "github.com/apernet/OpenGFW/modifier/udp"
|
||||
"github.com/apernet/OpenGFW/ruleset"
|
||||
"github.com/apernet/OpenGFW/ruleset/builtins/geo"
|
||||
"github.com/apernet/OpenGFW/web"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -64,6 +73,7 @@ func main() {
|
||||
},
|
||||
}
|
||||
},
|
||||
Geo: geoData,
|
||||
Logf: log.Printf,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -161,8 +171,9 @@ func generate(ctx context.Context, hub *web.Hub) {
|
||||
}
|
||||
}
|
||||
|
||||
// memoryRules is an in-memory web.RuleManager: it validates the YAML shape but
|
||||
// does not compile expressions, which is enough for UI work.
|
||||
// memoryRules is an in-memory web.RuleManager. Rules are compiled with the real
|
||||
// ruleset compiler and the real analyzers, so expression errors show up here
|
||||
// exactly like they would in the engine; only the "apply" step is faked.
|
||||
type memoryRules struct {
|
||||
raw string
|
||||
rules []web.Rule
|
||||
@@ -209,21 +220,68 @@ func (m *memoryRules) Apply(raw string) ([]web.Rule, error) {
|
||||
return rules, nil
|
||||
}
|
||||
|
||||
var (
|
||||
analyzers = []analyzer.Analyzer{
|
||||
&tcp.FETAnalyzer{}, &tcp.HTTPAnalyzer{}, &tcp.SocksAnalyzer{}, &tcp.SSHAnalyzer{},
|
||||
&tcp.TLSAnalyzer{}, &tcp.TrojanAnalyzer{}, &udp.DNSAnalyzer{}, &udp.OpenVPNAnalyzer{},
|
||||
&udp.QUICAnalyzer{}, &udp.WireGuardAnalyzer{},
|
||||
}
|
||||
modifiers = []modifier.Modifier{&modUDP.DNSModifier{}}
|
||||
)
|
||||
|
||||
// parse compiles rules the same way the engine does.
|
||||
func parse(raw string) ([]web.Rule, error) {
|
||||
var rules []web.Rule
|
||||
if err := yaml.Unmarshal([]byte(raw), &rules); err != nil {
|
||||
exprRules, err := ruleset.ExprRulesFromYAMLBytes([]byte(raw))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse rules: %w", err)
|
||||
}
|
||||
_, err = ruleset.CompileExprRules(exprRules, analyzers, modifiers, &ruleset.BuiltinConfig{
|
||||
Logger: nopRulesetLogger{},
|
||||
GeoSiteFilename: os.Getenv("OPENGFW_GEOSITE"),
|
||||
GeoIpFilename: os.Getenv("OPENGFW_GEOIP"),
|
||||
ProtectedDialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, network, address)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i, r := range rules {
|
||||
if r.Name == "" {
|
||||
return nil, fmt.Errorf("rule #%d has no name", i+1)
|
||||
out := make([]web.Rule, 0, len(exprRules))
|
||||
for _, r := range exprRules {
|
||||
wr := web.Rule{Name: r.Name, Action: r.Action, Log: r.Log, Expr: r.Expr}
|
||||
if r.Modifier.Name != "" {
|
||||
wr.Modifier = &web.RuleModifier{Name: r.Modifier.Name, Args: r.Modifier.Args}
|
||||
}
|
||||
if r.Expr == "" {
|
||||
return nil, fmt.Errorf("rule %q has no expression", r.Name)
|
||||
}
|
||||
if r.Action == "" && !r.Log {
|
||||
return nil, fmt.Errorf("rule %q must have at least one of action or log", r.Name)
|
||||
out = append(out, wr)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type nopRulesetLogger struct{}
|
||||
|
||||
func (nopRulesetLogger) Log(ruleset.StreamInfo, string) {}
|
||||
func (nopRulesetLogger) MatchError(ruleset.StreamInfo, string, error) {}
|
||||
|
||||
// geoData lists the geo databases, if they are available in the working
|
||||
// directory (or wherever OPENGFW_GEOIP / OPENGFW_GEOSITE point).
|
||||
func geoData() web.GeoData {
|
||||
matcher := geo.NewGeoMatcher(os.Getenv("OPENGFW_GEOSITE"), os.Getenv("OPENGFW_GEOIP"))
|
||||
var data web.GeoData
|
||||
if entries, err := matcher.ListGeoIP(); err != nil {
|
||||
data.IPError = err.Error()
|
||||
} else {
|
||||
for _, e := range entries {
|
||||
data.IP = append(data.IP, web.GeoEntry{Code: e.Code, Count: e.CIDRs})
|
||||
}
|
||||
}
|
||||
return rules, nil
|
||||
if entries, err := matcher.ListGeoSite(); err != nil {
|
||||
data.SiteError = err.Error()
|
||||
} else {
|
||||
for _, e := range entries {
|
||||
data.Site = append(data.Site, web.GeoEntry{
|
||||
Code: e.Code, Count: e.Domains, Attributes: e.Attributes,
|
||||
})
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user