relay29

package module
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2024 License: MIT Imports: 14 Imported by: 3

README

= relay29 image:https://pkg.go.dev/badge/github.com/fiatjaf/relay29.svg[link=https://pkg.go.dev/github.com/fiatjaf/relay29]

NIP-29 requires the relays to have more of an active role in making groups work with the rules, so this is a library for creating NIP-29 relays, works with https://github.com/fiatjaf/khatru[khatru] using the https://pkg.go.dev/github.com/fiatjaf/relay29/khatru29[khatru29] wrapper, https://github.com/hoytech/strfry[strfry] with link:strfry29[strfry29] and https://github.com/fiatjaf/relayer[relayer] with link:relayer29[relayer29].

CAUTION: This is probably broken so please don't trust it for anything serious and be prepared to delete your database.

[source,go]
----
package main

import (
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/fiatjaf/eventstore/slicestore"
	"github.com/fiatjaf/khatru/policies"
	"github.com/fiatjaf/relay29"
	"github.com/fiatjaf/relay29/khatru29"
	"github.com/nbd-wtf/go-nostr"
)

var (
	adminRole     = &nip29.Role{Name: "admin", Description: "the group's max top admin"}
	moderatorRole = &nip29.Role{Name: "moderator", Description: "the person who cleans up unwanted stuff"}
)

func main() {
	relayPrivateKey := nostr.GeneratePrivateKey()

	db := &slicestore.SliceStore{} // this only keeps things in memory, use a different eventstore in production
	db.Init()

	relay, state := khatru29.Init(relay29.Options{
		Domain:    "localhost:2929",
		DB:        db,
		SecretKey: relayPrivateKey,
		DefaultRoles:            []*nip29.Role{adminRole, moderatorRole},
		GroupCreatorDefaultRole: adminRole,
	})

	// setup group-related restrictions
	state.AllowAction = func(ctx context.Context, group nip29.Group, role *nip29.Role, action relay29.Action) bool {
		// this is simple:
		if _, ok := action.(relay29.PutUser); ok {
			// anyone can invite new users
			return true
		}
		if role == adminRole {
			// owners can do everything
			return true
		}
		if role == moderatorRole {
			// admins can delete people and messages
			switch action.(type) {
			case relay29.RemoveUser:
				return true
			case relay29.DeleteEvent:
				return true
			}
		}
		// no one else can do anything else
		return false
	}

	// init relay
	relay.Info.Name = "very ephemeral chat relay"
	relay.Info.Description = "everything will be deleted as soon as I turn off my computer"

	// extra policies
	relay.RejectEvent = append(relay.RejectEvent,
		policies.PreventLargeTags(64),
		policies.PreventTooManyIndexableTags(6, []int{9005}, nil),
		policies.RestrictToSpecifiedKinds(
			9, 10, 11, 12,
			30023, 31922, 31923, 9802,
			9000, 9001, 9002, 9003, 9004, 9005, 9006, 9007,
			9021,
		),
		policies.PreventTimestampsInThePast(60 * time.Second),
		policies.PreventTimestampsInTheFuture(30 * time.Second),
	)

	// http routes
	relay.Router().HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "nothing to see here, you must use a nip-29 powered client")
	})

	fmt.Println("running on http://0.0.0.0:2929")
	if err := http.ListenAndServe(":2929", relay); err != nil {
		log.Fatal("failed to serve")
	}
}
----

== How to use

Basically you just call `khatru29.Init()` and then you get back a `khatru.Relay` and a `relay29.State` instances. The state has inside it also a map of `Group` objects that you can read but you should not modify manually. To modify these groups you must write moderation events with the `.AddEvent()` method of the `Relay`. This API may be improved later.

See link:examples/groups.fiatjaf.com/main.go[] for a (not very much) more complex example.

== How it works

What this library does is basically:
- it keeps a list of of groups with metadata in memory (not the messages);
- it checks a bunch of stuff for every event and filter received;
- it acts on moderation events and on join-request events received and modify the group state;
- it generates group metadata events (39000, 39001, 39002, 39003) events on the fly (these are not stored) and returns them to whoever queries them;
- on startup it loads all the moderation events (9000, 9001, etc) from the database and rebuilds the group state from that (so if you want to modify the group state permanently you must publish one of these events to the relay — but of course you can also monkey-patch the map of groups in memory like an animal if you want);

Documentation

Index

Constants

This section is empty.

Variables

View Source
var PTagNotValidPublicKey = fmt.Errorf("'p' tag value is not a valid public key")

Functions

func GetGroupIDFromEvent

func GetGroupIDFromEvent(event *nostr.Event) string

func IsInternalCall added in v0.5.0

func IsInternalCall(ctx context.Context) bool

Types

type Action added in v0.4.0

type Action interface {
	Apply(group *nip29.Group)
	Name() string
}

func PrepareModerationAction added in v0.4.0

func PrepareModerationAction(evt *nostr.Event) (Action, error)

type CreateGroup added in v0.4.0

type CreateGroup struct {
	Creator string
	When    nostr.Timestamp
}

func (CreateGroup) Apply added in v0.4.0

func (a CreateGroup) Apply(group *nip29.Group)

func (CreateGroup) Name added in v0.5.0

func (_ CreateGroup) Name() string

type DeleteEvent added in v0.4.0

type DeleteEvent struct {
	Targets []string
}

func (DeleteEvent) Apply added in v0.4.0

func (a DeleteEvent) Apply(group *nip29.Group)

func (DeleteEvent) Name added in v0.5.0

func (_ DeleteEvent) Name() string

type DeleteGroup added in v0.4.0

type DeleteGroup struct {
	When nostr.Timestamp
}

func (DeleteGroup) Apply added in v0.4.0

func (a DeleteGroup) Apply(group *nip29.Group)

func (DeleteGroup) Name added in v0.5.0

func (_ DeleteGroup) Name() string

type EditMetadata added in v0.4.0

type EditMetadata struct {
	NameValue    *string
	PictureValue *string
	AboutValue   *string
	PrivateValue *bool
	ClosedValue  *bool
	When         nostr.Timestamp
}

func (EditMetadata) Apply added in v0.4.0

func (a EditMetadata) Apply(group *nip29.Group)

func (EditMetadata) Name added in v0.5.0

func (_ EditMetadata) Name() string

type Group

type Group struct {
	nip29.Group
	// contains filtered or unexported fields
}

type Options

type Options struct {
	Domain                  string
	DB                      eventstore.Store
	SecretKey               string
	DefaultRoles            []*nip29.Role
	GroupCreatorDefaultRole *nip29.Role
}

type PubKeyRoles added in v0.5.0

type PubKeyRoles struct {
	PubKey    string
	RoleNames []string
}

type PutUser added in v0.5.0

type PutUser struct {
	Targets []PubKeyRoles
	When    nostr.Timestamp
}

func (PutUser) Apply added in v0.5.0

func (a PutUser) Apply(group *nip29.Group)

func (PutUser) Name added in v0.5.0

func (_ PutUser) Name() string

type RemoveUser added in v0.4.0

type RemoveUser struct {
	Targets []string
	When    nostr.Timestamp
}

func (RemoveUser) Apply added in v0.4.0

func (a RemoveUser) Apply(group *nip29.Group)

func (RemoveUser) Name added in v0.5.0

func (_ RemoveUser) Name() string

type State

type State struct {
	Domain string
	Groups *xsync.MapOf[string, *Group]
	DB     eventstore.Store
	Relay  interface {
		BroadcastEvent(*nostr.Event)
		AddEvent(context.Context, *nostr.Event) (skipBroadcast bool, writeError error)
	}
	GetAuthed func(context.Context) string

	AllowPrivateGroups bool

	AllowAction func(ctx context.Context, group nip29.Group, role *nip29.Role, action Action) bool
	// contains filtered or unexported fields
}

func New added in v0.3.0

func New(opts Options) *State

func (*State) AdminsQueryHandler added in v0.3.0

func (s *State) AdminsQueryHandler(ctx context.Context, filter nostr.Filter) (chan *nostr.Event, error)

func (*State) ApplyModerationAction added in v0.3.0

func (s *State) ApplyModerationAction(ctx context.Context, event *nostr.Event)

func (*State) CreateGroup added in v0.5.0

func (s *State) CreateGroup(ctx context.Context, groupId string, creator string, defs EditMetadata) error

func (*State) DeleteEvent added in v0.5.0

func (s *State) DeleteEvent(ctx context.Context, groupId string, eventId string) error

func (*State) GetGroupFromEvent

func (s *State) GetGroupFromEvent(event *nostr.Event) *Group

func (*State) MembersQueryHandler added in v0.3.0

func (s *State) MembersQueryHandler(ctx context.Context, filter nostr.Filter) (chan *nostr.Event, error)

func (*State) MetadataQueryHandler added in v0.3.0

func (s *State) MetadataQueryHandler(ctx context.Context, filter nostr.Filter) (chan *nostr.Event, error)

func (*State) NewGroup

func (s *State) NewGroup(id string, creator string) *Group

NewGroup creates a new group from scratch (but doesn't store it in the groups map)

func (*State) NormalEventQuery added in v0.3.0

func (s *State) NormalEventQuery(ctx context.Context, filter nostr.Filter) (chan *nostr.Event, error)

func (*State) PreventWritingOfEventsJustDeleted added in v0.3.0

func (s *State) PreventWritingOfEventsJustDeleted(ctx context.Context, event *nostr.Event) (reject bool, msg string)

func (*State) PutUser added in v0.5.0

func (s *State) PutUser(ctx context.Context, groupId string, pubkey string, roles ...string) error

func (*State) ReactToJoinRequest added in v0.3.0

func (s *State) ReactToJoinRequest(ctx context.Context, event *nostr.Event)

func (*State) ReactToLeaveRequest added in v0.4.0

func (s *State) ReactToLeaveRequest(ctx context.Context, event *nostr.Event)

func (*State) RemoveUserFromGroup added in v0.5.0

func (s *State) RemoveUserFromGroup(ctx context.Context, groupId string, pubkey string) error

func (*State) RequireHTagForExistingGroup added in v0.3.0

func (s *State) RequireHTagForExistingGroup(ctx context.Context, event *nostr.Event) (reject bool, msg string)

func (*State) RequireKindAndSingleGroupIDOrSpecificEventReference added in v0.3.0

func (s *State) RequireKindAndSingleGroupIDOrSpecificEventReference(ctx context.Context, filter nostr.Filter) (reject bool, msg string)

func (*State) RequireModerationEventsToBeRecent added in v0.3.0

func (s *State) RequireModerationEventsToBeRecent(ctx context.Context, event *nostr.Event) (reject bool, msg string)

func (*State) RestrictInvalidModerationActions added in v0.3.0

func (s *State) RestrictInvalidModerationActions(ctx context.Context, event *nostr.Event) (reject bool, msg string)

func (*State) RestrictWritesBasedOnGroupRules added in v0.3.0

func (s *State) RestrictWritesBasedOnGroupRules(ctx context.Context, event *nostr.Event) (reject bool, msg string)

func (*State) RolesQueryHandler added in v0.5.0

func (s *State) RolesQueryHandler(ctx context.Context, filter nostr.Filter) (chan *nostr.Event, error)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL