forked from coracle/zooid
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9ed0d72ca9 |
+2
-11
@@ -1,13 +1,7 @@
|
||||
FROM --platform=$BUILDPLATFORM golang:1.25 AS build
|
||||
|
||||
ARG TARGETOS TARGETARCH
|
||||
FROM golang AS build
|
||||
|
||||
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
|
||||
@@ -15,10 +9,7 @@ RUN go mod download
|
||||
COPY zooid zooid
|
||||
COPY cmd cmd
|
||||
|
||||
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
|
||||
RUN CGO_ENABLED=1 GOOS=linux go build -o bin/zooid cmd/relay/main.go
|
||||
|
||||
FROM gcr.io/distroless/base-debian12 AS run
|
||||
|
||||
|
||||
@@ -1,41 +1,6 @@
|
||||
<p align="center">
|
||||
<img src="./zooid-wordmark.jpeg" alt="Zooid" width="280" />
|
||||
</p>
|
||||
# Zooid
|
||||
|
||||
<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 \
|
||||
ghcr.io/coracle-social/zooid
|
||||
```
|
||||
|
||||
Drop a TOML config file into `./config/` (see [Configuration](#configuration)) and the relay will be available at `ws://<host>:3334`.
|
||||
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.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -48,7 +13,7 @@ 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 database files. Defaults to `./data`.
|
||||
- `DATA` - where to store databse 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.
|
||||
@@ -95,7 +60,6 @@ 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.
|
||||
|
||||
### `[push]`
|
||||
|
||||
@@ -125,10 +89,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:3334` 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` to this virtual relay.
|
||||
|
||||
```toml
|
||||
host = "my-relay.example.com:3334"
|
||||
host = "my-relay.example.com"
|
||||
schema = "my_relay"
|
||||
secret = "<hex private key>"
|
||||
|
||||
@@ -187,6 +151,15 @@ After running `just build`, a number of scripts will be available:
|
||||
|
||||
See `justfile` for defined commands.
|
||||
|
||||
## License
|
||||
## Deploying
|
||||
|
||||
[MIT](./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
|
||||
```
|
||||
|
||||
@@ -6,10 +6,6 @@ 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
|
||||
@@ -22,24 +18,10 @@ 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
|
||||
fiatjaf.com/lib v0.3.6 // 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
|
||||
@@ -132,4 +114,4 @@ require (
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
replace fiatjaf.com/nostr => gitea.coracle.social/Coracle/nostrlib v0.0.0-20260505183642-fefc85d50080
|
||||
replace fiatjaf.com/nostr => gitea.coracle.social/Coracle/nostrlib v0.0.0-20260414151249-4daeb8737c1c
|
||||
|
||||
@@ -8,10 +8,12 @@ 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=
|
||||
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=
|
||||
fiatjaf.com/lib v0.3.6 h1:GRZNSxHI2EWdjSKVuzaT+c0aifLDtS16SzkeJaHyJfY=
|
||||
fiatjaf.com/lib v0.3.6/go.mod h1:UlHaZvPHj25PtKLh9GjZkUHRmQ2xZ8Jkoa4VRaLeeQ8=
|
||||
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=
|
||||
gitea.coracle.social/Coracle/nostrlib v0.0.0-20260414151249-4daeb8737c1c h1:RqKwqUz1R3LQC2IcsdsyYHEUAZACIAKYxGuntyBCGw8=
|
||||
gitea.coracle.social/Coracle/nostrlib v0.0.0-20260414151249-4daeb8737c1c/go.mod h1:1cmygNC87Pw06/WjkZqDV+Xo6rV10kpTjzuayosIX4Y=
|
||||
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=
|
||||
@@ -30,42 +32,6 @@ 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=
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 302 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 48 KiB |
+96
-82
@@ -13,14 +13,12 @@ import (
|
||||
|
||||
"fiatjaf.com/nostr"
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/gosimple/slug"
|
||||
)
|
||||
|
||||
// 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
|
||||
@@ -32,48 +30,78 @@ func NewAPIHandler(whitelist string, configDir string) *APIHandler {
|
||||
w[pubkey] = true
|
||||
}
|
||||
}
|
||||
api := &APIHandler{
|
||||
return &APIHandler{
|
||||
whitelist: w,
|
||||
configDir: configDir,
|
||||
}
|
||||
api.mux = api.buildMux()
|
||||
return api
|
||||
}
|
||||
|
||||
func (api *APIHandler) buildMux() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /relay/{id}", api.auth(api.createRelay))
|
||||
mux.HandleFunc("PUT /relay/{id}", api.auth(api.updateRelay))
|
||||
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))
|
||||
return mux
|
||||
}
|
||||
|
||||
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")
|
||||
api.mux.ServeHTTP(w, r)
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if len(parts) > 2 {
|
||||
if len(parts) == 3 && parts[2] == "members" {
|
||||
if r.Method != http.MethodGet {
|
||||
writeError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
|
||||
api.listRelayMembers(w, id)
|
||||
return
|
||||
}
|
||||
|
||||
// Keep trailing-slash compatibility for existing /relay/{id}/ calls.
|
||||
if len(parts) != 3 || parts[2] != "" {
|
||||
writeError(w, http.StatusNotFound, "not found")
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
// listRelayMembers returns members for a relay as an array of pubkeys.
|
||||
func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
func (api *APIHandler) listRelayMembers(w http.ResponseWriter, id string) {
|
||||
members, err := api.resolveRelayMembers(id)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
@@ -84,7 +112,8 @@ func (api *APIHandler) listRelayMembers(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, map[string][]string{"members": members})
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string][]string{"members": members})
|
||||
}
|
||||
|
||||
func (api *APIHandler) resolveRelayMembers(id string) ([]string, error) {
|
||||
@@ -92,26 +121,23 @@ func (api *APIHandler) resolveRelayMembers(id string) ([]string, error) {
|
||||
return members, nil
|
||||
}
|
||||
|
||||
config, err := api.loadConfigFromPath(api.configPath(id))
|
||||
if err != nil {
|
||||
configPath := api.configPath(id)
|
||||
if err := api.checkConfigExists(configPath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := &EventStore{
|
||||
Config: config,
|
||||
Schema: &Schema{Name: slug.Make(config.Schema)},
|
||||
instance, err := MakeInstanceFromPath(configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer instance.Cleanup()
|
||||
|
||||
memberSet := make(map[string]struct{})
|
||||
for _, pubkey := range instance.Management.GetMembers() {
|
||||
memberSet[pubkey.Hex()] = struct{}{}
|
||||
}
|
||||
|
||||
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
|
||||
return sortedMembers(memberSet), nil
|
||||
}
|
||||
|
||||
func (api *APIHandler) getMembersFromLoadedInstance(id string) ([]string, bool) {
|
||||
@@ -123,14 +149,15 @@ func (api *APIHandler) getMembersFromLoadedInstance(id string) ([]string, bool)
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return collectMembers(instance.Management), true
|
||||
}
|
||||
|
||||
func collectMembers(management *ManagementStore) []string {
|
||||
memberSet := make(map[string]struct{})
|
||||
for _, pubkey := range management.GetMembers() {
|
||||
for _, pubkey := range instance.Management.GetMembers() {
|
||||
memberSet[pubkey.Hex()] = struct{}{}
|
||||
}
|
||||
|
||||
return sortedMembers(memberSet), true
|
||||
}
|
||||
|
||||
func sortedMembers(memberSet map[string]struct{}) []string {
|
||||
members := Keys(memberSet)
|
||||
sort.Strings(members)
|
||||
return members
|
||||
@@ -143,9 +170,9 @@ func writeError(w http.ResponseWriter, status int, message string) {
|
||||
}
|
||||
|
||||
// writeJSON writes a JSON success response
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
func writeJSON(w http.ResponseWriter, status int, data map[string]string) {
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
// scheme returns the URL scheme based on the request
|
||||
@@ -157,8 +184,7 @@ func scheme(r *http.Request) string {
|
||||
}
|
||||
|
||||
// createRelay creates a new relay config file
|
||||
func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request, id string) {
|
||||
configPath := api.configPath(id)
|
||||
|
||||
if _, err := os.Stat(configPath); err == nil {
|
||||
@@ -186,8 +212,7 @@ func (api *APIHandler) createRelay(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// updateRelay updates an existing relay config file
|
||||
func (api *APIHandler) updateRelay(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
func (api *APIHandler) updateRelay(w http.ResponseWriter, r *http.Request, id string) {
|
||||
configPath := api.configPath(id)
|
||||
|
||||
if err := api.checkConfigExists(configPath); err != nil {
|
||||
@@ -219,8 +244,7 @@ func (api *APIHandler) updateRelay(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// patchRelay partially updates an existing relay config
|
||||
func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request, id string) {
|
||||
configPath := api.configPath(id)
|
||||
|
||||
if err := api.checkConfigExists(configPath); err != nil {
|
||||
@@ -253,7 +277,7 @@ func (api *APIHandler) patchRelay(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// Validate the patched config
|
||||
if err := api.validateConfig(existing); err != nil {
|
||||
if err := api.validatePatchedConfig(existing); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -336,8 +360,8 @@ func deepMerge(base, patch map[string]interface{}) map[string]interface{} {
|
||||
return result
|
||||
}
|
||||
|
||||
// validateConfig validates a config
|
||||
func (api *APIHandler) validateConfig(config *Config) error {
|
||||
// validatePatchedConfig validates a config after patching
|
||||
func (api *APIHandler) validatePatchedConfig(config *Config) error {
|
||||
if config.Host == "" {
|
||||
return fmt.Errorf("host is required")
|
||||
}
|
||||
@@ -353,21 +377,17 @@ func (api *APIHandler) validateConfig(config *Config) error {
|
||||
if _, err := nostr.SecretKeyFromHex(config.Secret); err != nil {
|
||||
return fmt.Errorf("invalid secret key: %w", err)
|
||||
}
|
||||
if config.Info.Pubkey != "" {
|
||||
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
|
||||
return fmt.Errorf("invalid info.pubkey: %w", err)
|
||||
}
|
||||
if config.Info.Pubkey == "" {
|
||||
return fmt.Errorf("info.pubkey is required")
|
||||
}
|
||||
normalizeBlossomConfig(config)
|
||||
if err := validateBlossomFileStorage(config); err != nil {
|
||||
return err
|
||||
if _, err := nostr.PubKeyFromHex(config.Info.Pubkey); err != nil {
|
||||
return fmt.Errorf("invalid info.pubkey: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteRelay deletes a relay config file
|
||||
func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request, id string) {
|
||||
configPath := api.configPath(id)
|
||||
|
||||
if err := api.checkConfigExists(configPath); err != nil {
|
||||
@@ -387,14 +407,9 @@ func (api *APIHandler) deleteRelay(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "relay deleted successfully"})
|
||||
}
|
||||
|
||||
// configName returns the config file name
|
||||
func (api *APIHandler) configName(id string) string {
|
||||
return id+".toml"
|
||||
}
|
||||
|
||||
// configPath returns the full path for a config file
|
||||
func (api *APIHandler) configPath(id string) string {
|
||||
return filepath.Join(api.configDir, api.configName(id))
|
||||
return filepath.Join(api.configDir, id+".toml")
|
||||
}
|
||||
|
||||
// checkConfigExists checks if a config file exists
|
||||
@@ -410,7 +425,6 @@ func (api *APIHandler) loadConfigFromPath(path string) (*Config, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
normalizeBlossomConfig(&config)
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
@@ -429,7 +443,7 @@ func (api *APIHandler) parseAndValidateConfig(r *http.Request) (*Config, error)
|
||||
return nil, fmt.Errorf("invalid json config: %w", err)
|
||||
}
|
||||
|
||||
if err := api.validateConfig(&config); err != nil {
|
||||
if err := api.validatePatchedConfig(&config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
+13
-28
@@ -13,7 +13,6 @@ import (
|
||||
"testing"
|
||||
|
||||
"fiatjaf.com/nostr"
|
||||
"github.com/gosimple/slug"
|
||||
)
|
||||
|
||||
func TestAPIHandler_Authentication(t *testing.T) {
|
||||
@@ -677,40 +676,25 @@ func TestAPIHandler_ListRelayMembers(t *testing.T) {
|
||||
|
||||
t.Run("list members from config fallback", func(t *testing.T) {
|
||||
relaySecret := nostr.Generate()
|
||||
member1 := nostr.Generate().Public()
|
||||
member2 := nostr.Generate().Public()
|
||||
owner := nostr.Generate().Public()
|
||||
rolePubkey := nostr.Generate().Public()
|
||||
|
||||
config := &Config{
|
||||
Host: "members.example.com",
|
||||
Schema: "members_" + RandomString(8),
|
||||
Secret: relaySecret.Hex(),
|
||||
Roles: map[string]Role{
|
||||
"admin": {
|
||||
Pubkeys: []string{rolePubkey.Hex()},
|
||||
},
|
||||
},
|
||||
}
|
||||
config.Info.Pubkey = owner.Hex()
|
||||
|
||||
if err := api.saveConfig(api.configPath("fallback"), config); 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: slug.Make(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
|
||||
@@ -741,8 +725,9 @@ func TestAPIHandler_ListRelayMembers(t *testing.T) {
|
||||
}
|
||||
|
||||
expected := map[string]struct{}{
|
||||
member1.Hex(): {},
|
||||
member2.Hex(): {},
|
||||
owner.Hex(): {},
|
||||
relaySecret.Public().Hex(): {},
|
||||
rolePubkey.Hex(): {},
|
||||
}
|
||||
|
||||
if len(payload.Members) != len(expected) {
|
||||
@@ -824,8 +809,8 @@ func TestAPIHandler_InvalidPath(t *testing.T) {
|
||||
|
||||
api.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("expected status %d, got %d", http.StatusNotFound, w.Code)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("expected status %d, got %d", http.StatusBadRequest, w.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+14
-116
@@ -3,19 +3,12 @@ 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/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/gosimple/slug"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
@@ -25,39 +18,19 @@ type BlossomStore struct {
|
||||
Events eventstore.Store
|
||||
}
|
||||
|
||||
func loadAWSConfigForBlossomS3(ctx context.Context, s *BlossomS3Settings) (aws.Config, error) {
|
||||
return awsconfig.LoadDefaultConfig(ctx,
|
||||
awsconfig.WithRegion(s.Region),
|
||||
awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(s.AccessKey, s.SecretKey, "")),
|
||||
)
|
||||
}
|
||||
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)
|
||||
|
||||
func s3APIClientForBlossomSettings(awsCfg aws.Config, s *BlossomS3Settings) *s3.Client {
|
||||
customEndpoint := s.Endpoint != ""
|
||||
return s3.NewFromConfig(awsCfg, func(o *s3.Options) {
|
||||
if customEndpoint {
|
||||
o.BaseEndpoint = aws.String(s.Endpoint)
|
||||
// Custom endpoints (e.g. MinIO) expect path-style addressing.
|
||||
o.UsePathStyle = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func blossomS3ObjectKey(slugName, sha256, keyPrefix string) string {
|
||||
rel := slugName + "/" + sha256
|
||||
if keyPrefix != "" {
|
||||
return keyPrefix + "/" + rel
|
||||
backend.Store = blossom.EventStoreBlobIndexWrapper{
|
||||
Store: bl.Events,
|
||||
ServiceURL: "https://" + bl.Config.Host,
|
||||
}
|
||||
return rel
|
||||
}
|
||||
|
||||
func attachBlossomLocalBlobs(bs *blossom.BlossomServer, slugName string) {
|
||||
dir := filepath.Join(Env("MEDIA"), slugName)
|
||||
osfs := afero.NewOsFs()
|
||||
_ = osfs.MkdirAll(dir, 0755)
|
||||
|
||||
bs.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
|
||||
file, err := osfs.Create(filepath.Join(dir, sha256))
|
||||
backend.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
|
||||
file, err := fs.Create(dir + "/" + sha256)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -69,87 +42,16 @@ func attachBlossomLocalBlobs(bs *blossom.BlossomServer, slugName string) {
|
||||
return nil
|
||||
}
|
||||
|
||||
bs.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
|
||||
file, err := osfs.Open(filepath.Join(dir, sha256))
|
||||
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
|
||||
}
|
||||
|
||||
bs.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
|
||||
return osfs.Remove(filepath.Join(dir, sha256))
|
||||
}
|
||||
}
|
||||
|
||||
func attachBlossomS3Blobs(bs *blossom.BlossomServer, cfg *Config, slugName string) error {
|
||||
s := &cfg.Blossom.S3
|
||||
ctx := context.Background()
|
||||
|
||||
awsCfg, err := loadAWSConfigForBlossomS3(ctx, s)
|
||||
if err != nil {
|
||||
return fmt.Errorf("aws config: %w", err)
|
||||
}
|
||||
|
||||
client := s3APIClientForBlossomSettings(awsCfg, s)
|
||||
bucket := s.Bucket
|
||||
|
||||
bs.StoreBlob = func(ctx context.Context, sha256 string, ext string, body []byte) error {
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(blossomS3ObjectKey(slugName, sha256, s.KeyPrefix)),
|
||||
Body: bytes.NewReader(body),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
bs.LoadBlob = func(ctx context.Context, sha256 string, ext string) (io.ReadSeeker, *url.URL, error) {
|
||||
out, err := client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(blossomS3ObjectKey(slugName, sha256, s.KeyPrefix)),
|
||||
})
|
||||
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
|
||||
}
|
||||
|
||||
bs.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
|
||||
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(blossomS3ObjectKey(slugName, sha256, s.KeyPrefix)),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (bl *BlossomStore) Enable(instance *Instance) {
|
||||
slugName := slug.Make(bl.Config.Schema)
|
||||
backend := blossom.New(instance.Relay, "https://"+bl.Config.Host)
|
||||
|
||||
backend.Store = blossom.EventStoreBlobIndexWrapper{
|
||||
Store: bl.Events,
|
||||
ServiceURL: "https://" + bl.Config.Host,
|
||||
}
|
||||
|
||||
switch bl.Config.Blossom.Backend {
|
||||
case "local":
|
||||
attachBlossomLocalBlobs(backend, slugName)
|
||||
case "s3":
|
||||
if err := attachBlossomS3Blobs(backend, bl.Config, slugName); err != nil {
|
||||
log.Fatalf("blossom: s3: %v", err)
|
||||
}
|
||||
default:
|
||||
log.Fatalf("blossom: unknown backend %q (use local or s3)", bl.Config.Blossom.Backend)
|
||||
backend.DeleteBlob = func(ctx context.Context, sha256 string, ext string) error {
|
||||
return fs.Remove(dir + "/" + sha256)
|
||||
}
|
||||
|
||||
backend.RejectUpload = func(ctx context.Context, auth *nostr.Event, size int, ext string) (bool, string, int) {
|
||||
@@ -165,10 +67,6 @@ 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
|
||||
}
|
||||
|
||||
+2
-65
@@ -7,7 +7,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
@@ -46,10 +45,7 @@ type Config struct {
|
||||
} `toml:"management" json:"management"`
|
||||
|
||||
Blossom struct {
|
||||
Enabled bool `toml:"enabled" json:"enabled"`
|
||||
AuthenticatedRead bool `toml:"authenticated_read" json:"authenticated_read"`
|
||||
Backend string `toml:"backend" json:"backend"`
|
||||
S3 BlossomS3Settings `toml:"s3" json:"s3"`
|
||||
Enabled bool `toml:"enabled" json:"enabled"`
|
||||
} `toml:"blossom" json:"blossom"`
|
||||
|
||||
Livekit struct {
|
||||
@@ -65,17 +61,6 @@ type Config struct {
|
||||
secret nostr.SecretKey
|
||||
}
|
||||
|
||||
// BlossomS3Settings configures S3-compatible object storage for Blossom blobs
|
||||
// when [blossom] backend 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 LoadConfig(filename string) (*Config, error) {
|
||||
path := filepath.Join(Env("CONFIG"), filename)
|
||||
|
||||
@@ -83,13 +68,12 @@ func LoadConfig(filename string) (*Config, error) {
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
normalizeBlossomConfig(&config)
|
||||
|
||||
if config.Host == "" {
|
||||
return nil, fmt.Errorf("host is required")
|
||||
}
|
||||
@@ -114,56 +98,9 @@ func LoadConfigFromPath(path string) (*Config, error) {
|
||||
config.Secret = ""
|
||||
config.secret = secret
|
||||
|
||||
if err := validateBlossomFileStorage(&config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
func normalizeBlossomConfig(c *Config) {
|
||||
s := &c.Blossom.S3
|
||||
s.Region = strings.TrimSpace(s.Region)
|
||||
s.Bucket = strings.TrimSpace(s.Bucket)
|
||||
s.AccessKey = strings.TrimSpace(s.AccessKey)
|
||||
s.SecretKey = strings.TrimSpace(s.SecretKey)
|
||||
s.Endpoint = strings.TrimRight(strings.TrimSpace(s.Endpoint), "/")
|
||||
s.KeyPrefix = strings.Trim(strings.TrimSpace(s.KeyPrefix), "/")
|
||||
|
||||
c.Blossom.Backend = strings.ToLower(strings.TrimSpace(c.Blossom.Backend))
|
||||
if c.Blossom.Backend == "" {
|
||||
c.Blossom.Backend = "local"
|
||||
}
|
||||
}
|
||||
|
||||
func validateBlossomFileStorage(c *Config) error {
|
||||
if !c.Blossom.Enabled {
|
||||
return nil
|
||||
}
|
||||
switch c.Blossom.Backend {
|
||||
case "local":
|
||||
return nil
|
||||
case "s3":
|
||||
// fall through
|
||||
default:
|
||||
return fmt.Errorf(`blossom.backend must be "local", "s3", or empty (defaults to local)`)
|
||||
}
|
||||
s := c.Blossom.S3
|
||||
if s.Bucket == "" {
|
||||
return fmt.Errorf("blossom.s3.bucket is required when blossom.backend is s3")
|
||||
}
|
||||
if s.Region == "" {
|
||||
return fmt.Errorf("blossom.s3.region is required when blossom.backend is s3")
|
||||
}
|
||||
if s.AccessKey == "" {
|
||||
return fmt.Errorf("blossom.s3.access_key is required when blossom.backend is s3")
|
||||
}
|
||||
if s.SecretKey == "" {
|
||||
return fmt.Errorf("blossom.s3.secret_key is required when blossom.backend is s3")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (config *Config) Save() error {
|
||||
// Restore the secret key to the public field for saving
|
||||
config.Secret = config.secret.Hex()
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package zooid
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"fiatjaf.com/nostr"
|
||||
@@ -156,94 +154,3 @@ func TestConfig_MemberRole(t *testing.T) {
|
||||
t.Error("Any pubkey should have member role permissions")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateBlossomFileStorage(t *testing.T) {
|
||||
t.Run("blossom disabled skips validation", func(t *testing.T) {
|
||||
c := &Config{}
|
||||
c.Blossom.Enabled = false
|
||||
c.Blossom.Backend = "s3"
|
||||
normalizeBlossomConfig(c)
|
||||
if err := validateBlossomFileStorage(c); err != nil {
|
||||
t.Fatalf("expected nil, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("local storage needs no s3 fields", func(t *testing.T) {
|
||||
c := &Config{}
|
||||
c.Blossom.Enabled = true
|
||||
c.Blossom.Backend = "local"
|
||||
normalizeBlossomConfig(c)
|
||||
if err := validateBlossomFileStorage(c); err != nil {
|
||||
t.Fatalf("expected nil, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("s3 requires bucket region keys and secret", func(t *testing.T) {
|
||||
c := &Config{}
|
||||
c.Blossom.Enabled = true
|
||||
c.Blossom.Backend = "s3"
|
||||
c.Blossom.S3.Region = "us-east-1"
|
||||
normalizeBlossomConfig(c)
|
||||
if err := validateBlossomFileStorage(c); 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"
|
||||
normalizeBlossomConfig(c)
|
||||
if err := validateBlossomFileStorage(c); err != nil {
|
||||
t.Fatalf("expected nil with all s3 fields set, got %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid backend value", func(t *testing.T) {
|
||||
c := &Config{}
|
||||
c.Blossom.Enabled = true
|
||||
c.Blossom.Backend = "nfs"
|
||||
normalizeBlossomConfig(c)
|
||||
if err := validateBlossomFileStorage(c); err == nil {
|
||||
t.Fatal("expected error for unknown backend")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
backend = "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.Backend != "s3" {
|
||||
t.Errorf("backend: got %q", cfg.Blossom.Backend)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -364,7 +364,7 @@ func (events *EventStore) SignAndStoreEvent(event *nostr.Event, broadcast bool)
|
||||
return err
|
||||
}
|
||||
|
||||
if broadcast && events.Relay != nil {
|
||||
if broadcast {
|
||||
events.Relay.BroadcastEvent(*event)
|
||||
}
|
||||
|
||||
|
||||
+11
-3
@@ -31,6 +31,15 @@ func MakeInstance(filename string) (*Instance, error) {
|
||||
return makeInstance(config, filename)
|
||||
}
|
||||
|
||||
func MakeInstanceFromPath(path string) (*Instance, error) {
|
||||
config, err := LoadConfigFromPath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return makeInstance(config, path)
|
||||
}
|
||||
|
||||
func makeInstance(config *Config, source string) (*Instance, error) {
|
||||
relay := khatru.NewRelay()
|
||||
|
||||
@@ -268,9 +277,8 @@ func (instance *Instance) StoreEvent(ctx context.Context, event nostr.Event) err
|
||||
return instance.Events.StoreEvent(event)
|
||||
}
|
||||
|
||||
func (instance *Instance) ReplaceEvent(ctx context.Context, event nostr.Event) error {
|
||||
_, err := instance.Events.ReplaceEvent(event)
|
||||
return err
|
||||
func (instance *Instance) ReplaceEvent(ctx context.Context, event nostr.Event) ([]nostr.Event, error) {
|
||||
return instance.Events.ReplaceEvent(event)
|
||||
}
|
||||
|
||||
func (instance *Instance) DeleteEvent(ctx context.Context, id nostr.ID) error {
|
||||
|
||||
@@ -27,7 +27,7 @@ func createTestInstance() *Instance {
|
||||
|
||||
schema := &Schema{Name: "test_" + RandomString(8)}
|
||||
|
||||
relay := khatru.NewRelay()
|
||||
relay := &khatru.Relay{}
|
||||
|
||||
events := &EventStore{
|
||||
Relay: relay,
|
||||
|
||||
+11
-4
@@ -28,6 +28,15 @@ func Dispatch(hostname string) (*Instance, bool) {
|
||||
return instance, exists
|
||||
}
|
||||
|
||||
func cleanupIfInactive(instance *Instance) bool {
|
||||
if instance != nil && instance.Config != nil && instance.Config.Inactive {
|
||||
instance.Cleanup()
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func Start() {
|
||||
dataDir := Env("DATA")
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
@@ -63,8 +72,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()
|
||||
} else if cleanupIfInactive(instance) {
|
||||
log.Printf("Skipped inactive %s", entry.Name())
|
||||
} else {
|
||||
instancesByHost[instance.Config.Host] = instance
|
||||
@@ -111,8 +119,7 @@ func Start() {
|
||||
instance, err := MakeInstance(filename)
|
||||
if err != nil {
|
||||
log.Printf("Failed to reload %s: %v", filename, err)
|
||||
} else if instance.Config.Inactive {
|
||||
instance.Cleanup()
|
||||
} else if cleanupIfInactive(instance) {
|
||||
log.Printf("Skipped inactive %s", filename)
|
||||
} else {
|
||||
instancesByHost[instance.Config.Host] = instance
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -13,7 +13,7 @@ func createTestManagementStore() *ManagementStore {
|
||||
secret: nostr.Generate(),
|
||||
}
|
||||
schema := &Schema{Name: "test_" + RandomString(8)}
|
||||
relay := khatru.NewRelay()
|
||||
relay := &khatru.Relay{}
|
||||
events := &EventStore{
|
||||
Relay: relay,
|
||||
Config: config,
|
||||
|
||||
Reference in New Issue
Block a user