kolo docsbeta

Step 5: Profiles and rooms

Give the group names and rooms: every member publishes a profile, and the owner keeps the room and member lists, all stored with kolo-kv and synced to the other members and the pin.

On this page

In the previous step you added invites. Now you add profiles and rooms, so the window shows names instead of short keys, and the group has more than one room.

Every member publishes a profile: a display name and an avatar reference. The group keeps a list of rooms and a list of members. All of it is stored with kolo-kv and synced to the other members and to the pin. The rule that keeps it safe is one writer per key: each member writes only their own profile, and only the owner writes the rooms and the members.

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 sidebar and profile form, is already built, and you bring it in with one command.

1Check what you need

You need what step 4 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 4.

2Bring the window and the library

The window of this step has a sidebar with the rooms and the members, a form for your profile and names on the messages. It is already built: bring it from the tag step-5. Then add kolo-kv. 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-5 -- frontend
Terminal
go get github.com/ciranda-dev/kolo-kv@v0.1.0

3Give each member a directory

A kolo-kv store is one signed log with one writer, so every member gets a second log next to the messages log: the directory. Only that member writes it. It holds the key profile of its member, and, in the owner's directory only, the keys room/<name> and member/<kolo-id>. What a member says about itself is a name and an avatar; the avatar is a reference, not an image, a short text such as an emoji. Mistakes come back as typed errors, so the window can show a sentence and the code can ask errors.Is.

Create profile.go with:

profile.go
import (
	"context"
	"crypto/ed25519"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"time"
	"unicode"
	"unicode/utf8"

	koloid "github.com/ciranda-dev/kolo-id"
	kolokv "github.com/ciranda-dev/kolo-kv"
	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"
)

Add to profile.go:

profile.go
const (
	defaultRoom  = "general" // every conversation has it, and nobody has to write it
	keyProfile   = "profile"
	prefixRoom   = "room/"
	prefixMember = "member/"

	maxName     = 40   // characters in a display name
	maxAvatar   = 16   // characters in an avatar reference
	maxRoomName = 32   // characters in a room name
	maxRooms    = 64   // rooms the owner may add, and the most a reader takes
	maxMembers  = 256  // members a reader takes from the owner's list
	maxValue    = 4096 // bytes of a sealed value a reader accepts
)

// Errors of the directory. ErrNotOwner, ErrRoomExists and ErrUnknownRoom come as they are, and the other two
// come wrapped with the reason, so errors.Is tells the kind and the message is the sentence to show.
var (
	ErrNotOwner       = errors.New("Only the owner of the conversation can do that.")
	ErrInvalidProfile = errors.New("That profile cannot be used")
	ErrInvalidRoom    = errors.New("That room name cannot be used")
	ErrRoomExists     = errors.New("That room already exists.")
	ErrUnknownRoom    = errors.New("That room is not in the room list.")

	errNoDirectory = errors.New("the directory of that member is not known yet")
)

// Profile is what a member says about itself. Avatar is a reference, not an image: a short text such as an
// emoji or an id of the window's own, with no URL characters.
type Profile struct {
	Name   string `json:"name"`
	Avatar string `json:"avatar"`
}

// Member is a member of the conversation as the window shows it. Name and Avatar are empty until the member's
// profile has been read.
type Member struct {
	Key    string `json:"key"` // the member's kolo-id, hex
	Name   string `json:"name"`
	Avatar string `json:"avatar"`
	Owner  bool   `json:"owner"`
}

// directoryView is what the window was told last: the payloads of "chat:profiles" and "chat:rooms".
type directoryView struct {
	Members []Member
	Rooms   []string
}

// directory is the read-only copy of another member's directory: its replica in our store, and the kolo-kv
// reader on it.
type directory struct {
	rep *kolostore.Replica
	db  *kolokv.DB
}

// stamp is the value of a room or a member: when the owner wrote it.
type stamp struct {
	At int64 `json:"at"`
}

4Write only what you own

One place decides what we may write in our directory: everybody writes the profile, and only the owner writes the rest. Every write goes through it, through the same seal as the messages. Publishing a profile is a write and a notice to the peers; adding a room is a write only the owner may make, and a room that exists, in any case, is refused.

Add to profile.go:

profile.go
// SetProfile publishes our name and avatar in our directory. Every peer that is connected is told to pull it,
// and the pin gets it with the next push.
func (c *ChatService) SetProfile(name, avatar string) error {
	p := Profile{Name: strings.TrimSpace(name), Avatar: strings.TrimSpace(avatar)}
	if err := validProfile(p); err != nil {
		return err
	}
	if _, err := c.write(keyProfile, p, false); err != nil {
		return err
	}
	c.directoryChanged()
	return nil
}

// AddRoom adds a room to the room list, which only the owner writes: anyone else gets ErrNotOwner. A bad name
// is ErrInvalidRoom, and a room that exists (in any case) is ErrRoomExists.
func (c *ChatService) AddRoom(name string) error {
	name = strings.TrimSpace(name)
	if err := c.mayWrite(prefixRoom + name); err != nil {
		return err
	}
	if err := validRoomName(name); err != nil {
		return err
	}
	rooms := c.Rooms()
	if slices.ContainsFunc(rooms, func(r string) bool { return strings.EqualFold(r, name) }) {
		return ErrRoomExists
	}
	if len(rooms) > maxRooms {
		return fmt.Errorf("%w: a conversation has at most %d rooms", ErrInvalidRoom, maxRooms)
	}
	wrote, err := c.write(prefixRoom+name, stamp{At: time.Now().Unix()}, true)
	if err != nil {
		return err
	}
	if !wrote {
		return ErrRoomExists
	}
	c.directoryChanged()
	return nil
}

// Rooms lists the rooms of the conversation: the default room, then the ones the owner added, by name. They
// come from the owner's directory only, so what we have read of it is what we show.
func (c *ChatService) Rooms() []string {
	rooms := []string{defaultRoom}
	db, owner := c.ownerDirectory()
	if db == nil {
		return rooms
	}
	it := db.Prefix([]byte(prefixRoom))
	for it.Next() && len(rooms) <= maxRooms {
		name := strings.TrimPrefix(string(it.Key()), prefixRoom)
		if validRoomName(name) == nil && name != defaultRoom && c.openValue(owner, string(it.Key()), it.Value(), &stamp{}) == nil {
			rooms = append(rooms, name)
		}
	}
	it.Close()
	slices.Sort(rooms[1:])
	return rooms
}

// Members lists the members we know: ourselves, the ones in the owner's member list, and the ones we met. Each
// has the profile that its own directory says, and the owner comes first.
func (c *ChatService) Members() []Member {
	if c.dir == nil {
		return nil
	}
	owner := hex.EncodeToString(c.ownerKey())
	keys := append(c.authors(), hex.EncodeToString(c.pub))
	keys = append(keys, c.roster()...)
	slices.Sort(keys)
	keys = slices.Compact(keys)
	members := make([]Member, len(keys))
	for i, key := range keys {
		p := c.profileOf(key)
		members[i] = Member{Key: key, Name: p.Name, Avatar: p.Avatar, Owner: key == owner}
	}
	slices.SortStableFunc(members, func(a, b Member) int { // the owner first, the rest in the order of their keys
		switch {
		case a.Owner == b.Owner:
			return 0
		case a.Owner:
			return -1
		}
		return 1
	})
	return members
}

// IsOwner says whether we are the owner: the only one that writes the room list and the member list.
func (c *ChatService) IsOwner() bool {
	owner := c.ownerKey()
	return len(owner) > 0 && owner.Equal(c.pub)
}

// ownerKey is the key of the conversation's owner, or nil while it is not known.
func (c *ChatService) ownerKey() ed25519.PublicKey {
	c.mu.Lock()
	defer c.mu.Unlock()
	return slices.Clone(c.owner)
}

// mayWrite says whether we may write key in our directory. This is the one place that decides it: everybody
// writes the profile, and only the owner writes the rest.
func (c *ChatService) mayWrite(key string) error {
	if !c.isActive() {
		return ErrNotInConversation
	}
	if key != keyProfile && !c.IsOwner() {
		return ErrNotOwner
	}
	return nil
}

// write puts a value in our directory under key, sealed with the conversation key. With ifMissing it writes
// only a key that is not there yet, and says whether it wrote.
func (c *ChatService) write(key string, v any, ifMissing bool) (bool, error) {
	if err := c.mayWrite(key); err != nil {
		return false, err
	}
	sealed, err := c.sealValue(key, v)
	if err != nil {
		return false, err
	}
	c.dirMu.Lock()
	defer c.dirMu.Unlock()
	if _, err := c.dir.Get([]byte(key)); ifMissing && !errors.Is(err, kolokv.ErrNotFound) {
		return false, nil
	}
	return true, c.dir.Put([]byte(key), sealed)
}

// recordMember writes a member in the member list if we are the owner and it is not there. It returns whether
// it wrote, and the caller then calls directoryChanged.
func (c *ChatService) recordMember(author string) bool {
	if !c.IsOwner() {
		return false
	}
	wrote, err := c.write(prefixMember+author, stamp{At: time.Now().Unix()}, true)
	if err != nil {
		log.Print("member list: ", err)
	}
	return wrote && err == nil
}

// recordKnownMembers writes the owner and every member it knows in the member list: the ones that joined before
// this directory existed, and any whose write failed.
func (c *ChatService) recordKnownMembers() {
	changed := false
	for _, author := range append(c.authors(), hex.EncodeToString(c.pub)) {
		changed = c.recordMember(author) || changed
	}
	if changed {
		c.directoryChanged()
	}
}

// roster lists the members in the owner's member list, as hex kolo-ids.
func (c *ChatService) roster() []string {
	db, owner := c.ownerDirectory()
	if db == nil {
		return nil
	}
	var keys []string
	it := db.Prefix([]byte(prefixMember))
	for it.Next() && len(keys) < maxMembers {
		id := strings.TrimPrefix(string(it.Key()), prefixMember)
		if b, err := hex.DecodeString(id); err == nil && len(b) == ed25519.PublicKeySize &&
			c.openValue(owner, string(it.Key()), it.Value(), &stamp{}) == nil {
			keys = append(keys, id)
		}
	}
	it.Close()
	return keys
}

5Seal the values

A value of the directory is sealed with the conversation key, bound to the author and to the key it is stored under. The pin and anyone who holds entry keys but not the conversation key cannot read it, and a value cannot be moved to another key.

Add to profile.go:

profile.go
// sealValue and openValue protect a value of the directory with the conversation key, bound to the author and
// to the key it is stored under, so the pin and anyone with entry keys but not the conversation key cannot read
// it, and a value cannot be moved to another key.
func (c *ChatService) sealValue(key string, v any) ([]byte, error) {
	plain, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, c.aead.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	return c.aead.Seal(nonce, nonce, plain, valueAD(c.pub, key)), nil
}

func (c *ChatService) openValue(author ed25519.PublicKey, key string, sealed []byte, out any) error {
	n := c.aead.NonceSize()
	if len(sealed) < n || len(sealed) > maxValue {
		return errors.New("sealed value has a bad size")
	}
	plain, err := c.aead.Open(nil, sealed[:n], sealed[n:], valueAD(author, key))
	if err != nil {
		return err
	}
	return json.Unmarshal(plain, out)
}

func valueAD(author ed25519.PublicKey, key string) []byte {
	return append(append([]byte("kolochat/directory/v1"), author...), key...)
}

6Read what the others wrote

A profile is read from its member's directory, and nowhere else. A value that does not open, or is not a valid profile, is treated as no profile. The room list and the member list are read from the owner's directory and from nothing else, so a member cannot add a room by writing a room/ key in its own.

Add to profile.go:

profile.go
// profileOf reads the profile in a member's own directory, and nothing else of it. It returns the zero Profile
// when there is none, or when it is not one we would have written.
func (c *ChatService) profileOf(author string) (p Profile) {
	db := c.readerOf(author)
	pub, err := hex.DecodeString(author)
	if db == nil || err != nil {
		return p
	}
	sealed, err := db.Get([]byte(keyProfile))
	if err != nil || c.openValue(pub, keyProfile, sealed, &p) != nil || validProfile(p) != nil {
		return Profile{}
	}
	return p
}

// ownerDirectory returns the store to read the owner's keys from, and the owner's key. The room list and the
// member list are read through it and through nothing else.
func (c *ChatService) ownerDirectory() (*kolokv.DB, ed25519.PublicKey) {
	owner := c.ownerKey()
	if len(owner) == 0 {
		return nil, nil
	}
	return c.readerOf(hex.EncodeToString(owner)), owner
}

// readerOf returns the store of a member's directory: ours, which we write, or the read-only copy of another's.
func (c *ChatService) readerOf(author string) *kolokv.DB {
	if author == hex.EncodeToString(c.pub) {
		return c.dir
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if d, ok := c.dirs[author]; ok {
		return d.db
	}
	return nil
}

Add to profile.go:

profile.go
// directory returns the read-only copy of a member's directory, opening it the first time: a replica of its
// log in our store, from the header the member sent, and a kolo-kv reader on it.
func (c *ChatService) directory(author string) (*directory, error) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if d, ok := c.dirs[author]; ok {
		return d, nil
	}
	m, ok := c.members[author]
	if !ok || len(m.DirHeader) == 0 {
		return nil, errNoDirectory
	}
	h, err := kololog.DecodeLogHeader(m.DirHeader)
	if err != nil {
		return nil, err
	}
	rep, err := c.store.OpenReplica(h.LogKey, h.LogID, m.DirHeader)
	if err != nil {
		return nil, err
	}
	db, err := kolokv.OpenReader(rep)
	if err != nil {
		rep.Close()
		return nil, err
	}
	d := &directory{rep: rep, db: db}
	c.dirs[author] = d
	return d, nil
}

7Sync the directories

On a connection, a peer's directory is pulled like its messages: a read-only replica in the store, a kolo-kv reader on it, Pull from the peer and PullCiphertext from the pin. When we write, the window is told, the connected peers are told to pull, and the pin gets it with the next push. The window is told only when what it knows has changed.

Add to profile.go:

profile.go
// openDirectories opens the copies of the directories of the members we know, from what the last run kept, so
// the window has names before anyone is connected.
func (c *ChatService) openDirectories() {
	for _, author := range c.authors() {
		if _, err := c.directory(author); err != nil && !errors.Is(err, errNoDirectory) {
			log.Printf("directory of %s: %v", author[:8], err)
		}
	}
	c.recordKnownMembers()
	c.publishDirectory()
}

func (c *ChatService) closeDirectories() {
	c.mu.Lock()
	dirs := c.dirs
	c.dirs = map[string]*directory{}
	c.mu.Unlock()
	for _, d := range dirs {
		d.db.Close() // also closes its replica
	}
	if c.dir != nil {
		c.dir.Close() // also closes the directory log
	}
}

// pullDirectory brings a member's directory up to date from conn, which is the member itself (with entry keys)
// or the pin (ciphertext only), and shows what changed. A reader replays the entries it has keys for, up to the
// first one it does not: from the pin that can be none of the new ones, so the old profile stays until the
// member itself is reachable.
func (c *ChatService) pullDirectory(ctx context.Context, conn *kolosecure.Conn, author string, fromPin bool) error {
	d, err := c.directory(author)
	if err != nil {
		return err
	}
	pull := kolosync.Pull
	if fromPin {
		pull = kolosync.PullCiphertext
	}
	c.pullMu.Lock()
	err = pull(ctx, conn, d.rep)
	c.pullMu.Unlock()
	if rerr := d.db.Refresh(); rerr != nil {
		err = errors.Join(err, rerr)
	}
	c.publishDirectory()
	return err
}

// syncDirectory pulls a peer's directory from the peer itself.
func (c *ChatService) syncDirectory(conn *kolosecure.Conn, author string) {
	ctx, cancel := context.WithTimeout(c.ctx, pinTimeout)
	defer cancel()
	err := c.pullDirectory(ctx, conn, author, false)
	if err != nil && !errors.Is(err, errNoDirectory) && c.ctx.Err() == nil {
		log.Print("sync of directory: ", err)
	}
}

// onDirectory handles a peer saying that its directory changed: it pulls it. The peer decides nothing else.
func (c *ChatService) onDirectory(p *koloswarm.Peer) {
	c.wg.Go(func() {
		if conn, ok := c.afterPin(p); ok {
			c.syncDirectory(conn, hex.EncodeToString(p.PublicKey()))
		}
	})
}

// directoryChanged is what follows a write to our directory: the window sees it, the peers that are connected
// are told to pull it, and the pin gets it.
func (c *ChatService) directoryChanged() {
	c.publishDirectory()
	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 {
		c.wg.Go(func() {
			if err := c.sendTo(p, wireMsg{Kind: "dir"}); err != nil {
				log.Print("directory notice: ", err)
			}
		})
	}
	c.pushSoon()
}

// publishDirectory tells the window the members ("chat:profiles") and the rooms ("chat:rooms") if they are not
// what it was told last.
func (c *ChatService) publishDirectory() {
	c.pubMu.Lock()
	defer c.pubMu.Unlock()
	view := directoryView{Members: c.Members(), Rooms: c.Rooms()}
	if !slices.Equal(view.Members, c.lastView.Members) {
		c.emit("chat:profiles", view.Members)
	}
	if !slices.Equal(view.Rooms, c.lastView.Rooms) {
		c.emit("chat:rooms", view.Rooms)
	}
	c.lastView = view
}

// checkDirHeader checks the directory header in a hello: it is the sender's own signed header, for a kolo-kv
// log (the bytes encoding) that is not its messages log. A hello without one, from a peer that has no
// directory, is fine.
func checkDirHeader(pub ed25519.PublicKey, raw []byte, messages kololog.LogHeader) error {
	if len(raw) == 0 {
		return nil
	}
	h, err := kololog.DecodeLogHeader(raw)
	if err == nil {
		err = kololog.VerifyLogHeader(pub, h)
	}
	if err == nil && (h.LogID == messages.LogID || h.Encoding != kololog.Bytes) {
		err = errors.New("not a directory log")
	}
	if err != nil {
		return fmt.Errorf("directory header: %w", err)
	}
	return nil
}

8Check what comes in

What comes from other members is untrusted: names, avatars and room names are checked for size and for characters that have no place in them before they are shown.

Add to profile.go:

profile.go
func validProfile(p Profile) error {
	bad := func(why string) error { return fmt.Errorf("%w: %s.", ErrInvalidProfile, why) }
	switch {
	case p.Name == "" || utf8.RuneCountInString(p.Name) > maxName:
		return bad(fmt.Sprintf("a name has 1 to %d characters", maxName))
	case !plainText(p.Name) || !plainText(p.Avatar):
		return bad("it has control characters or is not valid text")
	case utf8.RuneCountInString(p.Avatar) > maxAvatar || strings.ContainsAny(p.Avatar, `/:\<>`):
		return bad(fmt.Sprintf("an avatar is a short reference of up to %d characters, such as an emoji, not a URL", maxAvatar))
	}
	return nil
}

func validRoomName(name string) error {
	switch {
	case name == "" || utf8.RuneCountInString(name) > maxRoomName:
		return fmt.Errorf("%w: a name has 1 to %d characters.", ErrInvalidRoom, maxRoomName)
	case !plainText(name) || strings.TrimSpace(name) != name:
		return fmt.Errorf("%w: it has control characters, or spaces at its ends.", ErrInvalidRoom)
	}
	return nil
}

// plainText says that s is valid UTF-8 with no control characters.
func plainText(s string) bool {
	return utf8.ValidString(s) && !strings.ContainsFunc(s, unicode.IsControl)
}

9Keep a second log

The service now owns two logs, the messages and the directory, and the app remembers which is which. The pin capability covers both.

Add to profile.go:

profile.go
// openOwnLogs opens the two logs we write, or creates them the first time: the messages, and the directory.
// Both are ours and look alike, so the directory's ID is kept in the data directory. A store from step 4 has
// the messages log only, and gets a directory.
func (c *ChatService) openOwnLogs() (err error) {
	own, err := ownLogs(c.store, c.id)
	if err != nil {
		return err
	}
	dirID, saved := loadDirectoryID(c.set.DataDir)
	saved = saved && slices.Contains(own, dirID)
	messages := slices.DeleteFunc(own, func(id kololog.LogID) bool { return saved && id == dirID })
	switch {
	case len(messages) > 1:
		return errors.New("the store holds two logs of ours and does not say which one is the directory")
	case len(messages) == 1:
		c.log, err = c.store.Open(c.id, messages[0])
	default:
		c.log, err = c.store.Create(c.id)
	}
	if err != nil {
		return err
	}
	if saved {
		c.dirLog, err = c.store.Open(c.id, dirID)
	} else if c.dirLog, err = c.store.Create(c.id); err == nil {
		err = saveDirectoryID(c.set.DataDir, c.dirLog.ID())
	}
	if err != nil {
		return err
	}
	c.dir, err = kolokv.Open(c.dirLog) // from now on only the DB writes to the log
	return err
}

// ownLogs lists the logs in the store that are ours, not replicas of someone else's.
func ownLogs(st *kolostore.Store, id *koloid.Identity) (own []kololog.LogID, err error) {
	ids, err := st.List()
	if err != nil {
		return nil, err
	}
	for _, logID := range ids {
		pub, replica, err := st.Owner(logID)
		if err != nil {
			return nil, err
		}
		if !replica && pub.Equal(id.PublicKey()) {
			own = append(own, logID)
		}
	}
	return own, nil
}

func loadDirectoryID(dir string) (id kololog.LogID, ok bool) {
	data, err := os.ReadFile(filepath.Join(dir, "directory-log"))
	if b, err2 := hex.DecodeString(strings.TrimSpace(string(data))); err == nil && err2 == nil && len(b) == len(id) {
		copy(id[:], b)
		return id, true
	}
	return id, false
}

// saveDirectoryID writes directory-log, mode 0600, in one step.
func saveDirectoryID(dir string, id kololog.LogID) error {
	tmp := filepath.Join(dir, "directory-log.tmp")
	if err := os.WriteFile(tmp, []byte(id.String()), 0o600); err != nil {
		return err
	}
	return os.Rename(tmp, filepath.Join(dir, "directory-log"))
}

Delete openOwnLog from chatservice.go.

10Wire it into the service

The service reads and writes the directory when it starts, when it meets a peer, when it sends a message and when it pulls from the pin. A message now carries its room inside the sealed payload, and the window shows the selected room.

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"
	kolokv "github.com/ciranda-dev/kolo-kv"
	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 ChatMsg with:

chatservice.go
// ChatMsg is the payload of the "chat:msg" event. From is the sender's kolo-id (hex public key), Room is the room it was sent to and Via says how
// the message arrived: "direct" from the sender, "pin" when its ciphertext came from the pin, "peer" when it was
// pulled from the sender after the direct delivery was missed.
type ChatMsg struct {
	From string `json:"from"`
	Room string `json:"room"`
	Text string `json:"text"`
	Via  string `json:"via"`
}

In chatservice.go, replace wireMsg with:

chatservice.go
// wireMsg is what peers send each other on the direct connection, one unidirectional stream each.
type wireMsg struct {
	Kind      string `json:"kind"`                // "hello", "msg" or "dir"
	Header    []byte `json:"header,omitempty"`    // hello: the sender's signed log header
	DirHeader []byte `json:"dirHeader,omitempty"` // hello: the signed header of the sender's directory log
	Proof     []byte `json:"proof,omitempty"`     // hello: proves the sender knows the conversation key
	Reply     bool   `json:"reply,omitempty"`     // hello: answers a hello, so the sender has registered us
	Index     uint64 `json:"index,omitempty"`     // msg: the entry's index in the sender's log
	Sealed    []byte `json:"sealed,omitempty"`    // msg: the entry's value, the text sealed with the conversation key
	// "dir" has no fields: the sender's directory changed, pull it.
}

In chatservice.go, replace member with:

chatservice.go
// member is a peer of the conversation: its signed log header, which names its public key and log ID, the signed
// header of its directory log (see profile.go), and how many of its messages the window has shown. All are kept
// in the data directory.
type member struct {
	Header    []byte `json:"header"`
	DirHeader []byte `json:"dirHeader,omitempty"`
	Shown     uint64 `json:"shown"`
}

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 of messages, one of the two we write
	dirLog  *kolostore.Log // our directory log, the other one (see profile.go)
	dir     *kolokv.DB     // the key-value store on dirLog: the only writer of it
	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
	dirMu   sync.Mutex // one write of our directory at a time
	pubMu   sync.Mutex // one publication of the directory to the window at a time

	mu         sync.Mutex // guards the fields below
	peers      map[string]*koloswarm.Peer
	members    map[string]*member
	replicas   map[string]*kolostore.Replica
	dirs       map[string]*directory // per member: the read-only copy of its directory
	owner      ed25519.PublicKey     // the key of the conversation's owner: ours, or the one that invited us
	lastView   directoryView         // what the window was told last
	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 err = c.openOwnLogs(); err != nil {
		return err
	}
	c.peers = map[string]*koloswarm.Peer{}
	c.replicas = map[string]*kolostore.Replica{}
	c.dirs = map[string]*directory{}
	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)
}

In chatservice.go, replace enter with:

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(), c.dirLog.ID()); err != nil {
		return err
	}
	c.srv = kolosync.NewServer(c.authorize)
	for _, l := range []*kolostore.Log{c.log, c.dirLog} {
		if err = c.srv.Offer(l); err != nil {
			return err
		}
	}
	c.pinDone = make(chan struct{})
	c.mu.Lock()
	c.owner = ed25519.PublicKey(conv.Owner)
	c.active = true // what the goroutines below read was written before this
	c.mu.Unlock()
	c.openDirectories()

	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()
	c.closeDirectories()
	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
	c.log, c.dirLog, c.dir = nil, nil, nil
	return errors.Join(errs...)
}

In chatservice.go, replace receive with:

chatservice.go
// receive handles what one peer sends, one stream at a time.
func (c *ChatService) receive(p *koloswarm.Peer) {
	for {
		st, err := p.Conn().AcceptUniStream(c.ctx)
		if err != nil {
			return
		}
		st.SetReadDeadline(time.Now().Add(sendTimeout))
		data, err := io.ReadAll(io.LimitReader(st, maxWire+1))
		if err != nil || len(data) > maxWire {
			st.CancelRead(codeTooLong)
			continue
		}
		var m wireMsg
		if json.Unmarshal(data, &m) != nil {
			continue
		}
		switch m.Kind {
		case "hello":
			c.onHello(p, m)
		case "msg":
			c.onMessage(p, m)
		case "dir":
			c.onDirectory(p)
		}
	}
}

In chatservice.go, replace Send with:

chatservice.go
// Send seals the text, with the room it is for, 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. The room must be one of Rooms, or Send returns ErrUnknownRoom.
func (c *ChatService) Send(room, 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
	}
	if !slices.Contains(c.Rooms(), room) {
		return ErrUnknownRoom
	}
	sealed, err := c.seal(room, 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
}

Add to chatservice.go:

chatservice.go
// body is what a message holds before it is sealed: the room and the text. The room is inside the sealed bytes,
// so the pin and anyone with entry keys but not the conversation key cannot tell which room a message is for.
type body struct {
	Version int    `json:"v"`
	Room    string `json:"room"`
	Text    string `json:"text"`
}

In chatservice.go, replace seal with:

chatservice.go
// seal and open protect the room and the text with the conversation key (XChaCha20-Poly1305), bound to the
// author's key. This is the layer the pin and anyone with entry keys cannot remove. open takes an entry that
// is not a body, such as one written by step 4, for text in the default room.
func (c *ChatService) seal(room, text string) ([]byte, error) {
	plain, err := json.Marshal(body{Version: 1, Room: room, Text: text})
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, c.aead.NonceSize())
	if _, err := rand.Read(nonce); err != nil {
		return nil, err
	}
	return c.aead.Seal(nonce, nonce, plain, c.pub), nil
}

In chatservice.go, replace open with:

chatservice.go
func (c *ChatService) open(author ed25519.PublicKey, sealed []byte) (room, text string, err error) {
	n := c.aead.NonceSize()
	if len(sealed) < n {
		return "", "", errors.New("sealed text too short")
	}
	plain, err := c.aead.Open(nil, sealed[:n], sealed[n:], author)
	if err != nil {
		return "", "", err
	}
	var b body
	if json.Unmarshal(plain, &b) != nil || b.Version != 1 {
		return defaultRoom, string(plain), nil
	}
	if validRoomName(b.Room) != nil {
		return "", "", errors.New("message for a room with a bad name")
	}
	return b.Room, b.Text, nil
}

In chatservice.go, replace hello with:

chatservice.go
// hello introduces us: our signed log header, which names our key and log ID, and a proof that we know the
// conversation key, bound to both keys so it cannot be replayed to another peer. The directory header is how a
// peer learns which log holds our profile.
func (c *ChatService) hello(p *koloswarm.Peer, reply bool) wireMsg {
	return wireMsg{Kind: "hello", Header: c.log.Header().Encode(), DirHeader: c.dirLog.Header().Encode(),
		Proof: c.proof(c.pub, p.PublicKey()), Reply: reply}
}

In chatservice.go, replace onHello with:

chatservice.go
// onHello registers a peer that proves it knows the conversation key and answers with our own hello. The
// answer tells the peer that we registered it, so it may pull our log; a hello that is an answer tells us
// the same, so we may pull its log.
func (c *ChatService) onHello(p *koloswarm.Peer, m wireMsg) {
	pub := p.PublicKey()
	h, err := kololog.DecodeLogHeader(m.Header)
	if err != nil || kololog.VerifyLogHeader(pub, h) != nil || !hmac.Equal(m.Proof, c.proof(pub, c.pub)) {
		log.Print("hello refused from ", hex.EncodeToString(pub)[:8])
		return
	}
	if err := checkDirHeader(pub, m.DirHeader, h); err != nil {
		log.Print("hello refused from ", hex.EncodeToString(pub)[:8], ": ", err)
		return
	}
	if err := c.addMember(pub, m.Header, m.DirHeader); err != nil {
		log.Print("member: ", err)
		return
	}
	if !m.Reply {
		if err := c.sendTo(p, c.hello(p, true)); err != nil {
			log.Print("hello: ", err)
		}
		return
	}
	c.wg.Go(func() { c.syncFromPeer(p) })
}

In chatservice.go, replace authorize with:

chatservice.go
// authorize lets the members of the conversation read our two logs with their entry keys, and nobody else.
func (c *ChatService) authorize(peer, owner ed25519.PublicKey, logID kololog.LogID) kolosync.Access {
	c.mu.Lock()
	_, ok := c.members[hex.EncodeToString(peer)]
	c.mu.Unlock()
	if ok && owner.Equal(c.pub) && (logID == c.log.ID() || logID == c.dirLog.ID()) {
		return kolosync.Keys
	}
	return kolosync.NoAccess
}

In chatservice.go, replace onMessage with:

chatservice.go
// onMessage shows a message that arrives directly if it is the next one of its sender, and drops it if it was
// shown already. A gap means we missed some: a sync from the sender shows them all, in order.
func (c *ChatService) onMessage(p *koloswarm.Peer, m wireMsg) {
	author := hex.EncodeToString(p.PublicKey())
	c.showMu.Lock()
	defer c.showMu.Unlock()
	next, known := c.shown(author)
	switch {
	case !known: // its hello is not here yet, and the sync that follows it brings this message too
	case m.Index > next:
		c.wg.Go(func() { c.syncFromPeer(p) })
	case m.Index == next:
		room, text, err := c.open(p.PublicKey(), m.Sealed)
		if err != nil {
			log.Print("direct message refused: ", err)
			return
		}
		c.setShown(author, next+1)
		c.emit("chat:msg", ChatMsg{From: author, Room: room, Text: text, Via: "direct"})
	}
}

In chatservice.go, replace syncFromPeer with:

chatservice.go
// syncFromPeer pulls the sender's log and its directory from the sender, with their entry keys, and shows what
// is new. It waits for the pull from the pin at start, so what the pin has is taken from the pin.
func (c *ChatService) syncFromPeer(p *koloswarm.Peer) {
	conn, ok := c.afterPin(p)
	if !ok {
		return
	}
	author := hex.EncodeToString(p.PublicKey())
	rep, err := c.replica(author)
	if err != nil {
		log.Print("replica: ", err)
	} else {
		ctx, cancel := context.WithTimeout(c.ctx, pinTimeout)
		c.pullMu.Lock()
		err = kolosync.Pull(ctx, conn, rep)
		c.pullMu.Unlock()
		cancel()
		if err != nil && c.ctx.Err() == nil {
			log.Print("sync from peer: ", err)
		} else {
			c.show(author)
		}
	}
	c.syncDirectory(conn, author)
}

Add to chatservice.go:

chatservice.go
// afterPin waits for the pull from the pin at start, and returns the peer's connection if it can be synced.
func (c *ChatService) afterPin(p *koloswarm.Peer) (*kolosecure.Conn, bool) {
	select {
	case <-c.pinDone:
	case <-c.ctx.Done():
		return nil, false
	}
	conn, ok := p.Conn().(*kolosecure.Conn)
	return conn, ok
}

In chatservice.go, replace show with:

chatservice.go
// show gives the window the messages of an author that it has not seen, in the order of the author's log. It
// stops at the first entry whose key is missing: the pin sent the ciphertext, and the key comes only from the
// author, so the entry waits and nothing after it jumps ahead.
func (c *ChatService) show(author string) {
	c.showMu.Lock()
	defer c.showMu.Unlock()
	rep, err := c.replica(author)
	if err != nil {
		return
	}
	pub := rep.Header().LogKey
	for {
		index, _ := c.shown(author)
		if index >= rep.Len() {
			break
		}
		sealed, err := rep.Get(index)
		if errors.Is(err, kololog.ErrKeyUnavailable) {
			break
		}
		if err == nil {
			var room, text string
			if room, text, err = c.open(pub, sealed); err == nil {
				c.mu.Lock()
				via := "peer"
				if index < c.pinned[author] {
					via = "pin"
				}
				c.mu.Unlock()
				c.emit("chat:msg", ChatMsg{From: author, Room: room, Text: text, Via: via})
			}
		}
		if err != nil && !errors.Is(err, kololog.ErrDeleted) {
			log.Printf("entry %d of %s skipped: %v", index, author[:8], err)
		}
		c.setShown(author, index+1)
	}
	locked := 0
	if next, _ := c.shown(author); rep.Len() > next {
		locked = int(rep.Len() - next)
	}
	c.setPin(func(*pinState) { c.locked[author] = locked })
}

In chatservice.go, replace addMember with:

chatservice.go
// addMember registers a member from its signed headers. A member we know gets its directory header when it
// first sends one. The owner also writes every new member in the member list.
func (c *ChatService) addMember(pub ed25519.PublicKey, header, dirHeader []byte) error {
	author := hex.EncodeToString(pub)
	c.mu.Lock()
	m, known := c.members[author]
	switch {
	case !known:
		c.members[author] = &member{Header: header, DirHeader: dirHeader}
	case len(m.DirHeader) == 0 && len(dirHeader) > 0:
		m.DirHeader = dirHeader
	default:
		c.mu.Unlock()
		return nil
	}
	err := saveMembers(c.set.DataDir, c.members)
	c.mu.Unlock()
	if err == nil && !known && c.recordMember(author) {
		c.directoryChanged()
	}
	return err
}

In invite.go, replace conversation with:

invite.go
// conversation is what makes a member: the key, where the pin is, and who the owner is. It is kept in
// conversation.json. Owner is the key that writes the room list and the member list (see profile.go): ours for
// the owner, and for a joiner the key of the member that invited it, saved here. A file from step 4 has none.
type conversation struct {
	Key     []byte `json:"key"`
	PinAddr string `json:"pinAddr"`
	PinKey  []byte `json:"pinKey"`
	Owner   []byte `json:"owner,omitempty"`
}

In invite.go, replace check with:

invite.go
// 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 || len(v.Owner) != 0 && len(v.Owner) != ed25519.PublicKeySize {
		return errors.New("wrong key size")
	}
	_, err := netip.ParseAddrPort(v.PinAddr)
	return err
}

In invite.go, replace grantPayload with:

invite.go
// 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,
			Owner:   c.ownerKey(), // the inviter's own key if it is the owner, else the owner it knows
		},
		Header: c.log.Header().Encode(),
	})
}

In invite.go, replace onJoined with:

invite.go
// 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, nil)
	}
	if err != nil {
		log.Print("invite joiner: ", err)
	}
	log.Print("member joined: ", hex.EncodeToString(ev.Joiner)[:8])
	c.emitInvite(ev.Invite)
}

In invite.go, replace becomeMember with:

invite.go
// 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. The owner is the member that invited us, unless it
// names the owner, which it can because any member may invite.
func (c *ChatService) becomeMember(g grant, inviter ed25519.PublicKey) error {
	if len(g.Owner) == 0 {
		g.Owner = slices.Clone(inviter)
	}
	if err := saveConversation(c.set.DataDir, g.conversation); err != nil {
		return err
	}
	if err := c.addMember(inviter, g.Header, nil); err != nil {
		return err
	}
	return c.enter(g.conversation)
}

In invite.go, replace savedConversation with:

invite.go
// 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), Owner: slices.Clone(c.pub)}
	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}
	}
	if found {
		mine.Owner = saved.Owner // a member that also has the key is still a member
	}
	return mine, true, nil
}

In pin.go, replace the import block with:

pin.go
import (
	"context"
	"crypto/ed25519"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"time"

	koloid "github.com/ciranda-dev/kolo-id"
	kololog "github.com/ciranda-dev/kolo-log"
	"github.com/ciranda-dev/kolo-pin"
	kolosecure "github.com/ciranda-dev/kolo-secure"
	kolostore "github.com/ciranda-dev/kolo-store"
	kolosync "github.com/ciranda-dev/kolo-sync"
)

In pin.go, replace capability with:

pin.go
// capability returns the signed token that lets the pin keep our logs: the messages and the directory. A token
// from the configuration is checked and used as it is. Otherwise the app issues one with its own identity, for
// the pin and these two logs, keeps it in the data directory and reuses it until half of its lifetime has
// passed, since the pin refuses a second capability issued in the same second as the first. A token from step 4
// covers only the messages, so it is replaced by one for both.
func capability(set settings, id *koloid.Identity, logs ...kololog.LogID) ([]byte, error) {
	if set.token != nil {
		return set.token, checkToken(set.token, id, set.pinKey, logs...)
	}
	path := filepath.Join(set.DataDir, "pin-token")
	if token, err := os.ReadFile(path); err == nil {
		c, err := pin.ParseCapability(token)
		if err == nil && c.Quota == set.PinQuota && time.Until(c.Expires) > set.PinTTL/2 &&
			checkToken(token, id, set.pinKey, logs...) == nil {
			return token, nil
		}
	}
	token, err := pin.Issue(id, pin.Capability{
		Peer:    set.pinKey,
		Logs:    logs,
		Expires: time.Now().Add(set.PinTTL),
		Quota:   set.PinQuota,
	})
	if err != nil {
		return nil, &ConfigError{Setting: "pin-ttl", Err: err}
	}
	if err := os.WriteFile(path, token, 0o600); err != nil {
		return nil, err
	}
	return token, nil
}

In pin.go, replace checkToken with:

pin.go
// checkToken says why a token cannot work, with the errors of kolo-pin: ErrInvalidCapability for bytes that are
// not a capability signed by its owner, ErrUnauthorized for one that is not from this identity, for this pin and
// for these logs, and ErrExpired for one that has expired. The pin checks all of it again when it is used.
func checkToken(token []byte, id *koloid.Identity, pinKey ed25519.PublicKey, logs ...kololog.LogID) error {
	c, err := pin.ParseCapability(token)
	switch {
	case err != nil:
		err = fmt.Errorf("%w: %w", pin.ErrInvalidCapability, err)
	case !c.Owner.Equal(id.PublicKey()):
		err = fmt.Errorf("%w: issued by another identity", pin.ErrUnauthorized)
	case !c.Peer.Equal(pinKey):
		err = fmt.Errorf("%w: issued for another pin", pin.ErrUnauthorized)
	case slices.ContainsFunc(logs, func(id kololog.LogID) bool { return !c.Covers(id) }):
		err = fmt.Errorf("%w: does not cover this conversation's logs", pin.ErrUnauthorized)
	case !time.Now().Before(c.Expires):
		err = fmt.Errorf("%w: at %s", pin.ErrExpired, c.Expires.Format(time.RFC3339))
	}
	if err != nil {
		return &ConfigError{Setting: "pin-token", Err: err}
	}
	return nil
}

In pin.go, replace pushToPin with:

pin.go
// pushToPin gives the pin our two logs, the messages and the directory, which it pulls and verifies from what
// it does not have yet. It is how every message and every change of the directory reaches the pin, and it can
// be repeated at any time. The errors are those of kolo-pin: pin.ErrExpired, pin.ErrUnauthorized,
// pin.ErrRevoked, pin.ErrQuotaExceeded, pin.ErrDiskFull, pin.ErrUnreachable.
func (c *ChatService) pushToPin(ctx context.Context) error {
	c.pushMu.Lock() // the pin answers busy to a second Add of the same log
	defer c.pushMu.Unlock()
	ctx, cancel := context.WithTimeout(ctx, pinTimeout)
	defer cancel()
	peer := pin.Peer{ID: c.set.pinKey, Addr: c.set.PinAddr}
	var info pin.Info
	var errs []error
	for _, l := range []*kolostore.Log{c.log, c.dirLog} {
		got, err := pin.Add(ctx, c.id, peer, l, c.token)
		if err != nil {
			errs = append(errs, err)
			continue
		}
		info.Used, info.Quota = got.Used, got.Quota // the owner's, over both logs
		if l == c.log {
			info.Entries = got.Entries
		}
	}
	err := errors.Join(errs...)
	c.setPin(func(s *pinState) {
		s.Push = describe(err, c.set)
		s.Entries, s.Used, s.Quota = info.Entries, info.Used, info.Quota
	})
	return err
}

In pin.go, replace pullFromPin with:

pin.go
// pullFromPin brings the replica of every known peer's log, and of its directory, up to date from the pin. The
// pin sends ciphertext only, so an entry is stored but stays unreadable until its key arrives from the sender
// (see syncFromPeer). A directory then shows what its entries with keys say, which is the older profile.
func (c *ChatService) pullFromPin(ctx context.Context) error {
	authors := c.authors()
	if len(authors) == 0 {
		return nil
	}
	ctx, cancel := context.WithTimeout(ctx, pinTimeout)
	defer cancel()
	conn, err := kolosecure.Dial(ctx, c.set.PinAddr, c.id, c.set.pinKey, nil)
	if err != nil {
		err = fmt.Errorf("%w: %w", pin.ErrUnreachable, err)
		c.setPin(func(s *pinState) { s.Pull = describe(err, c.set) })
		return err
	}
	defer conn.Close()
	var errs []error
	for _, author := range authors {
		if err := c.pullPinnedMessages(ctx, conn, author); err != nil {
			errs = append(errs, fmt.Errorf("pin pull: %w", err))
		}
		err := c.pullDirectory(ctx, conn, author, true)
		if err != nil && !errors.Is(err, kolosync.ErrNotFound) && !errors.Is(err, errNoDirectory) {
			errs = append(errs, fmt.Errorf("pin pull of directory: %w", err))
		}
	}
	err = errors.Join(errs...)
	c.setPin(func(s *pinState) { s.Pull = describe(err, c.set) })
	return err
}

Add to pin.go:

pin.go
// pullPinnedMessages pulls the ciphertext of one author's messages from the pin and shows what can be read.
func (c *ChatService) pullPinnedMessages(ctx context.Context, conn *kolosecure.Conn, author string) error {
	rep, err := c.replica(author)
	if err == nil {
		c.pullMu.Lock()
		err = kolosync.PullCiphertext(ctx, conn, rep)
		c.pullMu.Unlock()
	}
	if errors.Is(err, kolosync.ErrNotFound) {
		return nil // the author has not pinned anything yet
	}
	if err != nil {
		return err
	}
	c.markPinned(author, rep.Len())
	c.show(author)
	return nil
}

11What the window does with it

The window listens to two events, with the members and the rooms:

frontend/src/App.jsx
    const offProfiles = Events.On("chat:profiles", (e) => setMembers(e.data ?? []))
    const offRooms = Events.On("chat:rooms", (e) => setRooms(e.data ?? ['general']))

The profile form calls SetProfile:

frontend/src/Profile.jsx
    SetProfile(name, avatar)
      .then(() => onDone())
      .catch((err) => setError(errorText(err)))

And the owner's box for a new room calls AddRoom:

frontend/src/Profile.jsx
    AddRoom(adding)
      .then(() => setAdding(''))
      .catch((err) => setError(errorText(err)))

12Run it

The commands are those of step 4:

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

Click Profile in each window and save a name and an avatar: the other window shows the name in the member list and on the messages. In the owner's window type a name in "New room" and press Enter: the room shows up in the other window. A member has no box for a new room.

The finished example shows one list of rooms, one for each conversation, and its pin is optional: without one, messages reach people only while they are online.

13What happens when the author is offline

Entry keys come only from the author, as in step 3. Close a member's window, rename another member, and open the first again while the author is offline: the pin gives it the new entry as ciphertext, and it keeps showing the old name until the author returns. The room list and the member list behave the same way, and the owner being online does not help, because it does not serve the keys of another member's entries.

Know the other limits. Names are not unique or verified: the window adds the start of the key when two members share a name. Old names stay in the log, since the app never deletes. A data directory from step 4 has no owner saved, so it shows only the default room until it joins again.

Next steps