Compare commits

...

7 Commits

Author SHA1 Message Date
Jon Staab e992b84f4f Add top-level livekit webhook
Docker / build-and-push-image (push) Successful in 3m3s
2026-06-16 09:43:56 -07:00
Jon Staab f9c752801f Create rooms with relay as metadata 2026-06-16 08:20:47 -07:00
Jon Staab a4cc9f53a8 If groups are disabled, treat h tagged events as regular events
Docker / build-and-push-image (push) Successful in 2m58s
2026-06-15 09:29:12 -07:00
Jon Staab 213ce1694d Prevent removing permanent admins from member list
Docker / build-and-push-image (push) Successful in 3m40s
2026-06-09 10:10:32 -07:00
Jon Staab 6a4dff3f51 Fix patch and tests
Docker / build-and-push-image (push) Successful in 2m58s
2026-06-01 16:54:29 -07:00
Jon Staab e9260f40f1 Clean up config file name stuff 2026-05-26 15:50:14 -07:00
Jon Staab 2fcc48abed Document blossom s3 options 2026-05-12 14:44:30 -07:00
17 changed files with 278 additions and 138 deletions
+1
View File
@@ -1 +1,2 @@
--ignore-dir=bin --ignore-dir=bin
--ignore-dir=.claude
+1
View File
@@ -1,3 +1,4 @@
bin bin
data data
media media
.claude
+1
View File
@@ -4,3 +4,4 @@ config
media media
data data
relay relay
.claude
+20 -3
View File
@@ -50,7 +50,7 @@ Zooid supports a few environment variables, which configure shared resources lik
- `MEDIA` - where to store blossom media files. Defaults to `./media`. - `MEDIA` - where to store blossom media files. Defaults to `./media`.
- `DATA` - where to store database files. Defaults to `./data`. - `DATA` - where to store database files. Defaults to `./data`.
- `API_HOST` - the hostname on which to expose the management API. If not set, the API is disabled. - `API_HOST` - the hostname on which to expose the management API. If not set, the API is disabled.
- `API_WHITELIST` - a comma-separated list of nostr hex pubkeys authorized to use the management API. Required when `API_HOST` is set. - `API_WHITELIST` - a comma-separated list of nostr hex pubkeys authorized to use the management API.
- `PPROF_ADDR` - an http host to serve pprof stats on. - `PPROF_ADDR` - an http host to serve pprof stats on.
## Configuration ## Configuration
@@ -96,6 +96,18 @@ Configures blossom support.
- `enabled` - whether blossom is enabled. - `enabled` - whether blossom is enabled.
- `authenticated_read` - whether users must perform NIP 98 AUTH in order to fetch a file. - `authenticated_read` - whether users must perform NIP 98 AUTH in order to fetch a file.
- `adapter` - where to store blobs. Either `local` (the default, stores files under `MEDIA`) or `s3` (stores files in an S3-compatible bucket).
#### `[blossom.s3]`
Configures S3-compatible object storage, used when `blossom.adapter` is `s3`.
- `endpoint` - the S3 endpoint URL. Optional; leave unset to use AWS S3.
- `region` - the bucket region. Required when `adapter` is `s3`.
- `bucket` - the bucket name. Required when `adapter` is `s3`.
- `access_key` - the access key ID. Required when `adapter` is `s3`.
- `secret_key` - the secret access key. Required when `adapter` is `s3`.
- `key_prefix` - an optional prefix prepended to every object key.
### `[push]` ### `[push]`
@@ -121,7 +133,12 @@ A special `[roles.member]` heading may be used to configure policies for all rel
- `api_key` - a key identifying this relay, assigned by the Livekit server. - `api_key` - a key identifying this relay, assigned by the Livekit server.
- `api_secret` - a secret key authenticating this relay, assigned by the Livekit server. - `api_secret` - a secret key authenticating this relay, assigned by the Livekit server.
On your LiveKit server you should also set up a webhook that points to `https://yourrelay.com/.well-known/nip29/livekit/webhook`. This allows LiveKit to notify your relay when people join rooms so it can publish a kind 39004 event. On your LiveKit server you should also set up a webhook so LiveKit can notify the relay when people join or leave rooms; the relay uses these notifications to publish a kind 39004 presence event. How you point the webhook depends on how many relays share a LiveKit project:
- **One relay, or a dedicated LiveKit project per relay** — point the webhook at that relay's own `https://yourrelay.com/.well-known/nip29/livekit/webhook`.
- **Several relays sharing one LiveKit project** — point the webhook at the management API's `https://api.relayplatform.com/.well-known/nip29/livekit/webhook` instead. zooid stamps each room's metadata with the owning relay's `schema` when it creates the room, so this shared endpoint routes every event to the relay that owns the room. This requires `API_HOST` to be set.
Either way the webhook is authenticated by LiveKit's own request signature (signed with the relay's `api_secret`) rather than NIP 98, so the shared endpoint is exempt from the `API_WHITELIST`. Configure LiveKit to sign webhooks with the same `api_key`/`api_secret` the relay uses, or the relay will reject them.
### Example ### Example
@@ -164,7 +181,7 @@ can_manage = true
## API ## API
When `API_HOST` and `API_WHITELIST` are configured, a JSON REST API is available for managing virtual relays remotely. All API requests must be authenticated using [NIP 98](https://github.com/nostr-protocol/nips/blob/master/98.md) HTTP AUTH. When `API_HOST` is configured, a JSON REST API is available for managing virtual relays remotely. All API requests must be authenticated using [NIP 98](https://github.com/nostr-protocol/nips/blob/master/98.md) HTTP AUTH signed by a pubkey listed in `API_WHITELIST`.
The API accepts JSON config objects and stores them as TOML files in the `CONFIG` directory. Configs are validated for required fields (`host`, `schema`, `secret`) and duplicate checking (`schema` and `host` must be unique across all relays). The API accepts JSON config objects and stores them as TOML files in the `CONFIG` directory. Configs are validated for required fields (`host`, `schema`, `secret`) and duplicate checking (`schema` and `host` must be unique across all relays).
+3 -2
View File
@@ -25,8 +25,9 @@ func main() {
os.Exit(1) os.Exit(1)
} }
// Load config for the specified relay name := zooid.ConfigNameFromId(*relay)
config, err := zooid.LoadConfigFromId(*relay) path := zooid.ConfigPathFromName(name)
config, err := zooid.LoadConfigFromPath(path)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
os.Exit(1) os.Exit(1)
+3 -2
View File
@@ -39,8 +39,9 @@ func main() {
os.Exit(1) os.Exit(1)
} }
// Load config for the specified relay name := zooid.ConfigNameFromId(*relay)
config, err := zooid.LoadConfigFromId(*relay) path := zooid.ConfigPathFromName(name)
config, err := zooid.LoadConfigFromPath(path)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
os.Exit(1) os.Exit(1)
+78 -28
View File
@@ -1,9 +1,12 @@
package zooid package zooid
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"net/http" "net/http"
"os" "os"
"sort" "sort"
@@ -35,6 +38,9 @@ func NewAPIHandler() *APIHandler {
mux.HandleFunc("DELETE /relay/{id}", api.auth(api.deleteRelay)) mux.HandleFunc("DELETE /relay/{id}", api.auth(api.deleteRelay))
mux.HandleFunc("GET /relay/{id}/members", api.auth(api.listRelayMembers)) mux.HandleFunc("GET /relay/{id}/members", api.auth(api.listRelayMembers))
// Skip auth, the handler checks the webhook signature itself
mux.HandleFunc("POST /.well-known/nip29/livekit/webhook", api.livekitWebhook)
api.mux = mux api.mux = mux
return api return api
@@ -72,7 +78,7 @@ func writeJSON(w http.ResponseWriter, status int, v any) {
// Relay CRUD // Relay CRUD
func (api *APIHandler) configFromRequest(r *http.Request) (*Config, error) { func (api *APIHandler) configFromRequest(path string, r *http.Request) (*Config, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024) r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close() defer r.Body.Close()
@@ -81,16 +87,7 @@ func (api *APIHandler) configFromRequest(r *http.Request) (*Config, error) {
return nil, fmt.Errorf("failed to read body: %w", err) return nil, fmt.Errorf("failed to read body: %w", err)
} }
var config Config return LoadConfigFromJson(path, body)
if err := json.Unmarshal(body, &config); err != nil {
return nil, fmt.Errorf("invalid json config: %w", err)
}
if err := config.Validate(); err != nil {
return nil, err
}
return &config, nil
} }
func (api *APIHandler) patchFromRequest(r *http.Request) (map[string]interface{}, error) { func (api *APIHandler) patchFromRequest(r *http.Request) (map[string]interface{}, error) {
@@ -121,7 +118,9 @@ func (api *APIHandler) checkDuplicateSchemaOrHost(config *Config, excludeFilenam
continue continue
} }
if existing, err := LoadConfigFromName(entry.Name()); err == nil { path := ConfigPathFromName(entry.Name())
if existing, err := LoadConfigFromPath(path); err == nil {
if existing.Schema == config.Schema { if existing.Schema == config.Schema {
return fmt.Errorf("schema %q is already in use", config.Schema) return fmt.Errorf("schema %q is already in use", config.Schema)
} }
@@ -137,13 +136,14 @@ func (api *APIHandler) checkDuplicateSchemaOrHost(config *Config, excludeFilenam
// Create relay // Create relay
func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) { func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
path := ConfigPathFromId(r.PathValue("id")) name := ConfigNameFromId(r.PathValue("id"))
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err == nil { if _, err := os.Stat(path); err == nil {
writeError(w, http.StatusConflict, "relay with this id already exists") writeError(w, http.StatusConflict, "relay with this id already exists")
return return
} }
config, err := api.configFromRequest(r) config, err := api.configFromRequest(path, r)
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, err.Error()) writeError(w, http.StatusBadRequest, err.Error())
return return
@@ -166,19 +166,20 @@ func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
func (api *APIHandler) putRelay(w http.ResponseWriter, r *http.Request) { func (api *APIHandler) putRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
path := ConfigPathFromId(id) name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusConflict, "relay not found") writeError(w, http.StatusNotFound, "relay not found")
return return
} }
config, err := api.configFromRequest(r) config, err := api.configFromRequest(path, r)
if err != nil { if err != nil {
writeError(w, http.StatusBadRequest, err.Error()) writeError(w, http.StatusBadRequest, err.Error())
return return
} }
if err := api.checkDuplicateSchemaOrHost(config, id+".toml"); err != nil { if err := api.checkDuplicateSchemaOrHost(config, name); err != nil {
writeError(w, http.StatusConflict, err.Error()) writeError(w, http.StatusConflict, err.Error())
return return
} }
@@ -195,9 +196,10 @@ func (api *APIHandler) putRelay(w http.ResponseWriter, r *http.Request) {
func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) { func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
path := ConfigPathFromId(id) name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusConflict, "relay not found") writeError(w, http.StatusNotFound, "relay not found")
return return
} }
@@ -223,7 +225,7 @@ func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
return return
} }
if err := api.checkDuplicateSchemaOrHost(config, id+".toml"); err != nil { if err := api.checkDuplicateSchemaOrHost(config, name); err != nil {
writeError(w, http.StatusConflict, err.Error()) writeError(w, http.StatusConflict, err.Error())
return return
} }
@@ -252,6 +254,10 @@ func (api *APIHandler) applyPatch(config *Config, patch map[string]interface{})
return err return err
} }
// Preserve unexported fields, which don't survive the JSON round-trip
patched.path = config.path
patched.secret = config.secret
// Copy patched values to original config // Copy patched values to original config
*config = patched *config = patched
return nil return nil
@@ -285,9 +291,10 @@ func deepMerge(base, patch map[string]interface{}) map[string]interface{} {
func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) { func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
path := ConfigPathFromId(id) name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusConflict, "relay not found") writeError(w, http.StatusNotFound, "relay not found")
return return
} }
@@ -303,9 +310,10 @@ func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request) { func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") id := r.PathValue("id")
members, err := api.resolveRelayMembers(id) name := ConfigNameFromId(id)
members, err := api.resolveRelayMembers(name)
if err != nil { if err != nil {
if os.IsNotExist(err) { if errors.Is(err, fs.ErrNotExist) {
writeError(w, http.StatusNotFound, "relay not found") writeError(w, http.StatusNotFound, "relay not found")
} else { } else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load relay members: %v", err)) writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load relay members: %v", err))
@@ -316,16 +324,17 @@ func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, map[string][]string{"members": members}) writeJSON(w, http.StatusOK, map[string][]string{"members": members})
} }
func (api *APIHandler) resolveRelayMembers(id string) ([]string, error) { func (api *APIHandler) resolveRelayMembers(name string) ([]string, error) {
instancesMux.RLock() instancesMux.RLock()
instance, exists := instancesByName[id+".toml"] instance, exists := instancesByName[name]
instancesMux.RUnlock() instancesMux.RUnlock()
if exists { if exists {
return collectMembers(instance.Management), nil return collectMembers(instance.Management), nil
} }
config, err := LoadConfigFromId(id) path := ConfigPathFromName(name)
config, err := LoadConfigFromPath(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -356,3 +365,44 @@ func collectMembers(management *ManagementStore) []string {
sort.Strings(members) sort.Strings(members)
return members return members
} }
// LiveKit webhook
// LiveKit webhooks are registered statically, so we add the relay's schema as metadata
// to the room and handle webhooks at the top level.
func (api *APIHandler) livekitWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1024*1024))
if err != nil {
writeError(w, http.StatusBadRequest, "failed to read body")
return
}
// Read the relay schema from the room metadata. This is parsed before
// verification, but the instance handler below re-checks the signature over
// the whole body (metadata included) with that relay's key, so a forged
// schema cannot pass.
var probe struct {
Room struct {
Metadata string `json:"metadata"`
} `json:"room"`
}
if err := json.Unmarshal(body, &probe); err != nil {
writeError(w, http.StatusBadRequest, "invalid webhook body")
return
}
schema := strings.TrimSpace(probe.Room.Metadata)
if schema == "" {
writeError(w, http.StatusBadRequest, "missing room metadata")
return
}
instance, ok := DispatchBySchema(schema)
if !ok {
writeError(w, http.StatusNotFound, "relay not found")
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
instance.livekitWebhookHandler(w, r)
}
+67 -36
View File
@@ -16,16 +16,14 @@ import (
) )
func TestAPIHandler_Authentication(t *testing.T) { func TestAPIHandler_Authentication(t *testing.T) {
// Create a temporary config directory useTestConfigDir(t)
configDir := t.TempDir()
// Create a test keypair for authentication // Create a test keypair for authentication
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
// Create API handler with whitelist containing our test pubkey // Create API handler with whitelist containing our test pubkey
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
t.Run("missing authorization header", func(t *testing.T) { t.Run("missing authorization header", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/relay/test", strings.NewReader("{}")) req := httptest.NewRequest(http.MethodPost, "/relay/test", strings.NewReader("{}"))
@@ -173,12 +171,11 @@ func TestAPIHandler_Authentication(t *testing.T) {
} }
func TestAPIHandler_CreateRelay(t *testing.T) { func TestAPIHandler_CreateRelay(t *testing.T) {
configDir := t.TempDir() configDir := useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
validConfig := map[string]interface{}{ validConfig := map[string]interface{}{
"host": "relay.example.com", "host": "relay.example.com",
@@ -226,6 +223,9 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
"host": "other.example.com", "host": "other.example.com",
"schema": "testrelay", // Same schema as existing "schema": "testrelay", // Same schema as existing
"secret": secretKey.Hex(), "secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
} }
body, _ := json.Marshal(config) body, _ := json.Marshal(config)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/other", secretKey, body) req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/other", secretKey, body)
@@ -243,6 +243,9 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
"host": "relay.example.com", // Same host as existing "host": "relay.example.com", // Same host as existing
"schema": "otherschema", "schema": "otherschema",
"secret": secretKey.Hex(), "secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
} }
body, _ := json.Marshal(config) body, _ := json.Marshal(config)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/other2", secretKey, body) req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/other2", secretKey, body)
@@ -301,12 +304,11 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
} }
func TestAPIHandler_UpdateRelay(t *testing.T) { func TestAPIHandler_UpdateRelay(t *testing.T) {
configDir := t.TempDir() useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
// Create initial relay // Create initial relay
initialConfig := map[string]interface{}{ initialConfig := map[string]interface{}{
@@ -371,6 +373,9 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
"host": "other.example.com", "host": "other.example.com",
"schema": "otherrelay", "schema": "otherrelay",
"secret": secretKey.Hex(), "secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
} }
body, _ := json.Marshal(otherConfig) body, _ := json.Marshal(otherConfig)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/otherrelay", secretKey, body) req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/otherrelay", secretKey, body)
@@ -385,6 +390,9 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
"host": "relay.example.com", "host": "relay.example.com",
"schema": "otherrelay", // Duplicate "schema": "otherrelay", // Duplicate
"secret": secretKey.Hex(), "secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
} }
body, _ = json.Marshal(updateConfig) body, _ = json.Marshal(updateConfig)
req = createAuthenticatedRequest(http.MethodPut, "http://api.example.com/relay/testrelay", secretKey, body) req = createAuthenticatedRequest(http.MethodPut, "http://api.example.com/relay/testrelay", secretKey, body)
@@ -399,12 +407,11 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
} }
func TestAPIHandler_PatchRelay(t *testing.T) { func TestAPIHandler_PatchRelay(t *testing.T) {
configDir := t.TempDir() useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
// Create initial relay with full config // Create initial relay with full config
initialConfig := map[string]interface{}{ initialConfig := map[string]interface{}{
@@ -494,6 +501,9 @@ func TestAPIHandler_PatchRelay(t *testing.T) {
"host": "other.example.com", "host": "other.example.com",
"schema": "anotherrelay", "schema": "anotherrelay",
"secret": secretKey.Hex(), "secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
} }
body, _ := json.Marshal(otherConfig) body, _ := json.Marshal(otherConfig)
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/anotherrelay", secretKey, body) req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/anotherrelay", secretKey, body)
@@ -550,12 +560,11 @@ func TestAPIHandler_PatchRelay(t *testing.T) {
} }
func TestAPIHandler_DeleteRelay(t *testing.T) { func TestAPIHandler_DeleteRelay(t *testing.T) {
configDir := t.TempDir() configDir := useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
// Create a relay to delete // Create a relay to delete
config := map[string]interface{}{ config := map[string]interface{}{
@@ -605,12 +614,11 @@ func TestAPIHandler_DeleteRelay(t *testing.T) {
} }
func TestAPIHandler_ListRelayMembers(t *testing.T) { func TestAPIHandler_ListRelayMembers(t *testing.T) {
configDir := t.TempDir() useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
t.Run("list members from loaded relay instance", func(t *testing.T) { t.Run("list members from loaded relay instance", func(t *testing.T) {
member1 := nostr.Generate().Public() member1 := nostr.Generate().Public()
@@ -681,11 +689,13 @@ func TestAPIHandler_ListRelayMembers(t *testing.T) {
config := &Config{ config := &Config{
Host: "members.example.com", Host: "members.example.com",
Schema: "members_" + RandomString(8), Schema: "members_" + strings.ToLower(RandomString(8)),
Secret: relaySecret.Hex(), Secret: relaySecret.Hex(),
} }
config.Info.Pubkey = nostr.Generate().Public().Hex()
config.path = ConfigPathFromName(ConfigNameFromId("fallback"))
if err := api.saveConfig(api.configPath("fallback"), config); err != nil { if err := config.Save(); err != nil {
t.Fatalf("failed to save config: %v", err) t.Fatalf("failed to save config: %v", err)
} }
@@ -779,12 +789,11 @@ func TestAPIHandler_ListRelayMembers(t *testing.T) {
} }
func TestAPIHandler_MethodNotAllowed(t *testing.T) { func TestAPIHandler_MethodNotAllowed(t *testing.T) {
configDir := t.TempDir() useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
t.Run("GET method not allowed", func(t *testing.T) { t.Run("GET method not allowed", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/test", secretKey, nil) req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/test", secretKey, nil)
@@ -799,12 +808,11 @@ func TestAPIHandler_MethodNotAllowed(t *testing.T) {
} }
func TestAPIHandler_InvalidPath(t *testing.T) { func TestAPIHandler_InvalidPath(t *testing.T) {
configDir := t.TempDir() useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
t.Run("invalid path returns not found", func(t *testing.T) { t.Run("invalid path returns not found", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/invalid/path", secretKey, []byte("{}")) req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/invalid/path", secretKey, []byte("{}"))
@@ -830,12 +838,11 @@ func TestAPIHandler_InvalidPath(t *testing.T) {
} }
func TestAPIHandler_ConfigValidation(t *testing.T) { func TestAPIHandler_ConfigValidation(t *testing.T) {
configDir := t.TempDir() configDir := useTestConfigDir(t)
secretKey := nostr.Generate() secretKey := nostr.Generate()
pubkey := secretKey.Public() pubkey := secretKey.Public()
whitelist := pubkey.Hex() api := newTestAPIHandler(t, pubkey.Hex())
api := NewAPIHandler(whitelist, configDir)
t.Run("invalid info.pubkey", func(t *testing.T) { t.Run("invalid info.pubkey", func(t *testing.T) {
config := map[string]interface{}{ config := map[string]interface{}{
@@ -976,9 +983,33 @@ func createAuthenticatedRequest(method, url string, secretKey nostr.SecretKey, b
return req return req
} }
// setTestEnv overrides a value in the package-level env map. Env memoizes
// os.Environ via sync.Once, so once the test binary has started, os.Setenv is
// ignored — mutating the cached map directly is the only way to change config
// for an individual test. Safe because tests in this package run sequentially.
func setTestEnv(key, value string) {
_ = Env("DATA") // ensure the env map has been initialized
env[key] = value
}
// useTestConfigDir points Env("CONFIG") at a fresh temp dir for this test.
func useTestConfigDir(t *testing.T) string {
t.Helper()
dir := t.TempDir()
setTestEnv("CONFIG", dir)
return dir
}
// newTestAPIHandler builds a handler whose whitelist contains the given pubkeys.
func newTestAPIHandler(t *testing.T, whitelist ...string) *APIHandler {
t.Helper()
setTestEnv("API_WHITELIST", strings.Join(whitelist, ","))
return NewAPIHandler()
}
func TestNewAPIHandler(t *testing.T) { func TestNewAPIHandler(t *testing.T) {
t.Run("empty whitelist", func(t *testing.T) { t.Run("empty whitelist", func(t *testing.T) {
api := NewAPIHandler("", "/tmp") api := newTestAPIHandler(t)
if len(api.whitelist) != 0 { if len(api.whitelist) != 0 {
t.Error("expected empty whitelist") t.Error("expected empty whitelist")
} }
@@ -986,7 +1017,7 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("single pubkey", func(t *testing.T) { t.Run("single pubkey", func(t *testing.T) {
pubkey := nostr.Generate().Public().Hex() pubkey := nostr.Generate().Public().Hex()
api := NewAPIHandler(pubkey, "/tmp") api := newTestAPIHandler(t, pubkey)
if len(api.whitelist) != 1 { if len(api.whitelist) != 1 {
t.Error("expected 1 entry in whitelist") t.Error("expected 1 entry in whitelist")
} }
@@ -998,8 +1029,8 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("multiple pubkeys", func(t *testing.T) { t.Run("multiple pubkeys", func(t *testing.T) {
pubkey1 := nostr.Generate().Public().Hex() pubkey1 := nostr.Generate().Public().Hex()
pubkey2 := nostr.Generate().Public().Hex() pubkey2 := nostr.Generate().Public().Hex()
whitelist := fmt.Sprintf("%s, %s", pubkey1, pubkey2) setTestEnv("API_WHITELIST", fmt.Sprintf("%s, %s", pubkey1, pubkey2))
api := NewAPIHandler(whitelist, "/tmp") api := NewAPIHandler()
if len(api.whitelist) != 2 { if len(api.whitelist) != 2 {
t.Error("expected 2 entries in whitelist") t.Error("expected 2 entries in whitelist")
} }
@@ -1010,8 +1041,8 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("whitespace trimming", func(t *testing.T) { t.Run("whitespace trimming", func(t *testing.T) {
pubkey := nostr.Generate().Public().Hex() pubkey := nostr.Generate().Public().Hex()
whitelist := " " + pubkey + " " setTestEnv("API_WHITELIST", " "+pubkey+" ")
api := NewAPIHandler(whitelist, "/tmp") api := NewAPIHandler()
if len(api.whitelist) != 1 { if len(api.whitelist) != 1 {
t.Error("expected 1 entry in whitelist after trimming") t.Error("expected 1 entry in whitelist after trimming")
} }
+1 -1
View File
@@ -3,8 +3,8 @@ package zooid
import ( import (
"bytes" "bytes"
"context" "context"
"io"
"fmt" "fmt"
"io"
"log" "log"
"net/url" "net/url"
"path/filepath" "path/filepath"
+20 -20
View File
@@ -1,12 +1,13 @@
package zooid package zooid
import ( import (
"encoding/json"
"fiatjaf.com/nostr" "fiatjaf.com/nostr"
"fmt" "fmt"
"regexp"
"github.com/BurntSushi/toml" "github.com/BurntSushi/toml"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
"slices" "slices"
) )
@@ -60,7 +61,7 @@ type Config struct {
Roles map[string]Role `toml:"roles" json:"roles"` Roles map[string]Role `toml:"roles" json:"roles"`
// Private/parsed values // Parsed values
path string path string
secret nostr.SecretKey secret nostr.SecretKey
} }
@@ -76,22 +77,14 @@ type BlossomS3Settings struct {
KeyPrefix string `toml:"key_prefix" json:"key_prefix"` KeyPrefix string `toml:"key_prefix" json:"key_prefix"`
} }
func ConfigPathFromId(id string) string { func ConfigNameFromId(id string) string {
return filepath.Join(Env("CONFIG"), id+".toml") return id + ".toml"
} }
func ConfigPathFromName(name string) string { func ConfigPathFromName(name string) string {
return filepath.Join(Env("CONFIG"), name) return filepath.Join(Env("CONFIG"), name)
} }
func LoadConfigFromId(id string) (*Config, error) {
return LoadConfigFromPath(ConfigPathFromId(id))
}
func LoadConfigFromName(name string) (*Config, error) {
return LoadConfigFromPath(ConfigPathFromName(name))
}
func LoadConfigFromPath(path string) (*Config, error) { func LoadConfigFromPath(path string) (*Config, error) {
var config Config var config Config
if _, err := toml.DecodeFile(path, &config); err != nil { if _, err := toml.DecodeFile(path, &config); err != nil {
@@ -107,6 +100,21 @@ func LoadConfigFromPath(path string) (*Config, error) {
return &config, nil return &config, nil
} }
func LoadConfigFromJson(path string, body []byte) (*Config, error) {
var config Config
if err := json.Unmarshal(body, &config); err != nil {
return nil, fmt.Errorf("invalid json config: %w", err)
}
config.path = path
if err := config.Validate(); err != nil {
return nil, err
}
return &config, nil
}
func (config *Config) Validate() error { func (config *Config) Validate() error {
if config.Blossom.Adapter == "" { if config.Blossom.Adapter == "" {
config.Blossom.Adapter = "local" config.Blossom.Adapter = "local"
@@ -130,8 +138,6 @@ func (config *Config) Validate() error {
return fmt.Errorf("invalid secret key: %w", err) return fmt.Errorf("invalid secret key: %w", err)
} }
// Make the secret... secret
config.Secret = ""
config.secret = secret config.secret = secret
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil { if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
@@ -159,9 +165,6 @@ func (config *Config) Validate() error {
} }
func (config *Config) Save() error { func (config *Config) Save() error {
// Restore the secret key to the public field for saving
config.Secret = config.secret.Hex()
file, err := os.Create(config.path) file, err := os.Create(config.path)
if err != nil { if err != nil {
return fmt.Errorf("Failed to open config file %s: %w", config.path, err) return fmt.Errorf("Failed to open config file %s: %w", config.path, err)
@@ -173,9 +176,6 @@ func (config *Config) Save() error {
return fmt.Errorf("Failed to encode config file %s: %w", config.path, err) return fmt.Errorf("Failed to encode config file %s: %w", config.path, err)
} }
// Clear the secret again
config.Secret = ""
return nil return nil
} }
+36 -25
View File
@@ -157,53 +157,64 @@ func TestConfig_MemberRole(t *testing.T) {
} }
} }
// validBlossomTestConfig returns a config that passes Validate except for any
// Blossom settings the caller overrides, so blossom validation can be exercised
// in isolation.
func validBlossomTestConfig() *Config {
sk := nostr.Generate()
c := &Config{
Host: "r.example.com",
Schema: "myrelay",
Secret: sk.Hex(),
}
c.Info.Pubkey = sk.Public().Hex()
return c
}
func TestValidateBlossomFileStorage(t *testing.T) { func TestValidateBlossomFileStorage(t *testing.T) {
t.Run("blossom disabled skips validation", func(t *testing.T) { t.Run("empty adapter defaults to local", func(t *testing.T) {
c := &Config{} c := validBlossomTestConfig()
c.Blossom.Enabled = false c.Blossom.Enabled = true
c.Blossom.Backend = "s3" if err := c.Validate(); err != nil {
normalizeBlossomConfig(c)
if err := validateBlossomFileStorage(c); err != nil {
t.Fatalf("expected nil, got %v", err) t.Fatalf("expected nil, got %v", err)
} }
if c.Blossom.Adapter != "local" {
t.Errorf("expected adapter normalized to local, got %q", c.Blossom.Adapter)
}
}) })
t.Run("local storage needs no s3 fields", func(t *testing.T) { t.Run("local storage needs no s3 fields", func(t *testing.T) {
c := &Config{} c := validBlossomTestConfig()
c.Blossom.Enabled = true c.Blossom.Enabled = true
c.Blossom.Backend = "local" c.Blossom.Adapter = "local"
normalizeBlossomConfig(c) if err := c.Validate(); err != nil {
if err := validateBlossomFileStorage(c); err != nil {
t.Fatalf("expected nil, got %v", err) t.Fatalf("expected nil, got %v", err)
} }
}) })
t.Run("s3 requires bucket region keys and secret", func(t *testing.T) { t.Run("s3 requires bucket region keys and secret", func(t *testing.T) {
c := &Config{} c := validBlossomTestConfig()
c.Blossom.Enabled = true c.Blossom.Enabled = true
c.Blossom.Backend = "s3" c.Blossom.Adapter = "s3"
c.Blossom.S3.Region = "us-east-1" c.Blossom.S3.Region = "us-east-1"
normalizeBlossomConfig(c) if err := c.Validate(); err == nil {
if err := validateBlossomFileStorage(c); err == nil {
t.Fatal("expected error for missing bucket and credentials") t.Fatal("expected error for missing bucket and credentials")
} }
c.Blossom.S3.Bucket = "b" c.Blossom.S3.Bucket = "b"
c.Blossom.S3.AccessKey = "k" c.Blossom.S3.AccessKey = "k"
c.Blossom.S3.SecretKey = "s" c.Blossom.S3.SecretKey = "s"
normalizeBlossomConfig(c) if err := c.Validate(); err != nil {
if err := validateBlossomFileStorage(c); err != nil {
t.Fatalf("expected nil with all s3 fields set, got %v", err) t.Fatalf("expected nil with all s3 fields set, got %v", err)
} }
}) })
t.Run("invalid backend value", func(t *testing.T) { t.Run("invalid adapter value", func(t *testing.T) {
c := &Config{} c := validBlossomTestConfig()
c.Blossom.Enabled = true c.Blossom.Enabled = true
c.Blossom.Backend = "nfs" c.Blossom.Adapter = "nfs"
normalizeBlossomConfig(c) if err := c.Validate(); err == nil {
if err := validateBlossomFileStorage(c); err == nil { t.Fatal("expected error for unknown adapter")
t.Fatal("expected error for unknown backend")
} }
}) })
} }
@@ -223,7 +234,7 @@ pubkey = "` + sk.Public().Hex() + `"
[blossom] [blossom]
enabled = true enabled = true
backend = "s3" adapter = "s3"
[blossom.s3] [blossom.s3]
region = "auto" region = "auto"
@@ -243,7 +254,7 @@ endpoint = "http://127.0.0.1:9000"
if cfg.Blossom.S3.SecretKey != "topsecret" { if cfg.Blossom.S3.SecretKey != "topsecret" {
t.Errorf("expected s3 secret_key retained in struct, got %q", cfg.Blossom.S3.SecretKey) t.Errorf("expected s3 secret_key retained in struct, got %q", cfg.Blossom.S3.SecretKey)
} }
if cfg.Blossom.Backend != "s3" { if cfg.Blossom.Adapter != "s3" {
t.Errorf("backend: got %q", cfg.Blossom.Backend) t.Errorf("adapter: got %q", cfg.Blossom.Adapter)
} }
} }
+4
View File
@@ -227,6 +227,10 @@ func (g *GroupStore) HasAccess(h string, pubkey nostr.PubKey) bool {
} }
func (g *GroupStore) IsGroupEvent(event nostr.Event) bool { func (g *GroupStore) IsGroupEvent(event nostr.Event) bool {
if !g.Config.Groups.Enabled {
return false
}
if slices.Contains(nip29.MetadataEventKinds, event.Kind) { if slices.Contains(nip29.MetadataEventKinds, event.Kind) {
return true return true
} }
+4 -3
View File
@@ -21,13 +21,14 @@ type Instance struct {
Push *PushManager Push *PushManager
} }
func MakeInstance(filename string) (*Instance, error) { func MakeInstance(name string) (*Instance, error) {
config, err := LoadConfigFromName(filename) path := ConfigPathFromName(name)
config, err := LoadConfigFromPath(path)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return makeInstance(config, filename) return makeInstance(config, name)
} }
func makeInstance(config *Config, source string) (*Instance, error) { func makeInstance(config *Config, source string) (*Instance, error) {
+13
View File
@@ -28,6 +28,19 @@ func Dispatch(hostname string) (*Instance, bool) {
return instance, exists return instance, exists
} }
func DispatchBySchema(schema string) (*Instance, bool) {
instancesMux.RLock()
defer instancesMux.RUnlock()
for _, instance := range instancesByName {
if instance.Config.Schema == schema && !instance.Config.Inactive {
return instance, true
}
}
return nil, false
}
func Start() { func Start() {
dataDir := Env("DATA") dataDir := Env("DATA")
if err := os.MkdirAll(dataDir, 0755); err != nil { if err := os.MkdirAll(dataDir, 0755); err != nil {
+4 -2
View File
@@ -50,7 +50,7 @@ func generateLivekitServerToken(apiKey, apiSecret string) string {
return jwt return jwt
} }
func ensureLivekitRoom(apiKey, apiSecret, serverURL, roomName string) error { func ensureLivekitRoom(apiKey, apiSecret, serverURL, roomName, metadata string) error {
roomKey := serverURL + "'" + roomName roomKey := serverURL + "'" + roomName
livekitRoomsMu.RLock() livekitRoomsMu.RLock()
@@ -63,8 +63,10 @@ func ensureLivekitRoom(apiKey, apiSecret, serverURL, roomName string) error {
httpURL := strings.Replace(strings.Replace(serverURL, "wss://", "https://", 1), "ws://", "http://", 1) httpURL := strings.Replace(strings.Replace(serverURL, "wss://", "https://", 1), "ws://", "http://", 1)
url := fmt.Sprintf("%s/twirp/livekit.RoomService/CreateRoom", httpURL) url := fmt.Sprintf("%s/twirp/livekit.RoomService/CreateRoom", httpURL)
// Use the relay's schema as room metadata so we can use the same livekit creds for multiple relay
reqBody, _ := json.Marshal(map[string]interface{}{ reqBody, _ := json.Marshal(map[string]interface{}{
"name": roomName, "name": roomName,
"metadata": metadata,
}) })
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody)) req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
@@ -214,7 +216,7 @@ func (instance *Instance) livekitTokenHandler(w http.ResponseWriter, r *http.Req
return return
} }
if err := ensureLivekitRoom(cfg.APIKey, cfg.APISecret, cfg.ServerURL, groupId); err != nil { if err := ensureLivekitRoom(cfg.APIKey, cfg.APISecret, cfg.ServerURL, groupId, instance.Config.Schema); err != nil {
http.Error(w, "failed to create room", http.StatusInternalServerError) http.Error(w, "failed to create room", http.StatusInternalServerError)
return return
} }
+10 -4
View File
@@ -1,7 +1,9 @@
package zooid package zooid
import ( import (
"slices"
"context" "context"
"errors"
"fiatjaf.com/nostr" "fiatjaf.com/nostr"
"fiatjaf.com/nostr/khatru" "fiatjaf.com/nostr/khatru"
"fiatjaf.com/nostr/nip86" "fiatjaf.com/nostr/nip86"
@@ -127,10 +129,6 @@ func (m *ManagementStore) PubkeyIsBanned(pubkey nostr.PubKey) bool {
// Admins // Admins
func (m *ManagementStore) IsAdmin(pubkey nostr.PubKey) bool {
return m.Config.IsOwner(pubkey) || m.Config.IsSelf(pubkey)
}
func (m *ManagementStore) GetAdmins() []nostr.PubKey { func (m *ManagementStore) GetAdmins() []nostr.PubKey {
members := make([]nostr.PubKey, 0) members := make([]nostr.PubKey, 0)
@@ -147,6 +145,10 @@ func (m *ManagementStore) GetAdmins() []nostr.PubKey {
return members return members
} }
func (m *ManagementStore) IsAdmin(pubkey nostr.PubKey) bool {
return slices.Contains(m.GetAdmins(), pubkey)
}
// Membership // Membership
func (m *ManagementStore) GetMembers() []nostr.PubKey { func (m *ManagementStore) GetMembers() []nostr.PubKey {
@@ -195,6 +197,10 @@ func (m *ManagementStore) AddMember(pubkey nostr.PubKey) error {
} }
func (m *ManagementStore) RemoveMember(pubkey nostr.PubKey) error { func (m *ManagementStore) RemoveMember(pubkey nostr.PubKey) error {
if m.IsAdmin(pubkey) {
return errors.New("Can't remove permanent admins from relay.")
}
membersEvent := m.Events.GetOrCreateRelayMembersList() membersEvent := m.Events.GetOrCreateRelayMembersList()
if membersEvent.Tags.FindWithValue("member", pubkey.Hex()) != nil { if membersEvent.Tags.FindWithValue("member", pubkey.Hex()) != nil {