kolo docsbeta

Step 4: Invite someone to a group

Add invites to the chat: the owner creates an invite with an expiry, a number of uses and approval, and the other person joins with the code and receives the conversation key through it.

On this page

In the previous step you kept messages for offline peers. Now you add invites, so the owner can bring someone into the conversation without sending the conversation key anywhere in the clear.

The owner creates an invite with an expiry, a number of uses and, if wanted, an approval step. The other person pastes the code, the owner approves, and the app of the new member receives the conversation key and the pin settings inside the answer, encrypted for that person alone. An expired, used up, denied or revoked invite fails with a clear sentence.

This step is backend only: you paste the Go code below into the project of the previous step. The window of this step, with its invite panel, is already built, and you bring it in with one command.

1Check what you need

You need what step 3 needed: Go 1.26 or newer, Node.js, wails3, openssl, the bootstrap node and a local pin. Start from the project you finished in step 3.

2Bring the window and the library

The window of this step has a panel to create invites, one to join with a code, and the requests that wait for an answer. It is already built: bring it from the tag step-4. Then add kolo-invite, which makes and answers the invites. The tag also holds the finished version of every file below, in case you want to compare yours with it.

Terminal
git fetch origin --tags
git checkout step-4 -- frontend
Terminal
go get github.com/ciranda-dev/kolo-invite@v0.1.0

3Let the conversation come from an invite

An owner still starts with a conversation key and a pin, as in step 3. A joiner starts with neither: it gets them from the invite. So the settings now accept a start without a key, and say plainly when only half of the pair is given.

In config.go, replace Config with:

config.go
// Config is everything the chat needs from outside. A zero field takes its default, if it has one.
// LoadConfig fills it from flags and environment variables.
type Config struct {
	DataDir         string        // -data, KOLO_CHAT_DATA: identity, Pebble store, members. Default: <user config dir>/kolo-chat
	Bootstrap       string        // -bootstrap, KOLO_CHAT_BOOTSTRAP: IP:PORT of a bootstrap node. Default 127.0.0.1:4000
	Listen          string        // -listen, KOLO_CHAT_LISTEN: local IP:PORT. Default 127.0.0.1:0
	ConversationKey string        // -conversation-key, KOLO_CHAT_CONVERSATION_KEY: 64 hex characters (32 bytes). Empty for someone who joins with an invite
	PinAddr         string        // -pin, KOLO_CHAT_PIN: IP:PORT of the pin. Default 127.0.0.1:7450. Used with a conversation key; a joiner gets the pin from the invite
	PinKey          string        // -pin-key, KOLO_CHAT_PIN_KEY: the pin's public key in hex (`kolo-pin id`). Required with a conversation key
	PinToken        string        // -pin-token, KOLO_CHAT_PIN_TOKEN: a capability in hex, issued by this app's identity. Default: the app issues one
	PinTTL          time.Duration // -pin-ttl, KOLO_CHAT_PIN_TTL: lifetime of the capability the app issues. Default 720h
	PinQuota        uint64        // -pin-quota, KOLO_CHAT_PIN_QUOTA: bytes the pin may keep for you, in the capability the app issues. Default 16777216
	LookupInterval  time.Duration // -lookup-interval, KOLO_CHAT_LOOKUP_INTERVAL: time between topic lookups. Default 5s
}

In config.go, replace LoadConfig with:

config.go
// LoadConfig reads the flags in args. A setting that is not given as a flag comes from its environment variable
// (read with getenv, such as os.Getenv), and a flag wins over its variable.
func LoadConfig(args []string, getenv func(string) string, stderr io.Writer) (Config, error) {
	var c Config
	fs := flag.NewFlagSet("kolo-chat", flag.ContinueOnError)
	fs.SetOutput(stderr)
	text := func(p *string) func(string) error {
		return func(v string) error { *p = v; return nil }
	}
	dur := func(p *time.Duration) func(string) error {
		return func(v string) (err error) { *p, err = time.ParseDuration(v); return err }
	}
	num := func(p *uint64) func(string) error {
		return func(v string) (err error) { *p, err = strconv.ParseUint(v, 10, 64); return err }
	}
	for _, s := range []struct {
		name, env, help string
		set             func(string) error
	}{
		{"data", "KOLO_CHAT_DATA", "data directory (default <user config dir>/kolo-chat)", text(&c.DataDir)},
		{"bootstrap", "KOLO_CHAT_BOOTSTRAP", "IP:PORT of the bootstrap node (default " + defaultBootstrap + ")", text(&c.Bootstrap)},
		{"listen", "KOLO_CHAT_LISTEN", "local IP:PORT to listen on (default " + defaultListen + ")", text(&c.Listen)},
		{"conversation-key", "KOLO_CHAT_CONVERSATION_KEY", "32-byte key of the conversation, in hex (leave it out to join with an invite)", text(&c.ConversationKey)},
		{"pin", "KOLO_CHAT_PIN", "IP:PORT of the pin (default " + defaultPinAddr + ")", text(&c.PinAddr)},
		{"pin-key", "KOLO_CHAT_PIN_KEY", "public key of the pin, in hex (required with -conversation-key)", text(&c.PinKey)},
		{"pin-token", "KOLO_CHAT_PIN_TOKEN", "capability for the pin, in hex (default: issued by the app)", text(&c.PinToken)},
		{"pin-ttl", "KOLO_CHAT_PIN_TTL", "lifetime of the capability the app issues (default 720h)", dur(&c.PinTTL)},
		{"pin-quota", "KOLO_CHAT_PIN_QUOTA", "bytes the pin may keep for you (default 16777216)", num(&c.PinQuota)},
		{"lookup-interval", "KOLO_CHAT_LOOKUP_INTERVAL", "time between lookups of the topic (default 5s)", dur(&c.LookupInterval)},
	} {
		if v := getenv(s.env); v != "" {
			if err := s.set(v); err != nil {
				return c, &ConfigError{Setting: s.name, Err: fmt.Errorf("%w: %s: %w", ErrMalformed, s.env, err)}
			}
		}
		fs.Func(s.name, s.help+" ("+s.env+")", s.set)
	}
	return c, fs.Parse(args)
}

In config.go, replace settings with:

config.go
// settings is a Config after defaults and checks: values the code can use as they are.
type settings struct {
	Config
	conversationKey [32]byte
	pinKey          ed25519.PublicKey
	token           []byte // nil: the app issues one
	bootstrap       netip.AddrPort
	inConversation  bool // the key and the pin are known: from the configuration, or later from an invite
}

In config.go, replace resolve with:

config.go
// resolve applies the defaults and checks every setting, returning a *ConfigError for the first bad one.
// Without a conversation key the chat starts as a joiner: the key and the pin come from an invite (see
// useConversation), so the pin settings are refused rather than ignored. A token is checked later, in
// capability, because it needs the identity.
func (c Config) resolve() (settings, error) {
	s := settings{Config: c}
	if s.DataDir == "" {
		dir, err := os.UserConfigDir()
		if err != nil {
			return s, &ConfigError{Setting: "data", Err: fmt.Errorf("%w: no user config directory: %w", ErrMissing, err)}
		}
		s.DataDir = filepath.Join(dir, "kolo-chat")
	}
	s.Bootstrap = orDefault(s.Bootstrap, defaultBootstrap)
	s.Listen = orDefault(s.Listen, defaultListen)
	s.PinAddr = orDefault(s.PinAddr, defaultPinAddr)
	if s.PinTTL == 0 {
		s.PinTTL = defaultPinTTL
	}
	if s.PinQuota == 0 {
		s.PinQuota = defaultPinQuota
	}
	if s.LookupInterval == 0 {
		s.LookupInterval = defaultLookupInterval
	}

	boot, err := netip.ParseAddrPort(s.Bootstrap)
	if err != nil {
		return s, &ConfigError{Setting: "bootstrap", Err: fmt.Errorf("%w: %w", ErrMalformed, err)}
	}
	s.bootstrap = boot
	if _, err := netip.ParseAddrPort(s.PinAddr); err != nil {
		return s, &ConfigError{Setting: "pin", Err: fmt.Errorf("%w: %w", ErrMalformed, err)}
	}
	if c.ConversationKey == "" && (c.PinKey != "" || c.PinToken != "") {
		return s, &ConfigError{Setting: "conversation-key", Err: ErrMissing}
	}
	if c.ConversationKey == "" {
		return s, nil
	}
	if err := parseHex("conversation-key", c.ConversationKey, s.conversationKey[:]); err != nil {
		return s, err
	}
	s.inConversation = true
	s.pinKey = make(ed25519.PublicKey, ed25519.PublicKeySize)
	if err := parseHex("pin-key", c.PinKey, s.pinKey); err != nil {
		return s, err
	}
	if c.PinToken != "" {
		if s.token, err = hex.DecodeString(c.PinToken); err != nil {
			return s, &ConfigError{Setting: "pin-token", Err: fmt.Errorf("%w: %w", ErrMalformed, err)}
		}
	}
	return s, nil
}

Add to config.go:

config.go
// useConversation takes the key and the pin from an invite, or from the file that kept them.
func (s *settings) useConversation(conv conversation) {
	copy(s.conversationKey[:], conv.Key)
	s.pinKey = ed25519.PublicKey(conv.PinKey)
	s.PinAddr = conv.PinAddr
	s.inConversation = true
}

4Decide what an invite carries

The owner chooses how long an invite lives, how many people can use it and whether it needs approval. What the new member receives is the grant: the invite encrypts it for the joiner alone, and nothing else in the app carries the conversation key. It holds the key, the pin address and public key, and the owner's signed log header, which is what the new member needs to meet the owner and read its log from the pin. It holds no pin token: a capability is signed by the owner of a log and covers that log only, so the new member issues its own, as in step 3. Refusals come back as an InviteError, with a sentence for the window and the error of kolo-invite as its cause.

Create invite.go with:

invite.go
import (
	"context"
	"crypto/ed25519"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"log"
	"net/netip"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"time"

	invite "github.com/ciranda-dev/kolo-invite"
	kololog "github.com/ciranda-dev/kolo-log"
	kolostore "github.com/ciranda-dev/kolo-store"
	koloswarm "github.com/ciranda-dev/kolo-swarm"
)

Add to invite.go:

invite.go
// Bounds of an invite, and how long Join waits.
const (
	grantVersion      = 1
	defaultInviteTTL  = 24 * time.Hour
	maxInviteTTL      = 30 * 24 * time.Hour
	maxInviteUses     = 100
	maxActiveInvites  = 16 // every active invite takes a topic of the swarm, see openInvites
	swarmTopics       = 32 // kolo-swarm's largest MaxTopics: the conversation's topic and the invites'
	joinFindTimeout   = 60 * time.Second
	joinAnswerTimeout = 10 * time.Minute
)

// InviteOptions is what the owner chooses for a new invite. A zero TTLSeconds is one day, a zero Uses is one.
type InviteOptions struct {
	TTLSeconds      int64 `json:"ttlSeconds"`
	Uses            int   `json:"uses"`
	RequireApproval bool  `json:"requireApproval"`
}

// InviteInfo describes an invite for the window. Code is the invite's secret: only the answer of CreateInvite
// has it, since kolo-invite does not give a code back later.
type InviteInfo struct {
	ID              string `json:"id"`
	Code            string `json:"code,omitempty"`
	Expires         string `json:"expires"` // RFC 3339
	Uses            int    `json:"uses"`
	Used            int    `json:"used"`
	RequireApproval bool   `json:"requireApproval"`
	State           string `json:"state"` // "active", "expired", "used up" or "revoked"
}

// InviteRequest is the payload of the "chat:invite-request" event: Joiner (a kolo-id) asks to join through a
// invite that needs approval. Withdrawn says the request is gone, because the joiner left or the invite ended.
type InviteRequest struct {
	Request   uint64 `json:"request"`
	Invite    string `json:"invite"`
	Joiner    string `json:"joiner"`
	Withdrawn bool   `json:"withdrawn"`
}

// JoinStatus is the payload of the "chat:join" event. Status is "joining", "waiting" (for the owner's answer),
// "joined" or "failed", and Message is the sentence to show.
type JoinStatus struct {
	Status  string `json:"status"`
	Message string `json:"message"`
}

// InviteError is an error of the invite flow. Message is the sentence the window shows, and Err the cause, one
// of the errors of kolo-invite.
type InviteError struct {
	Message string
	Err     error
}

func (e *InviteError) Error() string { return e.Message }
func (e *InviteError) Unwrap() error { return e.Err }

// ErrNotInConversation is returned by what needs a conversation before the user has joined one.
var ErrNotInConversation = errors.New("Join a conversation first: paste an invite code.")

// conversation is what makes a member: the key, and where the pin is. It is kept in conversation.json.
type conversation struct {
	Key     []byte `json:"key"`
	PinAddr string `json:"pinAddr"`
	PinKey  []byte `json:"pinKey"`
}

// grant is the payload of an accept. The invite encrypts it for the joiner alone (HPKE), and nothing else
// carries the conversation key. Header is the owner's signed log header, with its key and log ID: what the
// joiner needs to meet the owner and read its log from the pin. There is no pin token in it: a capability is
// signed by the owner of a log and covers that log only, so the joiner issues its own (see capability).
type grant struct {
	Version int `json:"v"`
	conversation
	Header []byte `json:"header"`
}

// check says whether the conversation is complete: a key, and a pin that can be dialed.
func (v conversation) check() error {
	if len(v.Key) != 32 || len(v.PinKey) != ed25519.PublicKeySize {
		return errors.New("wrong key size")
	}
	_, err := netip.ParseAddrPort(v.PinAddr)
	return err
}

5Create, answer and revoke invites

Create of kolo-invite returns the code. An invite that does not need approval carries the grant from the start; one that needs approval gets it when the owner approves. Every active invite takes a topic of the swarm, so the app limits how many can be active. A second loop reports what happens to the invites and meets the people that join. When a request comes, the joiner has sent its own log header with it: a request without one is refused, and a good one is shown to the owner's window. The owner approves or denies, and revoking an invite stops it at once, even if it still has uses and time left.

Add to invite.go:

invite.go
// openInvites opens the inviter, which keeps its invites in a store of its own, and runs what it needs next to
// the swarm: Announce, which joins the topic of every live invite, and the loop of its events. The swarm has
// room for the conversation's topic and for maxActiveInvites invites.
func (c *ChatService) openInvites() (err error) {
	if c.invDB, err = kolostore.OpenPebble(filepath.Join(c.set.DataDir, "invites")); err != nil {
		return err
	}
	if c.inv, err = invite.Open(c.invDB, c.id, nil); err != nil {
		return err
	}
	c.requests = map[invite.RequestID]invite.Event{}
	c.wg.Go(func() {
		if err := c.inv.Announce(c.ctx, c.sw); err != nil && c.ctx.Err() == nil && !errors.Is(err, invite.ErrClosed) {
			log.Print("invite announce: ", err)
		}
	})
	c.wg.Go(c.inviteLoop)
	return nil
}

// CreateInvite makes an invite for the conversation and returns it with its code, which the owner gives to the
// person to invite. Without RequireApproval the first joiners to use it are accepted at once, up to Uses.
func (c *ChatService) CreateInvite(opts InviteOptions) (InviteInfo, error) {
	if c.inv == nil {
		return InviteInfo{}, errors.New("not started")
	}
	if !c.isActive() {
		return InviteInfo{}, ErrNotInConversation
	}
	create := invite.CreateOptions{TTL: defaultInviteTTL, MaxUses: max(opts.Uses, 1), Manual: opts.RequireApproval}
	if opts.TTLSeconds != 0 {
		create.TTL = time.Duration(opts.TTLSeconds) * time.Second
	}
	if create.TTL < time.Second || create.TTL > maxInviteTTL || create.MaxUses > maxInviteUses {
		return InviteInfo{}, fmt.Errorf("An invite lasts from 1 second to %d days and takes 1 to %d uses.", maxInviteTTL/(24*time.Hour), maxInviteUses)
	}
	infos, err := c.inv.List()
	if err != nil {
		return InviteInfo{}, err
	}
	if n := countActive(infos); n >= maxActiveInvites {
		return InviteInfo{}, fmt.Errorf("You have %d active invites. Revoke one, or wait for one to expire.", n)
	}
	if !create.Manual { // an invite that needs approval takes its payload in Approve
		if create.Payload, err = c.grantPayload(); err != nil {
			return InviteInfo{}, err
		}
	}
	code, info, err := c.inv.Create(&create)
	if err != nil {
		return InviteInfo{}, err
	}
	out := inviteInfo(info)
	out.Code = code
	return out, nil
}

// Invites lists the invites, oldest first, ended ones included. It has no codes.
func (c *ChatService) Invites() ([]InviteInfo, error) {
	if c.inv == nil {
		return nil, errors.New("not started")
	}
	infos, err := c.inv.List()
	out := make([]InviteInfo, len(infos))
	for i, info := range infos {
		out[i] = inviteInfo(info)
	}
	return out, err
}

// Revoke ends an invite: a joiner that uses its code from now on is refused, and the requests that wait for an
// answer are refused too. Members that joined stay.
func (c *ChatService) Revoke(id string) error {
	if c.inv == nil {
		return errors.New("not started")
	}
	var inviteID invite.ID
	b, err := hex.DecodeString(id)
	if err != nil || len(b) != len(inviteID) {
		return errors.New("That is not an invite ID.")
	}
	copy(inviteID[:], b)
	return ownerError(c.inv.Revoke(inviteID))
}

// Approve lets in the person behind a request, giving it the conversation through the invite. Deny refuses it.
func (c *ChatService) Approve(request uint64) error {
	payload, err := c.grantPayload()
	if err != nil {
		return err
	}
	return ownerError(c.answer(request, func(id invite.RequestID) error { return c.inv.Approve(id, payload) }))
}

func (c *ChatService) Deny(request uint64) error {
	return ownerError(c.answer(request, func(id invite.RequestID) error { return c.inv.Deny(id) }))
}

func (c *ChatService) answer(request uint64, do func(invite.RequestID) error) error {
	if c.inv == nil {
		return errors.New("not started")
	}
	id := invite.RequestID(request)
	err := do(id)
	if err == nil || errors.Is(err, invite.ErrNotFound) || errors.Is(err, invite.ErrExpired) ||
		errors.Is(err, invite.ErrUsedUp) || errors.Is(err, invite.ErrRevoked) {
		c.mu.Lock()
		delete(c.requests, id) // the request is over, however it ended
		c.mu.Unlock()
		c.emit("chat:invite-request", InviteRequest{Request: request, Withdrawn: true})
	}
	return err
}

// grantPayload is what an accept carries: the conversation, and our signed log header.
func (c *ChatService) grantPayload() ([]byte, error) {
	if !c.isActive() {
		return nil, ErrNotInConversation
	}
	return json.Marshal(grant{
		Version: grantVersion,
		conversation: conversation{
			Key:     c.set.conversationKey[:],
			PinAddr: c.set.PinAddr,
			PinKey:  c.set.pinKey,
		},
		Header: c.log.Header().Encode(),
	})
}

// inviteLoop reports to the window what happens to the invites, and meets the people that join.
func (c *ChatService) inviteLoop() {
	for {
		ev, err := c.inv.Next(c.ctx)
		if err != nil {
			if c.ctx.Err() == nil && !errors.Is(err, invite.ErrClosed) {
				log.Print("invite events: ", err)
			}
			return
		}
		switch ev.Kind {
		case invite.Requested:
			c.onRequested(ev)
		case invite.Withdrawn:
			c.mu.Lock()
			delete(c.requests, ev.Request)
			c.mu.Unlock()
			c.emit("chat:invite-request", InviteRequest{Request: uint64(ev.Request), Invite: ev.Invite.String(), Joiner: hex.EncodeToString(ev.Joiner), Withdrawn: true})
		case invite.Joined:
			c.onJoined(ev)
		case invite.Ended:
			c.emitInvite(ev.Invite)
		}
	}
}

// onRequested shows the window a request that needs an answer. The joiner sends its signed log header as join
// data, so a request without one is refused.
func (c *ChatService) onRequested(ev invite.Event) {
	if _, err := joinerHeader(ev.Joiner, ev.Data); err != nil {
		log.Print("invite request refused: ", err)
		if err := c.inv.Deny(ev.Request); err != nil {
			log.Print("invite deny: ", err)
		}
		return
	}
	c.mu.Lock()
	c.requests[ev.Request] = ev
	c.mu.Unlock()
	c.emit("chat:invite-request", InviteRequest{Request: uint64(ev.Request), Invite: ev.Invite.String(), Joiner: hex.EncodeToString(ev.Joiner)})
}

// onJoined registers the person that joined as a member, from the log header it sent, so we may read its log and
// give it ours before its first hello. The hello registers it too, so a lost event costs nothing.
func (c *ChatService) onJoined(ev invite.Event) {
	c.mu.Lock()
	delete(c.requests, ev.Request)
	c.mu.Unlock()
	header, err := joinerHeader(ev.Joiner, ev.Data)
	if err == nil {
		err = c.addMember(ev.Joiner, header)
	}
	if err != nil {
		log.Print("invite joiner: ", err)
	}
	log.Print("member joined: ", hex.EncodeToString(ev.Joiner)[:8])
	c.emitInvite(ev.Invite)
}

func (c *ChatService) emitInvite(id invite.ID) {
	infos, err := c.inv.List()
	if err != nil {
		return
	}
	for _, info := range infos {
		if info.ID == id {
			c.emit("chat:invite", inviteInfo(info))
		}
	}
}

// joinerHeader returns the signed log header a joiner sent as its join data, if it is the joiner's own.
func joinerHeader(joiner ed25519.PublicKey, data []byte) ([]byte, error) {
	h, err := kololog.DecodeLogHeader(data)
	if err == nil {
		err = kololog.VerifyLogHeader(joiner, h)
	}
	if err != nil {
		return nil, errors.New("the join data is not the joiner's signed log header")
	}
	return data, nil
}

6Join with the code

The joiner starts without a key and without a pin. It finds the inviter on a topic derived from the code, asks, and waits for the answer. Only when the answer arrives does it leave the invite topic and join the conversation's own topic. The answer is checked before it is used, and saved first, because the payload is the only copy the joiner has. Then the app enters the conversation like an owner does.

Add to invite.go:

invite.go
// joinAttempt is a Join that waits for the connection to the inviter.
type joinAttempt struct {
	code invite.Code
	peer chan *koloswarm.Peer
}

// offerToJoin gives the peer to the Join that waits for it, if the peer is the inviter of its code.
func (c *ChatService) offerToJoin(p *koloswarm.Peer) bool {
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.joining == nil || !c.joining.code.Matches(p.PublicKey()) {
		return false
	}
	select {
	case c.joining.peer <- p:
	default:
	}
	return true
}

// Join uses an invite code: it finds the inviter on the invite's topic, asks to join, and waits for the answer,
// which for an invite that needs approval is a person's. With the answer it takes the conversation key and the
// pin from the payload of the accept, keeps them in the data directory, and joins the conversation like an owner
// that started with them. A refusal comes back as an *InviteError whose Message is the sentence to show and
// whose cause is an error of kolo-invite: ErrDenied, ErrExpired, ErrUsedUp, ErrRevoked, ErrInvalidCode,
// ErrInvalid, ErrUnreachable and the like.
func (c *ChatService) Join(text string) error {
	if c.sw == nil {
		return errors.New("not started")
	}
	err := c.join(strings.TrimSpace(text))
	if err == nil {
		c.emit("chat:join", JoinStatus{Status: "joined", Message: "You joined the conversation."})
		return nil
	}
	var ie *InviteError
	if !errors.As(err, &ie) {
		ie = &InviteError{Message: describeJoin(err), Err: err}
	}
	c.emit("chat:join", JoinStatus{Status: "failed", Message: ie.Message})
	return ie
}

func (c *ChatService) join(text string) error {
	code, err := invite.Parse(text)
	if err != nil {
		return err
	}
	ctx, cancel := context.WithCancel(c.ctx)
	defer cancel()
	att := &joinAttempt{code: code, peer: make(chan *koloswarm.Peer, 1)}
	c.mu.Lock()
	switch {
	case c.active:
		c.mu.Unlock()
		return &InviteError{Message: "You are already in a conversation."}
	case c.joining != nil:
		c.mu.Unlock()
		return &InviteError{Message: "A join is already in progress."}
	}
	c.joining, c.cancelJoin = att, cancel
	c.mu.Unlock()
	left := false
	leave := func() {
		if !left {
			left = true
			c.sw.Leave(code.Topic())
		}
	}
	defer func() {
		leave()
		c.mu.Lock()
		c.joining, c.cancelJoin = nil, nil
		c.mu.Unlock()
	}()

	c.emit("chat:join", JoinStatus{Status: "joining", Message: "Looking for the person who invited you..."})
	if err := c.sw.Join(ctx, code.Topic(), &koloswarm.JoinOptions{Lookup: true}); err != nil {
		return err
	}
	var peer *koloswarm.Peer
	select {
	case peer = <-att.peer:
	case <-time.After(joinFindTimeout):
		return fmt.Errorf("%w: not found in %s", invite.ErrUnreachable, joinFindTimeout)
	case <-ctx.Done():
		return ctx.Err()
	}

	c.emit("chat:join", JoinStatus{Status: "waiting", Message: "Waiting for the invite to be accepted..."})
	actx, acancel := context.WithTimeout(ctx, joinAnswerTimeout)
	defer acancel()
	payload, err := invite.JoinConn(actx, peer.Conn(), c.id, code, &invite.JoinOptions{Data: c.log.Header().Encode()})
	if err != nil {
		return err
	}
	g, err := readGrant(payload, peer.PublicKey())
	if err != nil {
		return err
	}
	leave() // before the conversation's topic: the invite-only connection closes, and the group gets its own
	return c.becomeMember(g, peer.PublicKey())
}

// CancelJoin stops a Join that waits, for the inviter or for its answer.
func (c *ChatService) CancelJoin() {
	c.mu.Lock()
	cancel := c.cancelJoin
	c.mu.Unlock()
	if cancel != nil {
		cancel()
	}
}

// Joined says whether this chat is in a conversation: it started with a conversation key, or joined with an invite.
func (c *ChatService) Joined() bool { return c.isActive() }

func (c *ChatService) isActive() bool {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.active
}

// readGrant checks the payload of an accept, which only the inviter could have made: a conversation that is
// complete, and the inviter's signed log header.
func readGrant(payload []byte, owner ed25519.PublicKey) (g grant, err error) {
	malformed := func(why string) error {
		return fmt.Errorf("%w: the accept payload is %s", invite.ErrProtocol, why)
	}
	if json.Unmarshal(payload, &g) != nil || g.Version != grantVersion {
		return g, malformed("not one this version understands")
	}
	if g.conversation.check() != nil {
		return g, malformed("incomplete")
	}
	if _, err := joinerHeader(owner, g.Header); err != nil {
		return g, malformed("missing the inviter's log header")
	}
	return g, nil
}

// becomeMember keeps the conversation the invite gave and enters it. It is saved first: the payload is the only
// copy the joiner has, and a restart finds it and goes on.
func (c *ChatService) becomeMember(g grant, owner ed25519.PublicKey) error {
	if err := saveConversation(c.set.DataDir, g.conversation); err != nil {
		return err
	}
	if err := c.addMember(owner, g.Header); err != nil {
		return err
	}
	return c.enter(g.conversation)
}

// savedConversation returns the conversation this chat is in at start: the one in the configuration, or the one
// an invite gave earlier. A joiner that has none yet returns false.
func (c *ChatService) savedConversation() (conversation, bool, error) {
	saved, found, err := loadConversation(c.set.DataDir)
	if err != nil {
		return saved, false, err
	}
	if !c.set.inConversation {
		return saved, found, nil
	}
	mine := conversation{Key: slices.Clone(c.set.conversationKey[:]), PinAddr: c.set.PinAddr, PinKey: slices.Clone(c.set.pinKey)}
	if found && !slices.Equal(saved.Key, mine.Key) {
		err := errors.New("is not the conversation this data directory joined with an invite: use another -data")
		return mine, false, &ConfigError{Setting: "conversation-key", Err: err}
	}
	return mine, true, nil
}

func loadConversation(dir string) (v conversation, found bool, err error) {
	data, err := os.ReadFile(filepath.Join(dir, "conversation.json"))
	if errors.Is(err, fs.ErrNotExist) {
		return v, false, nil
	}
	if err != nil {
		return v, false, err
	}
	if err = json.Unmarshal(data, &v); err == nil {
		err = v.check()
	}
	if err != nil {
		return v, false, fmt.Errorf("conversation.json: %w", errors.New("damaged"))
	}
	return v, true, nil
}

// saveConversation writes conversation.json, mode 0600, in one step.
func saveConversation(dir string, v conversation) error {
	data, err := json.Marshal(v)
	if err != nil {
		return err
	}
	tmp := filepath.Join(dir, "conversation.json.tmp")
	if err := os.WriteFile(tmp, data, 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, filepath.Join(dir, "conversation.json"))
}

7Say clearly what went wrong

A denied, expired, used up or revoked invite is not a stack trace. The joiner's window gets one sentence that says what happened and what to do, and the owner gets the same for the invites and requests it manages.

Add to invite.go:

invite.go
func inviteInfo(i invite.Info) InviteInfo {
	out := InviteInfo{ID: i.ID.String(), Uses: i.MaxUses, Used: i.Used, RequireApproval: i.Manual, State: i.State.String()}
	if !i.Expires.IsZero() {
		out.Expires = i.Expires.UTC().Format(time.RFC3339)
	}
	return out
}

func countActive(infos []invite.Info) (n int) {
	for _, i := range infos {
		if i.State == invite.Active {
			n++
		}
	}
	return n
}

// describeJoin turns an error of kolo-invite into the sentence the joiner's window shows.
func describeJoin(err error) string {
	switch {
	case errors.Is(err, context.Canceled):
		return "Joining was cancelled."
	case errors.Is(err, invite.ErrInvalidCode):
		return "That is not an invite code. Paste the whole code, exactly as you received it."
	case errors.Is(err, invite.ErrDenied):
		return "The owner denied your request to join."
	case errors.Is(err, invite.ErrExpired):
		return "This invite has expired. Ask for a new one."
	case errors.Is(err, invite.ErrUsedUp):
		return "This invite has no uses left. Ask for a new one."
	case errors.Is(err, invite.ErrRevoked):
		return "This invite was revoked. Ask for a new one."
	case errors.Is(err, invite.ErrInvalid):
		return "The inviter does not recognize this invite. Check that you pasted the whole code."
	case errors.Is(err, invite.ErrRateLimited):
		return "Too many attempts. Wait a minute and try again."
	case errors.Is(err, invite.ErrBusy):
		return "The inviter is busy. Try again in a moment."
	case errors.Is(err, invite.ErrNotAnswered):
		return "The inviter received your request, but the connection ended before it answered. Try again: asking twice is safe."
	case errors.Is(err, invite.ErrUnreachable):
		return "Could not reach the person who invited you. They must be online with the app open. Try again later."
	case errors.Is(err, invite.ErrTooLarge), errors.Is(err, invite.ErrProtocol):
		return "The inviter sent an answer this app cannot use. Ask for a new invite."
	}
	return "Could not join: " + err.Error()
}

// ownerError turns an error of kolo-invite into the sentence the owner's window shows, and keeps the cause.
func ownerError(err error) error {
	var msg string
	switch {
	case err == nil:
		return nil
	case errors.Is(err, invite.ErrExpired):
		msg = "The invite expired before it was answered."
	case errors.Is(err, invite.ErrUsedUp):
		msg = "The invite has no uses left."
	case errors.Is(err, invite.ErrRevoked):
		msg = "The invite was revoked."
	case errors.Is(err, invite.ErrNotFound):
		msg = "That request or invite is gone: the person left, or the app restarted."
	default:
		return err
	}
	return &InviteError{Message: msg, Err: err}
}

8Wire the invites into the service

The service has to route a connection by what it is for: a peer of the conversation, the inviter that a Join waits for, or a person that has only an invite's topic with us. It also starts the invite loop and can enter a conversation that came from an invite.

In chatservice.go, replace the import block with:

chatservice.go
import (
	"context"
	"crypto/cipher"
	"crypto/ed25519"
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"log"
	"net/netip"
	"os"
	"path/filepath"
	"slices"
	"sync"
	"time"

	koloid "github.com/ciranda-dev/kolo-id"
	invite "github.com/ciranda-dev/kolo-invite"
	kololog "github.com/ciranda-dev/kolo-log"
	kolosecure "github.com/ciranda-dev/kolo-secure"
	kolostore "github.com/ciranda-dev/kolo-store"
	koloswarm "github.com/ciranda-dev/kolo-swarm"
	kolosync "github.com/ciranda-dev/kolo-sync"
	"golang.org/x/crypto/chacha20poly1305"
)

In chatservice.go, replace ChatService with:

chatservice.go
type ChatService struct {
	cfg  Config
	emit func(name string, data any)

	startMu sync.Mutex
	set     settings
	id      *koloid.Identity
	pub     ed25519.PublicKey
	aead    cipher.AEAD
	token   []byte
	store   *kolostore.Store
	log     *kolostore.Log // our own log, the only one we write
	srv     *kolosync.Server
	sw      *koloswarm.Swarm
	ctx     context.Context
	cancel  context.CancelFunc
	wg      sync.WaitGroup
	push    chan struct{}     // a push to the pin is wanted
	pinDone chan struct{}     // closed when the pull from the pin at start is over
	invDB   kolostore.Backend // the invites' own store, used for nothing else
	inv     *invite.Inviter

	mu         sync.Mutex // guards the fields below
	peers      map[string]*koloswarm.Peer
	members    map[string]*member
	replicas   map[string]*kolostore.Replica
	pinned     map[string]uint64 // per author: entries below this index came from the pin
	locked     map[string]int    // per author: entries that wait for a key
	pin        pinState
	active     bool                              // in a conversation: it has its key and its pin
	joining    *joinAttempt                      // the Join that waits for its inviter
	cancelJoin context.CancelFunc                // stops that Join
	requests   map[invite.RequestID]invite.Event // the requests that wait for Approve or Deny

	showMu sync.Mutex // one message is shown at a time, so they keep their order
	pullMu sync.Mutex // one pull at a time, since a replica takes one
	pushMu sync.Mutex // one push at a time
}

In chatservice.go, replace start with:

chatservice.go
func (c *ChatService) start() (err error) {
	if c.set, err = c.cfg.resolve(); err != nil {
		return err
	}
	if err = os.MkdirAll(c.set.DataDir, 0o700); err != nil {
		return err
	}
	if c.id, err = loadIdentity(c.set.DataDir); err != nil {
		return err
	}
	c.pub = c.id.PublicKey()
	backend, err := kolostore.OpenPebble(filepath.Join(c.set.DataDir, "store"))
	if err != nil {
		return err
	}
	c.store = kolostore.New(backend)
	if c.log, err = openOwnLog(c.store, c.id); err != nil {
		return err
	}
	c.peers = map[string]*koloswarm.Peer{}
	c.replicas = map[string]*kolostore.Replica{}
	c.pinned = map[string]uint64{}
	c.locked = map[string]int{}
	if c.members, err = loadMembers(c.set.DataDir); err != nil {
		return err
	}
	c.ctx, c.cancel = context.WithCancel(context.Background())
	c.push = make(chan struct{}, 1)
	swarmCfg := &koloswarm.Config{LookupInterval: c.set.LookupInterval, MaxTopics: swarmTopics}
	if c.sw, err = koloswarm.New(c.ctx, c.set.Listen, c.id, swarmCfg); err != nil {
		return err
	}
	if err = c.sw.Bootstrap(c.ctx, []netip.AddrPort{c.set.bootstrap}); err != nil {
		return err
	}
	log.Print("kolo-id ", c.id.PublicKeyString())

	c.wg.Go(c.swarmLoop)
	if err = c.openInvites(); err != nil {
		return err
	}
	conv, found, err := c.savedConversation() // from the configuration, or from the invite that made us a member
	if err != nil || !found {
		return err // a joiner waits for Join
	}
	return c.enter(conv)
}

Add to chatservice.go:

chatservice.go
// enter makes this chat a member of the conversation: it has the key and the pin, offers its log, pulls from the
// pin first and then from the peers, and joins the conversation's topic. Start calls it for an owner or a member
// that joined earlier, and Join for a new member.
func (c *ChatService) enter(conv conversation) (err error) {
	c.set.useConversation(conv)
	if c.aead, err = chacha20poly1305.NewX(c.set.conversationKey[:]); err != nil {
		return err
	}
	if c.token, err = capability(c.set, c.id, c.log.ID()); err != nil {
		return err
	}
	c.srv = kolosync.NewServer(c.authorize)
	if err = c.srv.Offer(c.log); err != nil {
		return err
	}
	c.pinDone = make(chan struct{})
	c.mu.Lock()
	c.active = true // what the goroutines below read was written before this
	c.mu.Unlock()

	c.wg.Go(c.pushLoop)
	c.wg.Go(func() { // on open: the pin first, then the peers
		defer close(c.pinDone)
		if err := c.pullFromPin(c.ctx); err != nil {
			log.Print("pin pull: ", err)
		}
	})
	c.pushSoon()
	c.wg.Go(func() { // join the conversation's topic
		err := c.sw.Join(c.ctx, c.topic(), &koloswarm.JoinOptions{Announce: true, Lookup: true})
		if err != nil && c.ctx.Err() == nil {
			log.Print("join: ", err)
		}
	})
	return nil
}

In chatservice.go, replace shutdown with:

chatservice.go
func (c *ChatService) shutdown() error {
	if c.cancel != nil {
		c.cancel()
	}
	var errs []error
	if c.sw != nil {
		errs = append(errs, c.sw.Close())
	}
	if c.inv != nil {
		errs = append(errs, c.inv.Close())
	}
	c.wg.Wait()
	if c.store != nil {
		errs = append(errs, c.store.Close()) // also closes the log and the replicas
	}
	if c.invDB != nil {
		errs = append(errs, c.invDB.Close())
	}
	c.mu.Lock()
	c.active, c.joining, c.cancelJoin = false, nil, nil
	c.mu.Unlock()
	c.id, c.store, c.sw, c.cancel, c.inv, c.invDB = nil, nil, nil, nil, nil, nil
	return errors.Join(errs...)
}

In chatservice.go, replace swarmLoop with:

chatservice.go
// swarmLoop handles every peer the swarm connects.
func (c *ChatService) swarmLoop() {
	for {
		ev, err := c.sw.Next(c.ctx)
		if err != nil {
			if c.ctx.Err() == nil {
				log.Print("swarm: ", err)
			}
			return
		}
		if ev.Kind == koloswarm.Connected && ev.Peer != nil {
			c.route(ev.Peer)
		}
	}
}

Add to chatservice.go:

chatservice.go
// route decides what a connection is for, since one protocol serves it: the inviter that a Join waits for, a
// peer of the conversation (chat and sync), or a person that has only an invite's topic with us, whose
// requests the inviter answers.
func (c *ChatService) route(p *koloswarm.Peer) {
	switch {
	case c.offerToJoin(p):
	case !c.isActive():
	case slices.Contains(p.Topics(), c.topic()):
		c.addPeer(p)
	default:
		c.wg.Go(func() { c.inv.ServePeer(c.ctx, p) })
	}
}

In chatservice.go, replace Send with:

chatservice.go
// Send seals the text with the conversation key and appends it to our log. Then it hands it to every peer
// that is connected, and to the pin for those who are not. A pin that fails never fails the Send.
func (c *ChatService) Send(text string) error {
	if len(text) > maxMessage {
		return errors.New("message too long")
	}
	if c.log == nil {
		return errors.New("not started")
	}
	if !c.isActive() {
		return ErrNotInConversation
	}
	sealed, err := c.seal(text)
	if err != nil {
		return err
	}
	index, err := c.log.Append(sealed)
	if err != nil {
		return err
	}
	c.mu.Lock()
	peers := make([]*koloswarm.Peer, 0, len(c.peers))
	for _, p := range c.peers {
		peers = append(peers, p)
	}
	c.mu.Unlock()
	for _, p := range peers {
		if err := c.sendTo(p, wireMsg{Kind: "msg", Index: index, Sealed: sealed}); err != nil {
			log.Print("direct send: ", err) // the pin and the next sync still carry it
		}
	}
	c.pushSoon()
	return nil
}

9What the window does with it

Only a few lines of the window call the service. The panel to join pastes the code and calls Join:

frontend/src/Invite.jsx
    Join(code)
      .then(() => onJoined())
      .catch((err) => setError(errorText(err)))

The panel to invite chooses the options and calls CreateInvite:

frontend/src/Invite.jsx
    CreateInvite({ ttlSeconds: seconds, uses: Number(uses) || 1, requireApproval: approval })
      .then((info) => {
        setCodes((prev) => ({ ...prev, [info.id]: info.code }))
        setInvites((prev) => [...prev, info])
      })
      .catch((err) => setError(errorText(err)))

And each request that waits has two buttons:

frontend/src/Invite.jsx
          <button type="button" className="btn" onClick={() => answer(Approve, r.request)}>Approve</button>
          <button type="button" className="btn btn--ghost" onClick={() => answer(Deny, r.request)}>Deny</button>

10Run three instances

With the bootstrap node and the pin running, build the app, start the owner with the conversation key and the pin's key, and start the joiner in another terminal without them:

Terminal
# 1. The bootstrap node (keep it running)
go run ./cmd/bootstrap

# 2. A local pin, with its data in .data/pin and at most 100 MB (keep it running)
go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin run -data .data/pin -max-bytes 100MB

# 3. Build the app
GOWORK=off wails3 build

# 4. The owner: a key for the conversation and the pin's public key (in this terminal only)
export KOLO_CHAT_PIN_KEY=$(go run github.com/ciranda-dev/kolo-pin/cmd/kolo-pin id -data .data/pin)
export KOLO_CHAT_CONVERSATION_KEY=$(openssl rand -hex 32)
./bin/kolo-chat -data .data/alice

# 5. The joiner, in another terminal, without those variables (this one has no key and no pin)
./bin/kolo-chat -data .data/bob

In the owner's window click Invite, leave "Require my approval" checked and create the invite. Copy the code, paste it in the joiner's window and click Join. The owner's window shows who wants to join: click Approve and the joiner enters the conversation, and messages go both ways. Close the joiner, send two messages from the owner, open the joiner again: they appear once each, in order, marked "synced from pin". Try a third instance with an expired code, a used up code or a revoked code and it is refused with a clear sentence.

11What an invite protects, and what it does not

The code carries a fingerprint of the owner's key and a secret, never an address. The conversation key travels only in the answer, which is encrypted for the person who asked and signed by the owner, and is stored only in the data directory with mode 0600. It does not appear in logs, errors or events.

Know the limits. Each joiner issues its own pin capability, so the operator of the pin must list the joiners in -owners. An invite's code is shown once, when it is created; after a restart the invite can still be revoked, but not shown again. A new member reads the history of the members it meets. Any member can invite, there are no roles, and there is no way yet to remove a member or rotate the key. Requests that wait do not survive a restart, and the owner has to be online to approve.

12The pin is required in this step

An invite that does not need approval already exists: leave "Require my approval" unchecked and the new member comes in as soon as it pastes the code.

The pin is required in this step: the invite always carries its address and key, and every member issues a capability. The finished example makes the pin optional. Without one, the invites carry no pin and messages reach people only while they are online. It also shows one list of rooms, one for each conversation.

Next steps