From 645c47f7d1d5b99f8e91a1afc038c80d1017b04b Mon Sep 17 00:00:00 2001 From: mr0x50 <24775431+mroxso@users.noreply.github.com> Date: Fri, 7 Feb 2025 22:24:29 +0100 Subject: [PATCH] add support for ALLOWED_KINDS environment variable to filter event types --- compose.yaml | 1 + main.go | 40 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/compose.yaml b/compose.yaml index c7a0d94..bbe50f2 100644 --- a/compose.yaml +++ b/compose.yaml @@ -12,6 +12,7 @@ services: POSTGRES_URL: "postgres://postgres:postgres@postgres/postgres?sslmode=disable" # RELAY_PUBKEY: optional, will use default if not set # RELAY_ICON: optional, will use default if not set + # ALLOWED_KINDS: "0,1,20" # optional, will allow all kinds if not set ports: - 3334:3334 postgres: diff --git a/main.go b/main.go index f1b3733..ffb19cf 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,18 @@ package main import ( + "context" "fmt" "net/http" "os" + "strconv" + "strings" "time" "github.com/fiatjaf/eventstore/postgresql" "github.com/fiatjaf/khatru" "github.com/fiatjaf/khatru/policies" + "github.com/nbd-wtf/go-nostr" ) func getEnv(key, fallback string) string { @@ -18,6 +22,23 @@ func getEnv(key, fallback string) string { return fallback } +func getAllowedKinds() []int { + allowedKindsStr := getEnv("ALLOWED_KINDS", "") + if allowedKindsStr == "" { + return nil // Allow all kinds + } + + kindStrs := strings.Split(allowedKindsStr, ",") + kinds := make([]int, 0, len(kindStrs)) + + for _, k := range kindStrs { + if kind, err := strconv.Atoi(strings.TrimSpace(k)); err == nil { + kinds = append(kinds, kind) + } + } + return kinds +} + func main() { // Print ASCII art banner fmt.Print(` @@ -47,7 +68,24 @@ func main() { panic(err) } - relay.StoreEvent = append(relay.StoreEvent, db.SaveEvent) + allowedKinds := getAllowedKinds() + + relay.StoreEvent = append(relay.StoreEvent, + func(ctx context.Context, evt *nostr.Event) error { + if allowedKinds == nil { + db.SaveEvent(ctx, evt) // Allow all kinds + return nil + } + + for _, kind := range allowedKinds { + if evt.Kind == kind { + db.SaveEvent(ctx, evt) + return nil + } + } + return fmt.Errorf("event kind %d is not allowed", evt.Kind) + }, + ) relay.QueryEvents = append(relay.QueryEvents, db.QueryEvents) relay.DeleteEvent = append(relay.DeleteEvent, db.DeleteEvent) relay.ReplaceEvent = append(relay.ReplaceEvent, db.ReplaceEvent)