Files
realy/openapi/http-relay.go
2025-06-24 18:39:32 +01:00

71 lines
1.9 KiB
Go

package openapi
import (
"bytes"
"net/http"
"github.com/danielgtaylor/huma/v2"
"realy.lol/chk"
"realy.lol/context"
"realy.lol/event"
"realy.lol/log"
"realy.lol/publish"
"realy.lol/realy/helpers"
)
// RelayInput is the parameters for the Event HTTP API method.
type RelayInput struct {
Auth string `header:"Authorization" doc:"nostr nip-98 (and expiring variant)" required:"false"`
RawBody []byte
}
// RelayOutput is the return parameters for the HTTP API Relay method.
type RelayOutput struct{ Body string }
// RegisterRelay is the implementatino of the HTTP API Relay method.
func (x *Operations) RegisterRelay(api huma.API) {
name := "Relay"
description := "relay an event, don't store it"
path := x.path + "/relay"
scopes := []string{"user"}
method := http.MethodPost
huma.Register(api, huma.Operation{
OperationID: name,
Summary: name,
Path: path,
Method: method,
Tags: []string{"events"},
Description: helpers.GenerateDescription(description, scopes),
Security: []map[string][]string{{"auth": scopes}},
}, func(ctx context.T, input *RelayInput) (output *RelayOutput, err error) {
log.I.S(input)
r := ctx.Value("http-request").(*http.Request)
remote := helpers.GetRemoteFromReq(r)
var ok bool
ev := &event.T{}
if _, err = ev.Unmarshal(input.RawBody); chk.E(err) {
err = huma.Error406NotAcceptable(err.Error())
return
}
accept, notice, _ := x.AcceptEvent(ctx, ev, r, remote)
if !accept {
err = huma.Error401Unauthorized(notice)
return
}
if !bytes.Equal(ev.GetIDBytes(), ev.Id) {
err = huma.Error400BadRequest("event id is computed incorrectly")
return
}
if ok, err = ev.Verify(); chk.T(err) {
err = huma.Error400BadRequest("failed to verify signature")
return
} else if !ok {
err = huma.Error400BadRequest("signature is invalid")
return
}
publish.P.Deliver(ev)
return
})
}