20 Commits

Author SHA1 Message Date
Jon Staab 6a4dff3f51 Fix patch and tests 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
Jon Staab ea145079f4 Clean up api and blossom 2026-05-12 14:08:56 -07:00
userAdityaa f40e909863 feat(blossom): optional S3-compatible blob storage 2026-05-12 14:08:56 -07:00
Jon Staab fd645c1e0a Move containers to gitea registry 2026-05-12 10:07:33 -07:00
Jon Staab 9e56d47fc0 Add blossom.authenticated_read config setting 2026-05-06 16:45:46 -07:00
Jon Staab 6ef94a76c8 Bump khatru to fix broadcast bug 2026-05-05 12:03:41 -07:00
Jon Staab f48d4a0d12 Spiff up the readme 2026-04-28 14:02:54 -07:00
Jon Staab 34c02b45b2 tweak readme 2026-04-25 06:00:31 -07:00
Jon Staab 9960a0fae8 Attempt to reduce memory requirements for docker build 2026-04-22 15:38:43 -07:00
Jon Staab 959d019b54 A little more refactoring 2026-04-22 14:46:43 -07:00
Jon Staab 53bf913fe6 Fix some bugs 2026-04-22 14:40:37 -07:00
Jon Staab b3c2ee7f87 Use serve mux for api handler 2026-04-22 14:07:54 -07:00
Jon Staab 081c4765ed Do a little cleanup on the api 2026-04-22 13:52:20 -07:00
userAdityaa aa0eba1fbe feat: add GET /relay/{id}/members endpoint (#6)
Co-authored-by: userAdityaa <aditya.chaudhary1558@gmail.com>
Co-committed-by: userAdityaa <aditya.chaudhary1558@gmail.com>
2026-04-22 20:45:28 +00:00
Jon Staab 6adb09a1d6 Modify gitignore 2026-04-15 12:51:29 -07:00
Jon Staab b067b8b2b6 Add pprof 2026-04-15 12:51:13 -07:00
Jon Staab dc8c16527b Update nostrlib 2026-04-14 08:38:25 -07:00
Jon Staab 64bde746f9 Include more information about 2026-04-14 08:05:49 -07:00
25 changed files with 1021 additions and 443 deletions
+5 -4
View File
@@ -5,8 +5,8 @@ on:
branches: [master]
env:
REGISTRY: ghcr.io
IMAGE_NAME: coracle-social/zooid
REGISTRY: gitea.coracle.social
IMAGE_NAME: coracle/zooid
jobs:
build-and-push-image:
@@ -23,8 +23,8 @@ jobs:
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
username: hodlbod
password: ${{ secrets.PACKAGE_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
@@ -48,3 +48,4 @@ jobs:
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+1
View File
@@ -3,3 +3,4 @@ refs
config
media
data
relay
+11 -2
View File
@@ -1,7 +1,13 @@
FROM golang AS build
FROM --platform=$BUILDPLATFORM golang:1.25 AS build
ARG TARGETOS TARGETARCH
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc-aarch64-linux-gnu libc6-dev-arm64-cross \
&& rm -rf /var/lib/apt/lists/*
COPY go.mod go.sum ./
RUN go mod download
@@ -9,7 +15,10 @@ RUN go mod download
COPY zooid zooid
COPY cmd cmd
RUN CGO_ENABLED=1 GOOS=linux go build -o bin/zooid cmd/relay/main.go
RUN set -eux; \
if [ "$TARGETARCH" = "arm64" ]; then export CC=aarch64-linux-gnu-gcc; fi; \
CGO_ENABLED=1 GOOS=$TARGETOS GOARCH=$TARGETARCH \
go build -o bin/zooid cmd/relay/main.go
FROM gcr.io/distroless/base-debian12 AS run
+58 -17
View File
@@ -1,6 +1,41 @@
# Zooid
<p align="center">
<img src="./zooid-wordmark.jpeg" alt="Zooid" width="280" />
</p>
This is a multi-tenant relay based on [Khatru](https://gitworkshop.dev/fiatjaf.com/nostrlib/tree/master/khatru) which implements a range of access controls. It's designed to be used with [Flotilla](https://flotilla.social) as a community relay (complete with NIP 29 support), but it can also be used outside of a community context.
<p align="center">
<b>A multi-tenant Nostr relay for communities.</b>
</p>
<p align="center">
<a href="#quick-start">Quick start</a> ·
<a href="#configuration">Configuration</a> ·
<a href="#api">API</a>
</p>
---
Zooid is a multi-tenant relay built on [Khatru](https://gitworkshop.dev/fiatjaf.com/nostrlib/tree/master/khatru) with a flexible set of access controls. It's designed to pair with [Flotilla](https://flotilla.social) as a community relay (with full NIP 29 support), but it works just fine outside of a community context too.
## Features
- **Multi-tenant** — run any number of virtual relays from a single instance, each with its own host, schema, and policy.
- **Community-ready** — first-class support for [NIP 29](https://github.com/nostr-protocol/nips/blob/master/29.md) groups, invite codes, and role-based access.
- **Batteries included** — optional [Blossom](https://github.com/hzrd149/blossom) media, [NIP 86](https://github.com/nostr-protocol/nips/blob/master/86.md) management, [NIP 9a](https://github.com/nostr-protocol/nips/pull/1079) push, and [LiveKit](https://livekit.io/) audio/video calls.
- **Remotely manageable** — JSON REST API authenticated via [NIP 98](https://github.com/nostr-protocol/nips/blob/master/98.md).
- **Operationally simple** — single binary, SQLite storage, OCI container, optional pprof.
## Quick start
```sh
docker run -it \
-p 3334:3334 \
-v ./config:/app/config \
-v ./media:/app/media \
-v ./data:/app/data \
gitea.coracle.social/coracle/zooid
```
Drop a TOML config file into `./config/` (see [Configuration](#configuration)) and the relay will be available at `ws://<host>:3334`.
## Architecture
@@ -13,15 +48,16 @@ Zooid supports a few environment variables, which configure shared resources lik
- `PORT` - the port the server will listen on for all requests. Defaults to `3334`.
- `CONFIG` - where to store relay configuration files. Defaults to `./config`.
- `MEDIA` - where to store blossom media files. Defaults to `./media`.
- `DATA` - where to store databse 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_WHITELIST` - a comma-separated list of nostr hex pubkeys authorized to use the management API. Required when `API_HOST` is set.
- `PPROF_ADDR` - an http host to serve pprof stats on.
## Configuration
Configuration files are written using [toml](https://toml.io). Top level configuration options are required:
- `host` - a hostname to serve this relay on.
- `host` - a hostname to serve this relay on. Must match the `Host` header sent by the client, including the port if the client connects on a non-standard port (e.g. `relay.example.com:8443`). When running behind a reverse proxy such as nginx, ensure the proxy forwards the original `Host` header unmodified; with nginx, use `proxy_set_header Host $http_host;` (the common `$host` variable drops the port).
- `schema` - a string that identifies this relay. This cannot be changed, and must be usable as a sqlite identifier.
- `secret` - the nostr secret key of the relay. Will be used to populate the relay's NIP 11 `self` field and sign generated events.
- `inactive` - a boolean indicating whether the relay is currently inactive. The relay will not be available if set.
@@ -59,6 +95,19 @@ Configures NIP 86 support.
Configures blossom support.
- `enabled` - whether blossom is enabled.
- `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]`
@@ -88,10 +137,10 @@ On your LiveKit server you should also set up a webhook that points to `https://
### Example
The below config file might be saved as `./config/my-relay.example.com` in order to route requests from `wss://my-relay.example.com` to this virtual relay.
The below config file might be saved as `./config/my-relay.example.com` in order to route requests from `wss://my-relay.example.com:3334` to this virtual relay.
```toml
host = "my-relay.example.com"
host = "my-relay.example.com:3334"
schema = "my_relay"
secret = "<hex private key>"
@@ -137,6 +186,7 @@ Endpoints:
- `PUT /relay/{id}` - Updates an existing virtual relay config. Returns 200 on success, 404 if the id doesn't exist, 409 if the new schema/host conflicts with another relay.
- `PATCH /relay/{id}` - Partially updates an existing virtual relay config by recursively merging the provided JSON. Returns 200 on success, 404 if the id doesn't exist, 409 if the new schema/host conflicts, 400 for invalid config. Use `null` values to remove fields.
- `DELETE /relay/{id}` - Deletes a virtual relay config. Returns 200 on success, 404 if the id doesn't exist.
- `GET /relay/{id}/members` - Returns relay members as JSON (`{"members": ["<pubkey>", ...]}`). Returns 200 on success, 404 if the relay id does not exist.
## Scripts
@@ -149,15 +199,6 @@ After running `just build`, a number of scripts will be available:
See `justfile` for defined commands.
## Deploying
## License
Zooid can be run using an OCI container:
```sh
podman run -it \
-p 3334:3334 \
-v ./config:/app/config \
-v ./media:/app/media \
-v ./data:/app/data \
ghcr.io/coracle-social/zooid
```
[MIT](./LICENSE)
+4 -4
View File
@@ -25,11 +25,11 @@ func main() {
os.Exit(1)
}
// Load config for the specified relay
filename := fmt.Sprintf("%s.toml", *relay)
config, err := zooid.LoadConfig(filename)
name := zooid.ConfigNameFromId(*relay)
path := zooid.ConfigPathFromName(name)
config, err := zooid.LoadConfigFromPath(path)
if err != nil {
fmt.Fprintln(os.Stderr, "No such config file", filename)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
+4 -4
View File
@@ -39,11 +39,11 @@ func main() {
os.Exit(1)
}
// Load config for the specified relay
filename := fmt.Sprintf("%s.toml", *relay)
config, err := zooid.LoadConfig(filename)
name := zooid.ConfigNameFromId(*relay)
path := zooid.ConfigPathFromName(name)
config, err := zooid.LoadConfigFromPath(path)
if err != nil {
fmt.Fprintln(os.Stderr, "No such config file", filename)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
+15 -4
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
@@ -20,8 +21,18 @@ func main() {
port := zooid.Env("PORT")
apiHost := zooid.Env("API_HOST")
apiWhitelist := zooid.Env("API_WHITELIST")
configDir := zooid.Env("CONFIG")
pprofAddr := zooid.Env("PPROF_ADDR")
// pprof server — only starts when PPROF_ADDR is set. Bind to
// 127.0.0.1:6060 (or similar) and tunnel via SSH; never expose publicly.
if pprofAddr != "" {
go func() {
log.Printf("pprof listening on %s\n", pprofAddr)
if err := http.ListenAndServe(pprofAddr, nil); err != nil {
log.Printf("pprof server error: %v\n", err)
}
}()
}
// Create the main handler
mainHandler := http.HandlerFunc(
@@ -37,8 +48,8 @@ func main() {
// Wrap with API handler if API_HOST is configured
var handler http.Handler = mainHandler
if apiHost != "" && apiWhitelist != "" {
apiHandler := zooid.NewAPIHandler(apiWhitelist, configDir)
if apiHost != "" {
apiHandler := zooid.NewAPIHandler()
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if this request is for the API host
if r.Host == apiHost {
+20 -1
View File
@@ -6,6 +6,10 @@ require (
fiatjaf.com/nostr v0.0.0-20251104112613-38a6ca92b954
github.com/BurntSushi/toml v1.5.0
github.com/Masterminds/squirrel v1.5.4
github.com/aws/aws-sdk-go-v2 v1.41.7
github.com/aws/aws-sdk-go-v2/config v1.32.17
github.com/aws/aws-sdk-go-v2/credentials v1.19.16
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0
github.com/fsnotify/fsnotify v1.9.0
github.com/gosimple/slug v1.15.0
github.com/livekit/protocol v1.43.5-0.20260114074149-a8bb8204ce69
@@ -18,9 +22,24 @@ require (
buf.build/go/protovalidate v0.13.1 // indirect
buf.build/go/protoyaml v0.6.0 // indirect
cel.dev/expr v0.24.0 // indirect
fiatjaf.com/lib v0.3.7 // indirect
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 // indirect
github.com/andybalholm/brotli v1.1.1 // indirect
github.com/antlr4-go/antlr/v4 v4.13.1 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 // indirect
github.com/aws/smithy-go v1.25.1 // indirect
github.com/benbjohnson/clock v1.3.5 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bep/debounce v1.2.1 // indirect
@@ -113,4 +132,4 @@ require (
gopkg.in/yaml.v3 v3.0.1 // indirect
)
replace fiatjaf.com/nostr => gitea.coracle.social/Coracle/nostrlib v0.0.0-20260313164927-662e7d271c47
replace fiatjaf.com/nostr => gitea.coracle.social/Coracle/nostrlib v0.0.0-20260505183642-fefc85d50080
+40 -2
View File
@@ -8,8 +8,10 @@ cel.dev/expr v0.24.0 h1:56OvJKSH3hDGL0ml5uSxZmz3/3Pq4tJ+fb1unVLAFcY=
cel.dev/expr v0.24.0/go.mod h1:hLPLo1W4QUmuYdA72RBX06QTs6MXw941piREPl3Yfiw=
dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk=
dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
gitea.coracle.social/Coracle/nostrlib v0.0.0-20260313164927-662e7d271c47 h1:Pg/8ZXG2diV3uWbgt3mcAWF2ifL4FZXwotieokY8TBA=
gitea.coracle.social/Coracle/nostrlib v0.0.0-20260313164927-662e7d271c47/go.mod h1:ue7yw0zHfZj23Ml2kVSdBx0ENEaZiuvGxs/8VEN93FU=
fiatjaf.com/lib v0.3.7 h1:mXZOn7NrUcjSdy4oNvwQyAmes7Ueb+Zr5hjqMIe2dxI=
fiatjaf.com/lib v0.3.7/go.mod h1:UlHaZvPHj25PtKLh9GjZkUHRmQ2xZ8Jkoa4VRaLeeQ8=
gitea.coracle.social/Coracle/nostrlib v0.0.0-20260505183642-fefc85d50080 h1:nNL6kqhG0U4dVHYoRULb/klaocv2NGEQm/qxFiZzbzY=
gitea.coracle.social/Coracle/nostrlib v0.0.0-20260505183642-fefc85d50080/go.mod h1:b1EIUDnd133Ie8Pg8O/biaKdFyCMz28aD4n64g1GqvM=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
@@ -28,6 +30,42 @@ github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7X
github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
github.com/aws/aws-sdk-go-v2/config v1.32.17 h1:FpL4/758/diKwqbytU0prpuiu60fgXKUWCpDJtApclU=
github.com/aws/aws-sdk-go-v2/config v1.32.17/go.mod h1:OXqUMzgXytfoF9JaKkhrOYsyh72t9G+MJH8mMRaexOE=
github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU=
github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23 h1:UuSfcORqNSz/ey3VPRS8TcVH2Ikf0/sC+Hdj400QI6U=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.23/go.mod h1:+G/OSGiOFnSOkYloKj/9M35s74LgVAdJBSD5lsFfqKg=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11 h1:TdJ+HdzOBhU8+iVAOGUTU63VXopcumCOF1paFulHWZc=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.11/go.mod h1:R82ZRExE/nheo0N+T8zHPcLRTcH8MGsnR3BiVGX0TwI=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17 h1:7byT8HUWrgoRp6sXjxtZwgOKfhss5fW6SkLBtqzgRoE=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.17/go.mod h1:xNWknVi4Ezm1vg1QsB/5EWpAJURq22uqd38U8qKvOJc=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21 h1:+1Kl1zx6bWi4X7cKi3VYh29h8BvsCoHQEQ6ST9X8w7w=
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.21/go.mod h1:4vIRDq+CJB2xFAXZ+YgGUTiEft7oAQlhIs71xcSeuVg=
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1 h1:F/M5Y9I3nwr2IEpshZgh1GeHpOItExNM9L1euNuh/fk=
github.com/aws/aws-sdk-go-v2/service/sts v1.42.1/go.mod h1:mTNxImtovCOEEuD65mKW7DCsL+2gjEH+RPEAexAzAio=
github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
github.com/benbjohnson/clock v1.3.5/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
BIN
View File
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

+241 -292
View File
@@ -2,219 +2,91 @@ package zooid
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"fiatjaf.com/nostr"
"github.com/BurntSushi/toml"
)
// APIHandler handles REST API requests for managing virtual relays
type APIHandler struct {
whitelist map[string]bool
configDir string
mux http.Handler
}
// NewAPIHandler creates a new API handler with the given whitelist
func NewAPIHandler(whitelist string, configDir string) *APIHandler {
w := make(map[string]bool)
for _, pubkey := range Split(whitelist, ",") {
func NewAPIHandler() *APIHandler {
whitelist := make(map[string]bool)
for _, pubkey := range Split(Env("API_WHITELIST"), ",") {
pubkey = strings.TrimSpace(pubkey)
if pubkey != "" {
w[pubkey] = true
whitelist[pubkey] = true
}
}
return &APIHandler{
whitelist: w,
configDir: configDir,
api := &APIHandler{
whitelist: whitelist,
}
mux := http.NewServeMux()
mux.HandleFunc("POST /relay/{id}", api.auth(api.createRelay))
mux.HandleFunc("PUT /relay/{id}", api.auth(api.putRelay))
mux.HandleFunc("PATCH /relay/{id}", api.auth(api.patchRelay))
mux.HandleFunc("DELETE /relay/{id}", api.auth(api.deleteRelay))
mux.HandleFunc("GET /relay/{id}/members", api.auth(api.listRelayMembers))
api.mux = mux
return api
}
func (api *APIHandler) auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
pubkey, err := validateNIP98Auth(r)
if err != nil {
writeError(w, http.StatusUnauthorized, err.Error())
return
}
if !api.whitelist[pubkey.Hex()] {
writeError(w, http.StatusForbidden, "pubkey not in whitelist")
return
}
next(w, r)
}
}
// ServeHTTP implements the http.Handler interface
func (api *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Authenticate the request using NIP-98
pubkey, err := validateNIP98Auth(r)
if err != nil {
writeError(w, http.StatusUnauthorized, err.Error())
return
}
// Check if pubkey is in whitelist
if !api.whitelist[pubkey.Hex()] {
writeError(w, http.StatusForbidden, "pubkey not in whitelist")
return
}
// Route the request
path := strings.TrimPrefix(r.URL.Path, "/")
parts := strings.Split(path, "/")
if len(parts) < 2 || parts[0] != "relay" {
writeError(w, http.StatusNotFound, "not found")
return
}
id := parts[1]
if id == "" {
writeError(w, http.StatusBadRequest, "relay id is required")
return
}
switch r.Method {
case http.MethodPost:
api.createRelay(w, r, id)
case http.MethodPut:
api.updateRelay(w, r, id)
case http.MethodPatch:
api.patchRelay(w, r, id)
case http.MethodDelete:
api.deleteRelay(w, r, id)
default:
writeError(w, http.StatusMethodNotAllowed, "method not allowed")
}
api.mux.ServeHTTP(w, r)
}
// writeError writes a JSON error response
func writeError(w http.ResponseWriter, status int, message string) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"error": message})
}
// writeJSON writes a JSON success response
func writeJSON(w http.ResponseWriter, status int, data map[string]string) {
func writeJSON(w http.ResponseWriter, status int, v any) {
w.WriteHeader(status)
json.NewEncoder(w).Encode(data)
json.NewEncoder(w).Encode(v)
}
// scheme returns the URL scheme based on the request
func scheme(r *http.Request) string {
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
return "https"
}
return "http"
}
// Relay CRUD
// createRelay creates a new relay config file
func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request, id string) {
configPath := api.configPath(id)
func (api *APIHandler) configFromRequest(path string, r *http.Request) (*Config, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
if _, err := os.Stat(configPath); err == nil {
writeError(w, http.StatusConflict, "relay with this id already exists")
return
}
config, err := api.parseAndValidateConfig(r)
body, err := io.ReadAll(r.Body)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
return nil, fmt.Errorf("failed to read body: %w", err)
}
if err := api.checkDuplicateSchemaOrHost(config, ""); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := api.saveConfig(configPath, config); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
writeJSON(w, http.StatusCreated, map[string]string{"message": "relay created successfully"})
return LoadConfigFromJson(path, body)
}
// updateRelay updates an existing relay config file
func (api *APIHandler) updateRelay(w http.ResponseWriter, r *http.Request, id string) {
configPath := api.configPath(id)
if err := api.checkConfigExists(configPath); err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to check config: %v", err))
}
return
}
config, err := api.parseAndValidateConfig(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(config, id+".toml"); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := api.saveConfig(configPath, config); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "relay updated successfully"})
}
// patchRelay partially updates an existing relay config
func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request, id string) {
configPath := api.configPath(id)
if err := api.checkConfigExists(configPath); err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to check config: %v", err))
}
return
}
// Load existing config
existing, err := api.loadConfigFromPath(configPath)
if err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to read existing config: %v", err))
return
}
// Parse patch
patch, err := api.readPatch(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// Apply patch to existing config
if err := api.applyPatch(existing, patch); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// Validate the patched config
if err := api.validatePatchedConfig(existing); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(existing, id+".toml"); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := api.saveConfig(configPath, existing); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "relay patched successfully"})
}
// readPatch reads and parses the patch JSON from the request
func (api *APIHandler) readPatch(r *http.Request) (map[string]interface{}, error) {
func (api *APIHandler) patchFromRequest(r *http.Request) (map[string]interface{}, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
@@ -225,13 +97,143 @@ func (api *APIHandler) readPatch(r *http.Request) (map[string]interface{}, error
var patch map[string]interface{}
if err := json.Unmarshal(body, &patch); err != nil {
return nil, fmt.Errorf("invalid json: %w", err)
return nil, fmt.Errorf("invalid json config: %w", err)
}
return patch, nil
}
// applyPatch applies a JSON patch to a config using reflection via JSON marshaling
func (api *APIHandler) checkDuplicateSchemaOrHost(config *Config, excludeFilename string) error {
entries, err := os.ReadDir(Env("CONFIG"))
if err != nil {
return fmt.Errorf("failed to read config directory: %w", err)
}
for _, entry := range entries {
if entry.IsDir() || entry.Name() == excludeFilename || !strings.HasSuffix(entry.Name(), ".toml") {
continue
}
path := ConfigPathFromName(entry.Name())
if existing, err := LoadConfigFromPath(path); err == nil {
if existing.Schema == config.Schema {
return fmt.Errorf("schema %q is already in use", config.Schema)
}
if existing.Host == config.Host {
return fmt.Errorf("host %q is already in use", config.Host)
}
}
}
return nil
}
// Create relay
func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
name := ConfigNameFromId(r.PathValue("id"))
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err == nil {
writeError(w, http.StatusConflict, "relay with this id already exists")
return
}
config, err := api.configFromRequest(path, r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(config, ""); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := config.Save(); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
writeJSON(w, http.StatusCreated, map[string]string{"message": "relay created successfully"})
}
// Put relay
func (api *APIHandler) putRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "relay not found")
return
}
config, err := api.configFromRequest(path, r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(config, name); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := config.Save(); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "relay updated successfully"})
}
// Patch relay
func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "relay not found")
return
}
config, err := LoadConfigFromPath(path)
if err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to read existing config: %v", err))
return
}
patch, err := api.patchFromRequest(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.applyPatch(config, patch); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := config.Validate(); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if err := api.checkDuplicateSchemaOrHost(config, name); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
if err := config.Save(); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to write config: %v", err))
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "relay patched successfully"})
}
func (api *APIHandler) applyPatch(config *Config, patch map[string]interface{}) error {
// Convert config to map for merging
configJSON, _ := json.Marshal(config)
@@ -248,12 +250,15 @@ func (api *APIHandler) applyPatch(config *Config, patch map[string]interface{})
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
*config = patched
return nil
}
// deepMerge recursively merges patch into base
func deepMerge(base, patch map[string]interface{}) map[string]interface{} {
result := make(map[string]interface{})
@@ -278,46 +283,18 @@ func deepMerge(base, patch map[string]interface{}) map[string]interface{} {
return result
}
// validatePatchedConfig validates a config after patching
func (api *APIHandler) validatePatchedConfig(config *Config) error {
if config.Host == "" {
return fmt.Errorf("host is required")
}
if config.Schema == "" {
return fmt.Errorf("schema is required")
}
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(config.Schema) {
return fmt.Errorf("schema must contain only letters, numbers, and underscores")
}
if config.Secret == "" {
return fmt.Errorf("secret is required")
}
if _, err := nostr.SecretKeyFromHex(config.Secret); err != nil {
return fmt.Errorf("invalid secret key: %w", err)
}
if config.Info.Pubkey == "" {
return fmt.Errorf("info.pubkey is required")
}
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
return fmt.Errorf("invalid info.pubkey: %w", err)
}
return nil
}
// Delete relay
// deleteRelay deletes a relay config file
func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request, id string) {
configPath := api.configPath(id)
if err := api.checkConfigExists(configPath); err != nil {
if os.IsNotExist(err) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to check config: %v", err))
}
func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
path := ConfigPathFromName(name)
if _, err := os.Stat(path); err != nil {
writeError(w, http.StatusNotFound, "relay not found")
return
}
if err := os.Remove(configPath); err != nil {
if err := os.Remove(path); err != nil {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to delete config: %v", err))
return
}
@@ -325,90 +302,62 @@ func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request, id st
writeJSON(w, http.StatusOK, map[string]string{"message": "relay deleted successfully"})
}
// configPath returns the full path for a config file
func (api *APIHandler) configPath(id string) string {
return filepath.Join(api.configDir, id+".toml")
// Relay members endpoint
func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
name := ConfigNameFromId(id)
members, err := api.resolveRelayMembers(name)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
writeError(w, http.StatusNotFound, "relay not found")
} else {
writeError(w, http.StatusInternalServerError, fmt.Sprintf("failed to load relay members: %v", err))
}
return
}
writeJSON(w, http.StatusOK, map[string][]string{"members": members})
}
// checkConfigExists checks if a config file exists
func (api *APIHandler) checkConfigExists(path string) error {
_, err := os.Stat(path)
return err
}
func (api *APIHandler) resolveRelayMembers(name string) ([]string, error) {
instancesMux.RLock()
instance, exists := instancesByName[name]
instancesMux.RUnlock()
// loadConfigFromPath loads a config from a file path
func (api *APIHandler) loadConfigFromPath(path string) (*Config, error) {
var config Config
_, err := toml.DecodeFile(path, &config)
if exists {
return collectMembers(instance.Management), nil
}
path := ConfigPathFromName(name)
config, err := LoadConfigFromPath(path)
if err != nil {
return nil, err
}
return &config, nil
events := &EventStore{
Config: config,
Schema: &Schema{Name: config.Schema},
}
if err := events.Init(); err != nil {
return nil, fmt.Errorf("failed to init event store: %w", err)
}
management := &ManagementStore{
Config: config,
Events: events,
}
return collectMembers(management), nil
}
// parseAndValidateConfig parses and validates the JSON config from the request body
func (api *APIHandler) parseAndValidateConfig(r *http.Request) (*Config, error) {
r.Body = http.MaxBytesReader(nil, r.Body, 1024*1024)
defer r.Body.Close()
body, err := io.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("failed to read body: %w", err)
func collectMembers(management *ManagementStore) []string {
memberSet := make(map[string]struct{})
for _, pubkey := range management.GetMembers() {
memberSet[pubkey.Hex()] = struct{}{}
}
var config Config
if err := json.Unmarshal(body, &config); err != nil {
return nil, fmt.Errorf("invalid json config: %w", err)
}
if err := api.validatePatchedConfig(&config); err != nil {
return nil, err
}
return &config, nil
}
// saveConfig saves a config to a file as TOML
func (api *APIHandler) saveConfig(path string, config *Config) error {
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer file.Close()
encoder := toml.NewEncoder(file)
if err := encoder.Encode(config); err != nil {
return fmt.Errorf("failed to encode toml: %w", err)
}
return nil
}
// checkDuplicateSchemaOrHost checks if the schema or host is already in use by another config
func (api *APIHandler) checkDuplicateSchemaOrHost(config *Config, excludeFilename string) error {
entries, err := os.ReadDir(api.configDir)
if err != nil {
return fmt.Errorf("failed to read config directory: %w", err)
}
for _, entry := range entries {
if entry.IsDir() || entry.Name() == excludeFilename || !strings.HasSuffix(entry.Name(), ".toml") {
continue
}
path := filepath.Join(api.configDir, entry.Name())
var existing Config
if _, err := toml.DecodeFile(path, &existing); err != nil {
continue
}
if existing.Schema == config.Schema {
return fmt.Errorf("schema %q is already in use", config.Schema)
}
if existing.Host == config.Host {
return fmt.Errorf("host %q is already in use", config.Host)
}
}
return nil
members := Keys(memberSet)
sort.Strings(members)
return members
}
+239 -34
View File
@@ -16,16 +16,14 @@ import (
)
func TestAPIHandler_Authentication(t *testing.T) {
// Create a temporary config directory
configDir := t.TempDir()
useTestConfigDir(t)
// Create a test keypair for authentication
secretKey := nostr.Generate()
pubkey := secretKey.Public()
// Create API handler with whitelist containing our test pubkey
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
t.Run("missing authorization header", func(t *testing.T) {
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) {
configDir := t.TempDir()
configDir := useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
validConfig := map[string]interface{}{
"host": "relay.example.com",
@@ -226,6 +223,9 @@ func TestAPIHandler_CreateRelay(t *testing.T) {
"host": "other.example.com",
"schema": "testrelay", // Same schema as existing
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(config)
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
"schema": "otherschema",
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(config)
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) {
configDir := t.TempDir()
useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
// Create initial relay
initialConfig := map[string]interface{}{
@@ -371,6 +373,9 @@ func TestAPIHandler_UpdateRelay(t *testing.T) {
"host": "other.example.com",
"schema": "otherrelay",
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(otherConfig)
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",
"schema": "otherrelay", // Duplicate
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ = json.Marshal(updateConfig)
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) {
configDir := t.TempDir()
useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
// Create initial relay with full config
initialConfig := map[string]interface{}{
@@ -494,6 +501,9 @@ func TestAPIHandler_PatchRelay(t *testing.T) {
"host": "other.example.com",
"schema": "anotherrelay",
"secret": secretKey.Hex(),
"info": map[string]interface{}{
"pubkey": pubkey.Hex(),
},
}
body, _ := json.Marshal(otherConfig)
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) {
configDir := t.TempDir()
configDir := useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
// Create a relay to delete
config := map[string]interface{}{
@@ -604,13 +613,187 @@ func TestAPIHandler_DeleteRelay(t *testing.T) {
})
}
func TestAPIHandler_MethodNotAllowed(t *testing.T) {
configDir := t.TempDir()
func TestAPIHandler_ListRelayMembers(t *testing.T) {
useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
t.Run("list members from loaded relay instance", func(t *testing.T) {
member1 := nostr.Generate().Public()
member2 := nostr.Generate().Public()
management := createTestManagementStore()
if err := management.AllowPubkey(member1); err != nil {
t.Fatalf("failed to add first member: %v", err)
}
if err := management.AllowPubkey(member2); err != nil {
t.Fatalf("failed to add second member: %v", err)
}
instancesMux.Lock()
oldByName := instancesByName
oldByHost := instancesByHost
instancesByName = map[string]*Instance{
"loaded.toml": {
Config: &Config{Inactive: false},
Management: management,
},
}
instancesByHost = map[string]*Instance{}
instancesMux.Unlock()
defer func() {
instancesMux.Lock()
instancesByName = oldByName
instancesByHost = oldByHost
instancesMux.Unlock()
}()
req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/loaded/members", secretKey, nil)
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d: %s", http.StatusOK, w.Code, w.Body.String())
}
var payload struct {
Members []string `json:"members"`
}
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
expected := map[string]struct{}{
member1.Hex(): {},
member2.Hex(): {},
}
if len(payload.Members) != len(expected) {
t.Fatalf("expected %d members, got %d (%v)", len(expected), len(payload.Members), payload.Members)
}
for _, actual := range payload.Members {
if _, ok := expected[actual]; !ok {
t.Fatalf("unexpected member in response: %s", actual)
}
}
})
t.Run("list members from config fallback", func(t *testing.T) {
relaySecret := nostr.Generate()
member1 := nostr.Generate().Public()
member2 := nostr.Generate().Public()
config := &Config{
Host: "members.example.com",
Schema: "members_" + strings.ToLower(RandomString(8)),
Secret: relaySecret.Hex(),
}
config.Info.Pubkey = nostr.Generate().Public().Hex()
config.path = ConfigPathFromName(ConfigNameFromId("fallback"))
if err := config.Save(); err != nil {
t.Fatalf("failed to save config: %v", err)
}
// Seed DB with RELAY_MEMBERS to simulate a prior relay load.
seedEvents := &EventStore{
Config: &Config{secret: relaySecret},
Schema: &Schema{Name: config.Schema},
}
if err := seedEvents.Init(); err != nil {
t.Fatalf("failed to init seed events: %v", err)
}
membersEvent := nostr.Event{
Kind: RELAY_MEMBERS,
CreatedAt: nostr.Now(),
Tags: nostr.Tags{
{"-"},
{"member", member1.Hex()},
{"member", member2.Hex()},
},
}
if err := seedEvents.SignAndStoreEvent(&membersEvent, false); err != nil {
t.Fatalf("failed to seed members event: %v", err)
}
instancesMux.Lock()
oldByName := instancesByName
oldByHost := instancesByHost
instancesByName = map[string]*Instance{}
instancesByHost = map[string]*Instance{}
instancesMux.Unlock()
defer func() {
instancesMux.Lock()
instancesByName = oldByName
instancesByHost = oldByHost
instancesMux.Unlock()
}()
req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/fallback/members", secretKey, nil)
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected status %d, got %d: %s", http.StatusOK, w.Code, w.Body.String())
}
var payload struct {
Members []string `json:"members"`
}
if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
expected := map[string]struct{}{
member1.Hex(): {},
member2.Hex(): {},
}
if len(payload.Members) != len(expected) {
t.Fatalf("expected %d members, got %d (%v)", len(expected), len(payload.Members), payload.Members)
}
for _, actual := range payload.Members {
if _, ok := expected[actual]; !ok {
t.Fatalf("unexpected member in response: %s", actual)
}
}
})
t.Run("non-existent relay returns not found", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/missing/members", secretKey, nil)
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected status %d, got %d", http.StatusNotFound, w.Code)
}
})
t.Run("members endpoint rejects non-get methods", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/relay/loaded/members", secretKey, []byte("{}"))
w := httptest.NewRecorder()
api.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected status %d, got %d", http.StatusMethodNotAllowed, w.Code)
}
})
}
func TestAPIHandler_MethodNotAllowed(t *testing.T) {
useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
api := newTestAPIHandler(t, pubkey.Hex())
t.Run("GET method not allowed", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodGet, "http://api.example.com/relay/test", secretKey, nil)
@@ -625,12 +808,11 @@ func TestAPIHandler_MethodNotAllowed(t *testing.T) {
}
func TestAPIHandler_InvalidPath(t *testing.T) {
configDir := t.TempDir()
useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
t.Run("invalid path returns not found", func(t *testing.T) {
req := createAuthenticatedRequest(http.MethodPost, "http://api.example.com/invalid/path", secretKey, []byte("{}"))
@@ -649,19 +831,18 @@ func TestAPIHandler_InvalidPath(t *testing.T) {
api.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
if w.Code != http.StatusNotFound {
t.Errorf("expected status %d, got %d", http.StatusNotFound, w.Code)
}
})
}
func TestAPIHandler_ConfigValidation(t *testing.T) {
configDir := t.TempDir()
configDir := useTestConfigDir(t)
secretKey := nostr.Generate()
pubkey := secretKey.Public()
whitelist := pubkey.Hex()
api := NewAPIHandler(whitelist, configDir)
api := newTestAPIHandler(t, pubkey.Hex())
t.Run("invalid info.pubkey", func(t *testing.T) {
config := map[string]interface{}{
@@ -802,9 +983,33 @@ func createAuthenticatedRequest(method, url string, secretKey nostr.SecretKey, b
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) {
t.Run("empty whitelist", func(t *testing.T) {
api := NewAPIHandler("", "/tmp")
api := newTestAPIHandler(t)
if len(api.whitelist) != 0 {
t.Error("expected empty whitelist")
}
@@ -812,7 +1017,7 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("single pubkey", func(t *testing.T) {
pubkey := nostr.Generate().Public().Hex()
api := NewAPIHandler(pubkey, "/tmp")
api := newTestAPIHandler(t, pubkey)
if len(api.whitelist) != 1 {
t.Error("expected 1 entry in whitelist")
}
@@ -824,8 +1029,8 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("multiple pubkeys", func(t *testing.T) {
pubkey1 := nostr.Generate().Public().Hex()
pubkey2 := nostr.Generate().Public().Hex()
whitelist := fmt.Sprintf("%s, %s", pubkey1, pubkey2)
api := NewAPIHandler(whitelist, "/tmp")
setTestEnv("API_WHITELIST", fmt.Sprintf("%s, %s", pubkey1, pubkey2))
api := NewAPIHandler()
if len(api.whitelist) != 2 {
t.Error("expected 2 entries in whitelist")
}
@@ -836,8 +1041,8 @@ func TestNewAPIHandler(t *testing.T) {
t.Run("whitespace trimming", func(t *testing.T) {
pubkey := nostr.Generate().Public().Hex()
whitelist := " " + pubkey + " "
api := NewAPIHandler(whitelist, "/tmp")
setTestEnv("API_WHITELIST", " "+pubkey+" ")
api := NewAPIHandler()
if len(api.whitelist) != 1 {
t.Error("expected 1 entry in whitelist after trimming")
}
+131 -26
View File
@@ -3,13 +3,19 @@ package zooid
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/url"
"path/filepath"
"fiatjaf.com/nostr"
"fiatjaf.com/nostr/eventstore"
"fiatjaf.com/nostr/khatru/blossom"
"github.com/gosimple/slug"
"github.com/aws/aws-sdk-go-v2/aws"
awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/spf13/afero"
)
@@ -19,39 +25,23 @@ type BlossomStore struct {
}
func (bl *BlossomStore) Enable(instance *Instance) {
dir := Env("MEDIA") + "/" + slug.Make(bl.Config.Schema)
fs := afero.NewOsFs()
fs.MkdirAll(dir, 0755)
backend := blossom.New(instance.Relay, "https://"+bl.Config.Host)
backend.Store = blossom.EventStoreBlobIndexWrapper{
Store: bl.Events,
ServiceURL: "https://" + bl.Config.Host,
}
backend.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
file, err := fs.Create(dir + "/" + sha256)
if err != nil {
return err
switch bl.Config.Blossom.Adapter {
case "local":
if err := bl.UseLocalAdapter(backend); err != nil {
log.Fatalf("blossom: failed to use local adapter %q", err)
}
if _, err := io.Copy(file, bytes.NewReader(body)); err != nil {
return err
case "s3":
if err := bl.UseS3Adapter(backend); err != nil {
log.Fatalf("blossom: failed to use s3 adapter %q", err)
}
return nil
}
backend.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
file, err := fs.Open(dir + "/" + sha256)
if err != nil {
return nil, nil, err
}
return file, nil, nil
}
backend.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
return fs.Remove(dir + "/" + sha256)
default:
log.Fatalf("blossom: unknown backend %q", bl.Config.Blossom.Adapter)
}
backend.RejectUpload = func(ctx context.Context, auth *nostr.Event, size int, ext string) (bool, string, int) {
@@ -67,6 +57,10 @@ func (bl *BlossomStore) Enable(instance *Instance) {
}
backend.RejectGet = func(ctx context.Context, auth *nostr.Event, sha256 string, ext string) (bool, string, int) {
if !bl.Config.Blossom.AuthenticatedRead {
return false, "", 200
}
if auth == nil || !instance.Management.IsMember(auth.PubKey) {
return true, "unauthorized", 403
}
@@ -95,3 +89,114 @@ func (bl *BlossomStore) Enable(instance *Instance) {
instance.Relay.Info.SupportedNIPs = append(instance.Relay.Info.SupportedNIPs, "BUD-02")
instance.Relay.Info.SupportedNIPs = append(instance.Relay.Info.SupportedNIPs, "BUD-11")
}
// Local adapter
func (bl *BlossomStore) UseLocalAdapter(backend *blossom.BlossomServer) error {
dir := filepath.Join(Env("MEDIA"), bl.Config.Schema)
osfs := afero.NewOsFs()
_ = osfs.MkdirAll(dir, 0755)
backend.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
file, err := osfs.Create(filepath.Join(dir, sha256))
if err != nil {
return err
}
if _, err := io.Copy(file, bytes.NewReader(body)); err != nil {
return err
}
return nil
}
backend.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
file, err := osfs.Open(filepath.Join(dir, sha256))
if err != nil {
return nil, nil, err
}
return file, nil, nil
}
backend.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
return osfs.Remove(filepath.Join(dir, sha256))
}
return nil
}
// S3 adapter
func (bl *BlossomStore) S3Key(sha256 string) string {
key := bl.Config.Schema + "/" + sha256
if bl.Config.Blossom.S3.KeyPrefix != "" {
key = bl.Config.Blossom.S3.KeyPrefix + "/" + key
}
return key
}
func (bl *BlossomStore) UseS3Adapter(backend *blossom.BlossomServer) error {
ctx := context.Background()
awsConfig, err := awsconfig.LoadDefaultConfig(ctx,
awsconfig.WithRegion(bl.Config.Blossom.S3.Region),
awsconfig.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(
bl.Config.Blossom.S3.AccessKey,
bl.Config.Blossom.S3.SecretKey,
"",
),
),
)
if err != nil {
return fmt.Errorf("aws config: %w", err)
}
client := s3.NewFromConfig(awsConfig, func(o *s3.Options) {
if bl.Config.Blossom.S3.Endpoint != "" {
o.BaseEndpoint = aws.String(bl.Config.Blossom.S3.Endpoint)
o.UsePathStyle = true
}
})
backend.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
_, err := client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(bl.Config.Blossom.S3.Bucket),
Key: aws.String(bl.S3Key(sha256)),
Body: bytes.NewReader(body),
})
return err
}
backend.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
out, err := client.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(bl.Config.Blossom.S3.Bucket),
Key: aws.String(bl.S3Key(sha256)),
})
if err != nil {
return nil, nil, err
}
defer out.Body.Close()
data, err := io.ReadAll(out.Body)
if err != nil {
return nil, nil, err
}
return bytes.NewReader(data), nil, nil
}
backend.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(bl.Config.Blossom.S3.Bucket),
Key: aws.String(bl.S3Key(sha256)),
})
return err
}
return nil
}
+93 -31
View File
@@ -1,11 +1,13 @@
package zooid
import (
"encoding/json"
"fiatjaf.com/nostr"
"fmt"
"github.com/BurntSushi/toml"
"os"
"path/filepath"
"regexp"
"slices"
)
@@ -45,7 +47,10 @@ type Config struct {
} `toml:"management" json:"management"`
Blossom struct {
Enabled bool `toml:"enabled" json:"enabled"`
Enabled bool `toml:"enabled" json:"enabled"`
AuthenticatedRead bool `toml:"authenticated_read" json:"authenticated_read"`
Adapter string `toml:"adapter" json:"adapter"`
S3 BlossomS3Settings `toml:"s3" json:"s3"`
} `toml:"blossom" json:"blossom"`
Livekit struct {
@@ -56,50 +61,110 @@ type Config struct {
Roles map[string]Role `toml:"roles" json:"roles"`
// Private/parsed values
// Parsed values
path string
secret nostr.SecretKey
}
func LoadConfig(filename string) (*Config, error) {
path := filepath.Join(Env("CONFIG"), filename)
// BlossomS3Settings configures S3-compatible object storage for Blossom blobs
// when [blossom] adapter is "s3".
type BlossomS3Settings struct {
Endpoint string `toml:"endpoint" json:"endpoint"`
Region string `toml:"region" json:"region"`
Bucket string `toml:"bucket" json:"bucket"`
AccessKey string `toml:"access_key" json:"access_key"`
SecretKey string `toml:"secret_key" json:"secret_key"`
KeyPrefix string `toml:"key_prefix" json:"key_prefix"`
}
func ConfigNameFromId(id string) string {
return id + ".toml"
}
func ConfigPathFromName(name string) string {
return filepath.Join(Env("CONFIG"), name)
}
func LoadConfigFromPath(path string) (*Config, error) {
var config Config
if _, err := toml.DecodeFile(path, &config); err != nil {
return nil, fmt.Errorf("Failed to parse config file %s: %w", path, err)
}
if config.Host == "" {
return nil, fmt.Errorf("host is required")
}
if config.Schema == "" {
return nil, fmt.Errorf("schema is required")
}
if config.Info.Pubkey == "" {
return nil, fmt.Errorf("info.pubkey is required")
}
secret, err := nostr.SecretKeyFromHex(config.Secret)
if err != nil {
return nil, err
}
// Save the path for later
config.path = path
// Make the secret... secret
config.Secret = ""
config.secret = secret
if err := config.Validate(); err != nil {
return nil, err
}
return &config, nil
}
func (config *Config) Save() error {
// Restore the secret key to the public field for saving
config.Secret = config.secret.Hex()
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 {
if config.Blossom.Adapter == "" {
config.Blossom.Adapter = "local"
}
if config.Host == "" {
return fmt.Errorf("host is required")
}
if config.Schema == "" {
return fmt.Errorf("schema is required")
}
if !regexp.MustCompile(`^[a-z_][a-z0-9_]*$`).MatchString(config.Schema) {
return fmt.Errorf("schema must contain only lowercase letters, numbers, and underscores")
}
secret, err := nostr.SecretKeyFromHex(config.Secret)
if err != nil {
return fmt.Errorf("invalid secret key: %w", err)
}
config.secret = secret
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
return fmt.Errorf("invalid info.pubkey: %w", err)
}
if config.Blossom.Adapter == "s3" {
if config.Blossom.S3.Bucket == "" {
return fmt.Errorf("blossom.s3.bucket is required when blossom.adapter is s3")
}
if config.Blossom.S3.Region == "" {
return fmt.Errorf("blossom.s3.region is required when blossom.adapter is s3")
}
if config.Blossom.S3.AccessKey == "" {
return fmt.Errorf("blossom.s3.access_key is required when blossom.adapter is s3")
}
if config.Blossom.S3.SecretKey == "" {
return fmt.Errorf("blossom.s3.secret_key is required when blossom.adapter is s3")
}
} else if config.Blossom.Adapter != "local" {
return fmt.Errorf("invalid blossom adapter")
}
return nil
}
func (config *Config) Save() error {
file, err := os.Create(config.path)
if err != nil {
return fmt.Errorf("Failed to open config file %s: %w", config.path, err)
@@ -111,9 +176,6 @@ func (config *Config) Save() error {
return fmt.Errorf("Failed to encode config file %s: %w", config.path, err)
}
// Clear the secret again
config.Secret = ""
return nil
}
+104
View File
@@ -1,6 +1,8 @@
package zooid
import (
"os"
"path/filepath"
"testing"
"fiatjaf.com/nostr"
@@ -154,3 +156,105 @@ func TestConfig_MemberRole(t *testing.T) {
t.Error("Any pubkey should have member role permissions")
}
}
// 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) {
t.Run("empty adapter defaults to local", func(t *testing.T) {
c := validBlossomTestConfig()
c.Blossom.Enabled = true
if err := c.Validate(); err != nil {
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) {
c := validBlossomTestConfig()
c.Blossom.Enabled = true
c.Blossom.Adapter = "local"
if err := c.Validate(); err != nil {
t.Fatalf("expected nil, got %v", err)
}
})
t.Run("s3 requires bucket region keys and secret", func(t *testing.T) {
c := validBlossomTestConfig()
c.Blossom.Enabled = true
c.Blossom.Adapter = "s3"
c.Blossom.S3.Region = "us-east-1"
if err := c.Validate(); err == nil {
t.Fatal("expected error for missing bucket and credentials")
}
c.Blossom.S3.Bucket = "b"
c.Blossom.S3.AccessKey = "k"
c.Blossom.S3.SecretKey = "s"
if err := c.Validate(); err != nil {
t.Fatalf("expected nil with all s3 fields set, got %v", err)
}
})
t.Run("invalid adapter value", func(t *testing.T) {
c := validBlossomTestConfig()
c.Blossom.Enabled = true
c.Blossom.Adapter = "nfs"
if err := c.Validate(); err == nil {
t.Fatal("expected error for unknown adapter")
}
})
}
func TestLoadConfigFromPath_BlossomS3(t *testing.T) {
sk := nostr.Generate()
tmp := t.TempDir()
path := filepath.Join(tmp, "relay.toml")
tomlBody := `host = "r.example.com"
schema = "myrelay"
secret = "` + sk.Hex() + `"
inactive = false
[info]
name = "n"
pubkey = "` + sk.Public().Hex() + `"
[blossom]
enabled = true
adapter = "s3"
[blossom.s3]
region = "auto"
bucket = "test-bucket"
access_key = "AKIA"
secret_key = "topsecret"
endpoint = "http://127.0.0.1:9000"
`
if err := os.WriteFile(path, []byte(tomlBody), 0644); err != nil {
t.Fatal(err)
}
cfg, err := LoadConfigFromPath(path)
if err != nil {
t.Fatalf("LoadConfigFromPath: %v", err)
}
if cfg.Blossom.S3.SecretKey != "topsecret" {
t.Errorf("expected s3 secret_key retained in struct, got %q", cfg.Blossom.S3.SecretKey)
}
if cfg.Blossom.Adapter != "s3" {
t.Errorf("adapter: got %q", cfg.Blossom.Adapter)
}
}
+10 -9
View File
@@ -294,17 +294,17 @@ func (events *EventStore) SaveEvent(evt nostr.Event) error {
return nil
}
func (events *EventStore) ReplaceEvent(evt nostr.Event) error {
func (events *EventStore) ReplaceEvent(evt nostr.Event) ([]nostr.Event, error) {
filter := nostr.Filter{Kinds: []nostr.Kind{evt.Kind}, Authors: []nostr.PubKey{evt.PubKey}}
if evt.Kind.IsAddressable() {
filter.Tags = nostr.TagMap{"d": []string{evt.Tags.GetD()}}
}
shouldSave := true
shouldDelete := make([]nostr.ID, 0)
shouldDelete := make([]nostr.Event, 0)
for previous := range events.QueryEvents(filter, 1) {
if previous.CreatedAt <= evt.CreatedAt {
shouldDelete = append(shouldDelete, previous.ID)
shouldDelete = append(shouldDelete, previous)
} else {
shouldSave = false
}
@@ -312,16 +312,16 @@ func (events *EventStore) ReplaceEvent(evt nostr.Event) error {
if shouldSave {
if err := events.SaveEvent(evt); err != nil && err != eventstore.ErrDupEvent {
return fmt.Errorf("failed to save: %w", err)
return nil, fmt.Errorf("failed to save: %w", err)
}
}
// Wait until the end to delete old events, just in case our new one doesn't save
for _, id := range shouldDelete {
events.DeleteEvent(id)
for _, previous := range shouldDelete {
events.DeleteEvent(previous.ID)
}
return nil
return shouldDelete, nil
}
func (events *EventStore) CountEvents(filter nostr.Filter) (uint32, error) {
@@ -344,7 +344,8 @@ func (events *EventStore) CountEvents(filter nostr.Filter) (uint32, error) {
func (events *EventStore) StoreEvent(event nostr.Event) error {
if event.Kind.IsReplaceable() || event.Kind.IsAddressable() {
return events.ReplaceEvent(event)
_, err := events.ReplaceEvent(event)
return err
}
if err := events.SaveEvent(event); err != nil && err != eventstore.ErrDupEvent {
@@ -363,7 +364,7 @@ func (events *EventStore) SignAndStoreEvent(event *nostr.Event, broadcast bool)
return err
}
if broadcast {
if broadcast && events.Relay != nil {
events.Relay.BroadcastEvent(*event)
}
+3 -3
View File
@@ -391,7 +391,7 @@ func TestEventStore_ReplaceEvent(t *testing.T) {
}
event1.Sign(secret)
err := store.ReplaceEvent(event1)
_, err := store.ReplaceEvent(event1)
if err != nil {
t.Errorf("ReplaceEvent() error = %v", err)
}
@@ -405,7 +405,7 @@ func TestEventStore_ReplaceEvent(t *testing.T) {
}
event2.Sign(secret)
err = store.ReplaceEvent(event2)
_, err = store.ReplaceEvent(event2)
if err != nil {
t.Errorf("ReplaceEvent() error = %v", err)
}
@@ -452,7 +452,7 @@ func TestEventStore_ReplaceEvent_OlderEvent(t *testing.T) {
}
event2.Sign(secret)
err := store.ReplaceEvent(event2)
_, err := store.ReplaceEvent(event2)
if err != nil {
t.Errorf("ReplaceEvent() with older event error = %v", err)
}
+12 -7
View File
@@ -9,7 +9,6 @@ import (
"fiatjaf.com/nostr"
"fiatjaf.com/nostr/khatru"
"github.com/gosimple/slug"
)
type Instance struct {
@@ -22,19 +21,24 @@ type Instance struct {
Push *PushManager
}
func MakeInstance(filename string) (*Instance, error) {
config, err := LoadConfig(filename)
func MakeInstance(name string) (*Instance, error) {
path := ConfigPathFromName(name)
config, err := LoadConfigFromPath(path)
if err != nil {
return nil, err
}
return makeInstance(config, name)
}
func makeInstance(config *Config, source string) (*Instance, error) {
relay := khatru.NewRelay()
events := &EventStore{
Relay: relay,
Config: config,
Schema: &Schema{
Name: slug.Make(config.Schema),
Name: config.Schema,
},
}
@@ -101,7 +105,7 @@ func MakeInstance(filename string) (*Instance, error) {
// Expiration
instance.Relay.StartExpirationManager(instance.Relay.QueryStored, instance.Relay.DeleteEvent)
instance.Relay.StartExpirationManager(instance.Relay.QueryStored, instance.Relay.DeleteEvent, nil)
// HTTP request handling
@@ -122,7 +126,7 @@ func MakeInstance(filename string) (*Instance, error) {
// Initialize the database
if err := instance.Events.Init(); err != nil {
log.Fatal("Failed to initialize event store for ", filename, ": ", err)
log.Fatal("Failed to initialize event store for ", source, ": ", err)
}
// Enable extra functionality
@@ -265,7 +269,8 @@ func (instance *Instance) StoreEvent(ctx context.Context, event nostr.Event) err
}
func (instance *Instance) ReplaceEvent(ctx context.Context, event nostr.Event) error {
return instance.Events.ReplaceEvent(event)
_, err := instance.Events.ReplaceEvent(event)
return err
}
func (instance *Instance) DeleteEvent(ctx context.Context, id nostr.ID) error {
+1 -1
View File
@@ -27,7 +27,7 @@ func createTestInstance() *Instance {
schema := &Schema{Name: "test_" + RandomString(8)}
relay := &khatru.Relay{}
relay := khatru.NewRelay()
events := &EventStore{
Relay: relay,
+2
View File
@@ -64,6 +64,7 @@ func Start() {
if err != nil {
log.Printf("Failed to make instance for %s: %v", entry.Name(), err)
} else if instance.Config.Inactive {
instance.Cleanup()
log.Printf("Skipped inactive %s", entry.Name())
} else {
instancesByHost[instance.Config.Host] = instance
@@ -111,6 +112,7 @@ func Start() {
if err != nil {
log.Printf("Failed to reload %s: %v", filename, err)
} else if instance.Config.Inactive {
instance.Cleanup()
log.Printf("Skipped inactive %s", filename)
} else {
instancesByHost[instance.Config.Host] = instance
+20
View File
@@ -0,0 +1,20 @@
package zooid
import (
"os"
"testing"
)
func TestMain(m *testing.M) {
dir, err := os.MkdirTemp("", "zooid-test-*")
if err != nil {
panic(err)
}
os.Setenv("DATA", dir)
code := m.Run()
os.RemoveAll(dir)
os.Exit(code)
}
+1 -1
View File
@@ -13,7 +13,7 @@ func createTestManagementStore() *ManagementStore {
secret: nostr.Generate(),
}
schema := &Schema{Name: "test_" + RandomString(8)}
relay := &khatru.Relay{}
relay := khatru.NewRelay()
events := &EventStore{
Relay: relay,
Config: config,
+6 -1
View File
@@ -183,7 +183,12 @@ func validateNIP98Auth(r *http.Request) (nostr.PubKey, error) {
return nostr.PubKey{}, fmt.Errorf("invalid event signature")
}
expectedURL := fmt.Sprintf("%s://%s%s", scheme(r), r.Host, r.URL.Path)
scheme := "http"
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
scheme = scheme + "s"
}
expectedURL := fmt.Sprintf("%s://%s%s", scheme, r.Host, r.URL.Path)
var hasURL, hasMethod bool
for _, tag := range event.Tags {