No passo anterior você adicionou convites. Agora você adiciona perfis e salas, para que a janela mostre nomes em vez de chaves curtas e o grupo tenha mais de uma sala.
Cada membro publica um perfil: um nome e uma referência de avatar. O grupo guarda uma lista de salas e uma lista de membros. Tudo é guardado com o kolo-kv e sincronizado com os outros membros e com o pin. A regra que mantém isso seguro é um só escritor por chave: cada membro escreve só o próprio perfil, e só o dono escreve as salas e os membros.
Este passo é só backend: você cola o código Go abaixo no projeto do passo anterior. A janela deste passo, com a barra lateral e o formulário de perfil, já está pronta, e você a traz com um comando.
1Confira o que você precisa
Você precisa do mesmo que no passo 4: Go 1.26 ou mais novo, Node.js, wails3, openssl, o nó de bootstrap e um pin local. Parta do projeto que você terminou no passo 4.
2Traga a janela e a biblioteca
A janela deste passo tem uma barra lateral com as salas e os membros, um formulário para o seu perfil e nomes nas mensagens. Ela já está pronta: traga-a da tag step-5. Depois adicione o kolo-kv. A tag também tem a versão pronta de cada arquivo abaixo, caso você queira comparar o seu.
git fetch origin --tags
git checkout step-5 -- frontendgo get github.com/ciranda-dev/kolo-kv@v0.1.03Dê um diretório a cada membro
Um store do kolo-kv é um log assinado com um só escritor, então cada membro ganha um segundo log ao lado do de mensagens: o diretório. Só esse membro o escreve. Ele guarda a chave profile do membro e, só no diretório do dono, as chaves room/<nome> e member/<kolo-id>. O que um membro diz sobre si é um nome e um avatar; o avatar é uma referência, não uma imagem, um texto curto como um emoji. Os erros voltam como erros tipados, para que a janela mostre uma frase e o código possa perguntar com errors.Is.
Crie profile.go com:
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"
)Adicione a 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"`
}4Escreva só o que é seu
Um só lugar decide o que podemos escrever no nosso diretório: todos escrevem o perfil, e só o dono escreve o resto. Toda escrita passa por ele, e pelo mesmo selo das mensagens. Publicar um perfil é uma escrita e um aviso aos peers; adicionar uma sala é uma escrita que só o dono pode fazer, e uma sala que já existe, em qualquer combinação de maiúsculas, é recusada.
Adicione a 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
}5Sele os valores
Um valor do diretório é selado com a chave da conversa, ligado ao autor e à chave sob a qual é guardado. O pin e quem tem chaves de entrada mas não a chave da conversa não conseguem lê-lo, e um valor não pode ser movido para outra chave.
Adicione a 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...)
}6Leia o que os outros escreveram
Um perfil é lido do diretório do próprio membro, e de nenhum outro lugar. Um valor que não abre, ou que não é um perfil válido, é tratado como se não houvesse perfil. A lista de salas e a de membros são lidas do diretório do dono e de nada mais, então um membro não consegue adicionar uma sala escrevendo uma chave room/ no dele.
Adicione a 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
}Adicione a 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
}7Sincronize os diretórios
Em uma conexão, o diretório de um peer é buscado como as mensagens dele: uma réplica somente leitura no store, um leitor do kolo-kv sobre ela, Pull do peer e PullCiphertext do pin. Quando escrevemos, a janela é avisada, os peers conectados são avisados para buscar o diretório e o pin o recebe no próximo push. A janela só é avisada quando o que ela sabe mudou.
Adicione a 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
}8Confira o que chega
O que vem de outros membros não é confiável: nomes, avatares e nomes de sala são conferidos em tamanho e em caracteres que não têm lugar ali antes de serem mostrados.
Adicione a 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)
}9Guarde um segundo log
O serviço agora tem dois logs, o de mensagens e o diretório, e o app lembra qual é qual. A capability do pin cobre os dois.
Adicione a 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"))
}Apague openOwnLog de chatservice.go.
10Ligue ao serviço
O serviço lê e escreve o diretório ao iniciar, ao conhecer um peer, ao enviar uma mensagem e ao buscar do pin. Uma mensagem agora leva a sala dentro do payload selado, e a janela mostra a sala escolhida.
Em chatservice.go, troque o bloco de imports por:
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"
)Em chatservice.go, troque ChatMsg por:
// 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"`
}Em chatservice.go, troque wireMsg por:
// 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.
}Em chatservice.go, troque member por:
// 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"`
}Em chatservice.go, troque ChatService por:
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
}Em chatservice.go, troque start por:
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)
}Em chatservice.go, troque enter por:
// 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
}Em chatservice.go, troque shutdown por:
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...)
}Em chatservice.go, troque receive por:
// 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)
}
}
}Em chatservice.go, troque Send por:
// 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
}Adicione a 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"`
}Em chatservice.go, troque seal por:
// 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
}Em chatservice.go, troque open por:
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
}Em chatservice.go, troque hello por:
// 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}
}Em chatservice.go, troque onHello por:
// 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) })
}Em chatservice.go, troque authorize por:
// 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
}Em chatservice.go, troque onMessage por:
// 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"})
}
}Em chatservice.go, troque syncFromPeer por:
// 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)
}Adicione a 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
}Em chatservice.go, troque show por:
// 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 })
}Em chatservice.go, troque addMember por:
// 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
}Em invite.go, troque conversation por:
// 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"`
}Em invite.go, troque check por:
// 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
}Em invite.go, troque grantPayload por:
// 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(),
})
}Em invite.go, troque onJoined por:
// 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)
}Em invite.go, troque becomeMember por:
// 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)
}Em invite.go, troque savedConversation por:
// 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
}Em pin.go, troque o bloco de imports por:
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"
)Em pin.go, troque capability por:
// 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
}Em pin.go, troque checkToken por:
// 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
}Em pin.go, troque pushToPin por:
// 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
}Em pin.go, troque pullFromPin por:
// 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
}Adicione a 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
}11O que a janela faz com isso
A janela escuta dois eventos, com os membros e as salas:
const offProfiles = Events.On("chat:profiles", (e) => setMembers(e.data ?? []))
const offRooms = Events.On("chat:rooms", (e) => setRooms(e.data ?? ['general']))O formulário do perfil chama SetProfile:
SetProfile(name, avatar)
.then(() => onDone())
.catch((err) => setError(errorText(err)))E a caixa do dono para uma sala nova chama AddRoom:
AddRoom(adding)
.then(() => setAdding(''))
.catch((err) => setError(errorText(err)))12Rode
Os comandos são os do passo 4:
# 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/bobClique em Profile em cada janela e salve um nome e um avatar: a outra janela mostra o nome na lista de membros e nas mensagens. Na janela do dono digite um nome em "New room" e aperte Enter: a sala aparece na outra janela. Um membro não tem caixa para uma sala nova.
O exemplo pronto mostra uma única lista de salas, uma para cada conversa, e o pin dele é opcional: sem ele, as mensagens chegam às pessoas só enquanto elas estão online.
13O que acontece quando o autor está offline
As chaves de entrada vêm só do autor, como no passo 3. Feche a janela de um membro, troque o nome de outro e abra a primeira de novo enquanto o autor está offline: o pin entrega a entrada nova como texto cifrado, e ela continua mostrando o nome antigo até o autor voltar. A lista de salas e a de membros se comportam do mesmo jeito, e o dono estar online não ajuda, porque ele não serve as chaves das entradas de outro membro.
Conheça os outros limites. Os nomes não são únicos nem verificados: a janela acrescenta o começo da chave quando dois membros têm o mesmo nome. Os nomes antigos ficam no log, porque o app nunca apaga. Um diretório de dados do passo 4 não tem dono salvo, então mostra só a sala padrão até entrar de novo.
Próximos passos
- Tenha várias conversas em uma só janela: Passo 6: Várias conversas em um app.
- Leia como rodar um pin de verdade: Rode um peer de fixação em uma VPS e Como escolher peers de fixação.
- Leia a página do kolo-kv: a API e os limites.
- Para comparar seus arquivos com os prontos, use a tag
step-5do repositório do starter.