No passo anterior você guardou mensagens para peers offline. Agora você adiciona convites, para que o dono possa trazer alguém para a conversa sem enviar a chave da conversa em claro para lugar nenhum.
O dono cria um convite com validade, número de usos e, se quiser, uma etapa de aprovação. A outra pessoa cola o código, o dono aprova, e o app do novo membro recebe a chave da conversa e os ajustes do pin dentro da resposta, cifrados só para essa pessoa. Um convite vencido, esgotado, negado ou revogado falha com uma frase clara.
Este passo é só backend: você cola o código Go abaixo no projeto do passo anterior. A janela deste passo, com o painel de convites, já está pronta, e você a traz com um comando.
1Confira o que você precisa
Você precisa do mesmo que no passo 3: 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 3.
2Traga a janela e a biblioteca
A janela deste passo tem um painel para criar convites, um para entrar com um código e os pedidos que esperam resposta. Ela já está pronta: traga-a da tag step-4. Depois adicione o kolo-invite, que cria e responde os convites. 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-4 -- frontendgo get github.com/ciranda-dev/kolo-invite@v0.1.03Deixe a conversa vir de um convite
Um dono continua começando com uma chave da conversa e um pin, como no passo 3. Quem entra começa sem nenhum dos dois: ele os recebe do convite. Por isso os ajustes agora aceitam um início sem chave, e dizem com clareza quando só metade do par é dada.
Em config.go, troque Config por:
// Config is everything the chat needs from outside. A zero field takes its default, if it has one.
// LoadConfig fills it from flags and environment variables.
type Config struct {
DataDir string // -data, KOLO_CHAT_DATA: identity, Pebble store, members. Default: <user config dir>/kolo-chat
Bootstrap string // -bootstrap, KOLO_CHAT_BOOTSTRAP: IP:PORT of a bootstrap node. Default 127.0.0.1:4000
Listen string // -listen, KOLO_CHAT_LISTEN: local IP:PORT. Default 127.0.0.1:0
ConversationKey string // -conversation-key, KOLO_CHAT_CONVERSATION_KEY: 64 hex characters (32 bytes). Empty for someone who joins with an invite
PinAddr string // -pin, KOLO_CHAT_PIN: IP:PORT of the pin. Default 127.0.0.1:7450. Used with a conversation key; a joiner gets the pin from the invite
PinKey string // -pin-key, KOLO_CHAT_PIN_KEY: the pin's public key in hex (`kolo-pin id`). Required with a conversation key
PinToken string // -pin-token, KOLO_CHAT_PIN_TOKEN: a capability in hex, issued by this app's identity. Default: the app issues one
PinTTL time.Duration // -pin-ttl, KOLO_CHAT_PIN_TTL: lifetime of the capability the app issues. Default 720h
PinQuota uint64 // -pin-quota, KOLO_CHAT_PIN_QUOTA: bytes the pin may keep for you, in the capability the app issues. Default 16777216
LookupInterval time.Duration // -lookup-interval, KOLO_CHAT_LOOKUP_INTERVAL: time between topic lookups. Default 5s
}Em config.go, troque LoadConfig por:
// LoadConfig reads the flags in args. A setting that is not given as a flag comes from its environment variable
// (read with getenv, such as os.Getenv), and a flag wins over its variable.
func LoadConfig(args []string, getenv func(string) string, stderr io.Writer) (Config, error) {
var c Config
fs := flag.NewFlagSet("kolo-chat", flag.ContinueOnError)
fs.SetOutput(stderr)
text := func(p *string) func(string) error {
return func(v string) error { *p = v; return nil }
}
dur := func(p *time.Duration) func(string) error {
return func(v string) (err error) { *p, err = time.ParseDuration(v); return err }
}
num := func(p *uint64) func(string) error {
return func(v string) (err error) { *p, err = strconv.ParseUint(v, 10, 64); return err }
}
for _, s := range []struct {
name, env, help string
set func(string) error
}{
{"data", "KOLO_CHAT_DATA", "data directory (default <user config dir>/kolo-chat)", text(&c.DataDir)},
{"bootstrap", "KOLO_CHAT_BOOTSTRAP", "IP:PORT of the bootstrap node (default " + defaultBootstrap + ")", text(&c.Bootstrap)},
{"listen", "KOLO_CHAT_LISTEN", "local IP:PORT to listen on (default " + defaultListen + ")", text(&c.Listen)},
{"conversation-key", "KOLO_CHAT_CONVERSATION_KEY", "32-byte key of the conversation, in hex (leave it out to join with an invite)", text(&c.ConversationKey)},
{"pin", "KOLO_CHAT_PIN", "IP:PORT of the pin (default " + defaultPinAddr + ")", text(&c.PinAddr)},
{"pin-key", "KOLO_CHAT_PIN_KEY", "public key of the pin, in hex (required with -conversation-key)", text(&c.PinKey)},
{"pin-token", "KOLO_CHAT_PIN_TOKEN", "capability for the pin, in hex (default: issued by the app)", text(&c.PinToken)},
{"pin-ttl", "KOLO_CHAT_PIN_TTL", "lifetime of the capability the app issues (default 720h)", dur(&c.PinTTL)},
{"pin-quota", "KOLO_CHAT_PIN_QUOTA", "bytes the pin may keep for you (default 16777216)", num(&c.PinQuota)},
{"lookup-interval", "KOLO_CHAT_LOOKUP_INTERVAL", "time between lookups of the topic (default 5s)", dur(&c.LookupInterval)},
} {
if v := getenv(s.env); v != "" {
if err := s.set(v); err != nil {
return c, &ConfigError{Setting: s.name, Err: fmt.Errorf("%w: %s: %w", ErrMalformed, s.env, err)}
}
}
fs.Func(s.name, s.help+" ("+s.env+")", s.set)
}
return c, fs.Parse(args)
}Em config.go, troque settings por:
// settings is a Config after defaults and checks: values the code can use as they are.
type settings struct {
Config
conversationKey [32]byte
pinKey ed25519.PublicKey
token []byte // nil: the app issues one
bootstrap netip.AddrPort
inConversation bool // the key and the pin are known: from the configuration, or later from an invite
}Em config.go, troque resolve por:
// resolve applies the defaults and checks every setting, returning a *ConfigError for the first bad one.
// Without a conversation key the chat starts as a joiner: the key and the pin come from an invite (see
// useConversation), so the pin settings are refused rather than ignored. A token is checked later, in
// capability, because it needs the identity.
func (c Config) resolve() (settings, error) {
s := settings{Config: c}
if s.DataDir == "" {
dir, err := os.UserConfigDir()
if err != nil {
return s, &ConfigError{Setting: "data", Err: fmt.Errorf("%w: no user config directory: %w", ErrMissing, err)}
}
s.DataDir = filepath.Join(dir, "kolo-chat")
}
s.Bootstrap = orDefault(s.Bootstrap, defaultBootstrap)
s.Listen = orDefault(s.Listen, defaultListen)
s.PinAddr = orDefault(s.PinAddr, defaultPinAddr)
if s.PinTTL == 0 {
s.PinTTL = defaultPinTTL
}
if s.PinQuota == 0 {
s.PinQuota = defaultPinQuota
}
if s.LookupInterval == 0 {
s.LookupInterval = defaultLookupInterval
}
boot, err := netip.ParseAddrPort(s.Bootstrap)
if err != nil {
return s, &ConfigError{Setting: "bootstrap", Err: fmt.Errorf("%w: %w", ErrMalformed, err)}
}
s.bootstrap = boot
if _, err := netip.ParseAddrPort(s.PinAddr); err != nil {
return s, &ConfigError{Setting: "pin", Err: fmt.Errorf("%w: %w", ErrMalformed, err)}
}
if c.ConversationKey == "" && (c.PinKey != "" || c.PinToken != "") {
return s, &ConfigError{Setting: "conversation-key", Err: ErrMissing}
}
if c.ConversationKey == "" {
return s, nil
}
if err := parseHex("conversation-key", c.ConversationKey, s.conversationKey[:]); err != nil {
return s, err
}
s.inConversation = true
s.pinKey = make(ed25519.PublicKey, ed25519.PublicKeySize)
if err := parseHex("pin-key", c.PinKey, s.pinKey); err != nil {
return s, err
}
if c.PinToken != "" {
if s.token, err = hex.DecodeString(c.PinToken); err != nil {
return s, &ConfigError{Setting: "pin-token", Err: fmt.Errorf("%w: %w", ErrMalformed, err)}
}
}
return s, nil
}Adicione a config.go:
// useConversation takes the key and the pin from an invite, or from the file that kept them.
func (s *settings) useConversation(conv conversation) {
copy(s.conversationKey[:], conv.Key)
s.pinKey = ed25519.PublicKey(conv.PinKey)
s.PinAddr = conv.PinAddr
s.inConversation = true
}4Decida o que um convite carrega
O dono escolhe quanto tempo um convite vive, quantas pessoas podem usá-lo e se ele precisa de aprovação. O que o novo membro recebe é o grant: o convite o cifra só para quem entra, e nada mais no app carrega a chave da conversa. Ele contém a chave, o endereço e a chave pública do pin, e o cabeçalho assinado do log do dono, que é o que o novo membro precisa para encontrar o dono e ler o log dele a partir do pin. Não contém nenhum token do pin: uma capability é assinada pelo dono de um log e cobre só esse log, então o novo membro emite a sua, como no passo 3. As recusas voltam como um InviteError, com uma frase para a janela e o erro do kolo-invite como causa.
Crie invite.go com:
import (
"context"
"crypto/ed25519"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"net/netip"
"os"
"path/filepath"
"slices"
"strings"
"time"
invite "github.com/ciranda-dev/kolo-invite"
kololog "github.com/ciranda-dev/kolo-log"
kolostore "github.com/ciranda-dev/kolo-store"
koloswarm "github.com/ciranda-dev/kolo-swarm"
)Adicione a invite.go:
// Bounds of an invite, and how long Join waits.
const (
grantVersion = 1
defaultInviteTTL = 24 * time.Hour
maxInviteTTL = 30 * 24 * time.Hour
maxInviteUses = 100
maxActiveInvites = 16 // every active invite takes a topic of the swarm, see openInvites
swarmTopics = 32 // kolo-swarm's largest MaxTopics: the conversation's topic and the invites'
joinFindTimeout = 60 * time.Second
joinAnswerTimeout = 10 * time.Minute
)
// InviteOptions is what the owner chooses for a new invite. A zero TTLSeconds is one day, a zero Uses is one.
type InviteOptions struct {
TTLSeconds int64 `json:"ttlSeconds"`
Uses int `json:"uses"`
RequireApproval bool `json:"requireApproval"`
}
// InviteInfo describes an invite for the window. Code is the invite's secret: only the answer of CreateInvite
// has it, since kolo-invite does not give a code back later.
type InviteInfo struct {
ID string `json:"id"`
Code string `json:"code,omitempty"`
Expires string `json:"expires"` // RFC 3339
Uses int `json:"uses"`
Used int `json:"used"`
RequireApproval bool `json:"requireApproval"`
State string `json:"state"` // "active", "expired", "used up" or "revoked"
}
// InviteRequest is the payload of the "chat:invite-request" event: Joiner (a kolo-id) asks to join through a
// invite that needs approval. Withdrawn says the request is gone, because the joiner left or the invite ended.
type InviteRequest struct {
Request uint64 `json:"request"`
Invite string `json:"invite"`
Joiner string `json:"joiner"`
Withdrawn bool `json:"withdrawn"`
}
// JoinStatus is the payload of the "chat:join" event. Status is "joining", "waiting" (for the owner's answer),
// "joined" or "failed", and Message is the sentence to show.
type JoinStatus struct {
Status string `json:"status"`
Message string `json:"message"`
}
// InviteError is an error of the invite flow. Message is the sentence the window shows, and Err the cause, one
// of the errors of kolo-invite.
type InviteError struct {
Message string
Err error
}
func (e *InviteError) Error() string { return e.Message }
func (e *InviteError) Unwrap() error { return e.Err }
// ErrNotInConversation is returned by what needs a conversation before the user has joined one.
var ErrNotInConversation = errors.New("Join a conversation first: paste an invite code.")
// conversation is what makes a member: the key, and where the pin is. It is kept in conversation.json.
type conversation struct {
Key []byte `json:"key"`
PinAddr string `json:"pinAddr"`
PinKey []byte `json:"pinKey"`
}
// grant is the payload of an accept. The invite encrypts it for the joiner alone (HPKE), and nothing else
// carries the conversation key. Header is the owner's signed log header, with its key and log ID: what the
// joiner needs to meet the owner and read its log from the pin. There is no pin token in it: a capability is
// signed by the owner of a log and covers that log only, so the joiner issues its own (see capability).
type grant struct {
Version int `json:"v"`
conversation
Header []byte `json:"header"`
}
// check says whether the conversation is complete: a key, and a pin that can be dialed.
func (v conversation) check() error {
if len(v.Key) != 32 || len(v.PinKey) != ed25519.PublicKeySize {
return errors.New("wrong key size")
}
_, err := netip.ParseAddrPort(v.PinAddr)
return err
}5Crie, responda e revogue convites
O Create do kolo-invite devolve o código. Um convite que não precisa de aprovação leva o grant desde o início; um que precisa o recebe quando o dono aprova. Cada convite ativo ocupa um tópico do swarm, então o app limita quantos podem estar ativos. Um segundo laço informa o que acontece com os convites e conhece quem entra. Quando um pedido chega, quem entra enviou com ele o cabeçalho do próprio log: um pedido sem ele é recusado, e um bom aparece na janela do dono. O dono aprova ou nega, e revogar um convite o para na hora, mesmo que ainda tenha usos e tempo.
Adicione a invite.go:
// openInvites opens the inviter, which keeps its invites in a store of its own, and runs what it needs next to
// the swarm: Announce, which joins the topic of every live invite, and the loop of its events. The swarm has
// room for the conversation's topic and for maxActiveInvites invites.
func (c *ChatService) openInvites() (err error) {
if c.invDB, err = kolostore.OpenPebble(filepath.Join(c.set.DataDir, "invites")); err != nil {
return err
}
if c.inv, err = invite.Open(c.invDB, c.id, nil); err != nil {
return err
}
c.requests = map[invite.RequestID]invite.Event{}
c.wg.Go(func() {
if err := c.inv.Announce(c.ctx, c.sw); err != nil && c.ctx.Err() == nil && !errors.Is(err, invite.ErrClosed) {
log.Print("invite announce: ", err)
}
})
c.wg.Go(c.inviteLoop)
return nil
}
// CreateInvite makes an invite for the conversation and returns it with its code, which the owner gives to the
// person to invite. Without RequireApproval the first joiners to use it are accepted at once, up to Uses.
func (c *ChatService) CreateInvite(opts InviteOptions) (InviteInfo, error) {
if c.inv == nil {
return InviteInfo{}, errors.New("not started")
}
if !c.isActive() {
return InviteInfo{}, ErrNotInConversation
}
create := invite.CreateOptions{TTL: defaultInviteTTL, MaxUses: max(opts.Uses, 1), Manual: opts.RequireApproval}
if opts.TTLSeconds != 0 {
create.TTL = time.Duration(opts.TTLSeconds) * time.Second
}
if create.TTL < time.Second || create.TTL > maxInviteTTL || create.MaxUses > maxInviteUses {
return InviteInfo{}, fmt.Errorf("An invite lasts from 1 second to %d days and takes 1 to %d uses.", maxInviteTTL/(24*time.Hour), maxInviteUses)
}
infos, err := c.inv.List()
if err != nil {
return InviteInfo{}, err
}
if n := countActive(infos); n >= maxActiveInvites {
return InviteInfo{}, fmt.Errorf("You have %d active invites. Revoke one, or wait for one to expire.", n)
}
if !create.Manual { // an invite that needs approval takes its payload in Approve
if create.Payload, err = c.grantPayload(); err != nil {
return InviteInfo{}, err
}
}
code, info, err := c.inv.Create(&create)
if err != nil {
return InviteInfo{}, err
}
out := inviteInfo(info)
out.Code = code
return out, nil
}
// Invites lists the invites, oldest first, ended ones included. It has no codes.
func (c *ChatService) Invites() ([]InviteInfo, error) {
if c.inv == nil {
return nil, errors.New("not started")
}
infos, err := c.inv.List()
out := make([]InviteInfo, len(infos))
for i, info := range infos {
out[i] = inviteInfo(info)
}
return out, err
}
// Revoke ends an invite: a joiner that uses its code from now on is refused, and the requests that wait for an
// answer are refused too. Members that joined stay.
func (c *ChatService) Revoke(id string) error {
if c.inv == nil {
return errors.New("not started")
}
var inviteID invite.ID
b, err := hex.DecodeString(id)
if err != nil || len(b) != len(inviteID) {
return errors.New("That is not an invite ID.")
}
copy(inviteID[:], b)
return ownerError(c.inv.Revoke(inviteID))
}
// Approve lets in the person behind a request, giving it the conversation through the invite. Deny refuses it.
func (c *ChatService) Approve(request uint64) error {
payload, err := c.grantPayload()
if err != nil {
return err
}
return ownerError(c.answer(request, func(id invite.RequestID) error { return c.inv.Approve(id, payload) }))
}
func (c *ChatService) Deny(request uint64) error {
return ownerError(c.answer(request, func(id invite.RequestID) error { return c.inv.Deny(id) }))
}
func (c *ChatService) answer(request uint64, do func(invite.RequestID) error) error {
if c.inv == nil {
return errors.New("not started")
}
id := invite.RequestID(request)
err := do(id)
if err == nil || errors.Is(err, invite.ErrNotFound) || errors.Is(err, invite.ErrExpired) ||
errors.Is(err, invite.ErrUsedUp) || errors.Is(err, invite.ErrRevoked) {
c.mu.Lock()
delete(c.requests, id) // the request is over, however it ended
c.mu.Unlock()
c.emit("chat:invite-request", InviteRequest{Request: request, Withdrawn: true})
}
return err
}
// grantPayload is what an accept carries: the conversation, and our signed log header.
func (c *ChatService) grantPayload() ([]byte, error) {
if !c.isActive() {
return nil, ErrNotInConversation
}
return json.Marshal(grant{
Version: grantVersion,
conversation: conversation{
Key: c.set.conversationKey[:],
PinAddr: c.set.PinAddr,
PinKey: c.set.pinKey,
},
Header: c.log.Header().Encode(),
})
}
// inviteLoop reports to the window what happens to the invites, and meets the people that join.
func (c *ChatService) inviteLoop() {
for {
ev, err := c.inv.Next(c.ctx)
if err != nil {
if c.ctx.Err() == nil && !errors.Is(err, invite.ErrClosed) {
log.Print("invite events: ", err)
}
return
}
switch ev.Kind {
case invite.Requested:
c.onRequested(ev)
case invite.Withdrawn:
c.mu.Lock()
delete(c.requests, ev.Request)
c.mu.Unlock()
c.emit("chat:invite-request", InviteRequest{Request: uint64(ev.Request), Invite: ev.Invite.String(), Joiner: hex.EncodeToString(ev.Joiner), Withdrawn: true})
case invite.Joined:
c.onJoined(ev)
case invite.Ended:
c.emitInvite(ev.Invite)
}
}
}
// onRequested shows the window a request that needs an answer. The joiner sends its signed log header as join
// data, so a request without one is refused.
func (c *ChatService) onRequested(ev invite.Event) {
if _, err := joinerHeader(ev.Joiner, ev.Data); err != nil {
log.Print("invite request refused: ", err)
if err := c.inv.Deny(ev.Request); err != nil {
log.Print("invite deny: ", err)
}
return
}
c.mu.Lock()
c.requests[ev.Request] = ev
c.mu.Unlock()
c.emit("chat:invite-request", InviteRequest{Request: uint64(ev.Request), Invite: ev.Invite.String(), Joiner: hex.EncodeToString(ev.Joiner)})
}
// onJoined registers the person that joined as a member, from the log header it sent, so we may read its log and
// give it ours before its first hello. The hello registers it too, so a lost event costs nothing.
func (c *ChatService) onJoined(ev invite.Event) {
c.mu.Lock()
delete(c.requests, ev.Request)
c.mu.Unlock()
header, err := joinerHeader(ev.Joiner, ev.Data)
if err == nil {
err = c.addMember(ev.Joiner, header)
}
if err != nil {
log.Print("invite joiner: ", err)
}
log.Print("member joined: ", hex.EncodeToString(ev.Joiner)[:8])
c.emitInvite(ev.Invite)
}
func (c *ChatService) emitInvite(id invite.ID) {
infos, err := c.inv.List()
if err != nil {
return
}
for _, info := range infos {
if info.ID == id {
c.emit("chat:invite", inviteInfo(info))
}
}
}
// joinerHeader returns the signed log header a joiner sent as its join data, if it is the joiner's own.
func joinerHeader(joiner ed25519.PublicKey, data []byte) ([]byte, error) {
h, err := kololog.DecodeLogHeader(data)
if err == nil {
err = kololog.VerifyLogHeader(joiner, h)
}
if err != nil {
return nil, errors.New("the join data is not the joiner's signed log header")
}
return data, nil
}6Entre com o código
Quem entra começa sem chave e sem pin. Ele encontra quem convidou em um tópico derivado do código, pergunta e espera a resposta. Só quando a resposta chega ele sai do tópico do convite e entra no tópico da conversa. A resposta é conferida antes de ser usada, e salva primeiro, porque o payload é a única cópia que quem entra tem. Depois o app entra na conversa como um dono faz.
Adicione a invite.go:
// joinAttempt is a Join that waits for the connection to the inviter.
type joinAttempt struct {
code invite.Code
peer chan *koloswarm.Peer
}
// offerToJoin gives the peer to the Join that waits for it, if the peer is the inviter of its code.
func (c *ChatService) offerToJoin(p *koloswarm.Peer) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.joining == nil || !c.joining.code.Matches(p.PublicKey()) {
return false
}
select {
case c.joining.peer <- p:
default:
}
return true
}
// Join uses an invite code: it finds the inviter on the invite's topic, asks to join, and waits for the answer,
// which for an invite that needs approval is a person's. With the answer it takes the conversation key and the
// pin from the payload of the accept, keeps them in the data directory, and joins the conversation like an owner
// that started with them. A refusal comes back as an *InviteError whose Message is the sentence to show and
// whose cause is an error of kolo-invite: ErrDenied, ErrExpired, ErrUsedUp, ErrRevoked, ErrInvalidCode,
// ErrInvalid, ErrUnreachable and the like.
func (c *ChatService) Join(text string) error {
if c.sw == nil {
return errors.New("not started")
}
err := c.join(strings.TrimSpace(text))
if err == nil {
c.emit("chat:join", JoinStatus{Status: "joined", Message: "You joined the conversation."})
return nil
}
var ie *InviteError
if !errors.As(err, &ie) {
ie = &InviteError{Message: describeJoin(err), Err: err}
}
c.emit("chat:join", JoinStatus{Status: "failed", Message: ie.Message})
return ie
}
func (c *ChatService) join(text string) error {
code, err := invite.Parse(text)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(c.ctx)
defer cancel()
att := &joinAttempt{code: code, peer: make(chan *koloswarm.Peer, 1)}
c.mu.Lock()
switch {
case c.active:
c.mu.Unlock()
return &InviteError{Message: "You are already in a conversation."}
case c.joining != nil:
c.mu.Unlock()
return &InviteError{Message: "A join is already in progress."}
}
c.joining, c.cancelJoin = att, cancel
c.mu.Unlock()
left := false
leave := func() {
if !left {
left = true
c.sw.Leave(code.Topic())
}
}
defer func() {
leave()
c.mu.Lock()
c.joining, c.cancelJoin = nil, nil
c.mu.Unlock()
}()
c.emit("chat:join", JoinStatus{Status: "joining", Message: "Looking for the person who invited you..."})
if err := c.sw.Join(ctx, code.Topic(), &koloswarm.JoinOptions{Lookup: true}); err != nil {
return err
}
var peer *koloswarm.Peer
select {
case peer = <-att.peer:
case <-time.After(joinFindTimeout):
return fmt.Errorf("%w: not found in %s", invite.ErrUnreachable, joinFindTimeout)
case <-ctx.Done():
return ctx.Err()
}
c.emit("chat:join", JoinStatus{Status: "waiting", Message: "Waiting for the invite to be accepted..."})
actx, acancel := context.WithTimeout(ctx, joinAnswerTimeout)
defer acancel()
payload, err := invite.JoinConn(actx, peer.Conn(), c.id, code, &invite.JoinOptions{Data: c.log.Header().Encode()})
if err != nil {
return err
}
g, err := readGrant(payload, peer.PublicKey())
if err != nil {
return err
}
leave() // before the conversation's topic: the invite-only connection closes, and the group gets its own
return c.becomeMember(g, peer.PublicKey())
}
// CancelJoin stops a Join that waits, for the inviter or for its answer.
func (c *ChatService) CancelJoin() {
c.mu.Lock()
cancel := c.cancelJoin
c.mu.Unlock()
if cancel != nil {
cancel()
}
}
// Joined says whether this chat is in a conversation: it started with a conversation key, or joined with an invite.
func (c *ChatService) Joined() bool { return c.isActive() }
func (c *ChatService) isActive() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.active
}
// readGrant checks the payload of an accept, which only the inviter could have made: a conversation that is
// complete, and the inviter's signed log header.
func readGrant(payload []byte, owner ed25519.PublicKey) (g grant, err error) {
malformed := func(why string) error {
return fmt.Errorf("%w: the accept payload is %s", invite.ErrProtocol, why)
}
if json.Unmarshal(payload, &g) != nil || g.Version != grantVersion {
return g, malformed("not one this version understands")
}
if g.conversation.check() != nil {
return g, malformed("incomplete")
}
if _, err := joinerHeader(owner, g.Header); err != nil {
return g, malformed("missing the inviter's log header")
}
return g, nil
}
// becomeMember keeps the conversation the invite gave and enters it. It is saved first: the payload is the only
// copy the joiner has, and a restart finds it and goes on.
func (c *ChatService) becomeMember(g grant, owner ed25519.PublicKey) error {
if err := saveConversation(c.set.DataDir, g.conversation); err != nil {
return err
}
if err := c.addMember(owner, g.Header); err != nil {
return err
}
return c.enter(g.conversation)
}
// savedConversation returns the conversation this chat is in at start: the one in the configuration, or the one
// an invite gave earlier. A joiner that has none yet returns false.
func (c *ChatService) savedConversation() (conversation, bool, error) {
saved, found, err := loadConversation(c.set.DataDir)
if err != nil {
return saved, false, err
}
if !c.set.inConversation {
return saved, found, nil
}
mine := conversation{Key: slices.Clone(c.set.conversationKey[:]), PinAddr: c.set.PinAddr, PinKey: slices.Clone(c.set.pinKey)}
if found && !slices.Equal(saved.Key, mine.Key) {
err := errors.New("is not the conversation this data directory joined with an invite: use another -data")
return mine, false, &ConfigError{Setting: "conversation-key", Err: err}
}
return mine, true, nil
}
func loadConversation(dir string) (v conversation, found bool, err error) {
data, err := os.ReadFile(filepath.Join(dir, "conversation.json"))
if errors.Is(err, fs.ErrNotExist) {
return v, false, nil
}
if err != nil {
return v, false, err
}
if err = json.Unmarshal(data, &v); err == nil {
err = v.check()
}
if err != nil {
return v, false, fmt.Errorf("conversation.json: %w", errors.New("damaged"))
}
return v, true, nil
}
// saveConversation writes conversation.json, mode 0600, in one step.
func saveConversation(dir string, v conversation) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
tmp := filepath.Join(dir, "conversation.json.tmp")
if err := os.WriteFile(tmp, data, 0o600); err != nil {
return err
}
return os.Rename(tmp, filepath.Join(dir, "conversation.json"))
}7Diga com clareza o que deu errado
Um convite negado, vencido, esgotado ou revogado não é um stack trace. A janela de quem entra recebe uma frase que diz o que aconteceu e o que fazer, e o dono recebe o mesmo para os convites e pedidos que gerencia.
Adicione a invite.go:
func inviteInfo(i invite.Info) InviteInfo {
out := InviteInfo{ID: i.ID.String(), Uses: i.MaxUses, Used: i.Used, RequireApproval: i.Manual, State: i.State.String()}
if !i.Expires.IsZero() {
out.Expires = i.Expires.UTC().Format(time.RFC3339)
}
return out
}
func countActive(infos []invite.Info) (n int) {
for _, i := range infos {
if i.State == invite.Active {
n++
}
}
return n
}
// describeJoin turns an error of kolo-invite into the sentence the joiner's window shows.
func describeJoin(err error) string {
switch {
case errors.Is(err, context.Canceled):
return "Joining was cancelled."
case errors.Is(err, invite.ErrInvalidCode):
return "That is not an invite code. Paste the whole code, exactly as you received it."
case errors.Is(err, invite.ErrDenied):
return "The owner denied your request to join."
case errors.Is(err, invite.ErrExpired):
return "This invite has expired. Ask for a new one."
case errors.Is(err, invite.ErrUsedUp):
return "This invite has no uses left. Ask for a new one."
case errors.Is(err, invite.ErrRevoked):
return "This invite was revoked. Ask for a new one."
case errors.Is(err, invite.ErrInvalid):
return "The inviter does not recognize this invite. Check that you pasted the whole code."
case errors.Is(err, invite.ErrRateLimited):
return "Too many attempts. Wait a minute and try again."
case errors.Is(err, invite.ErrBusy):
return "The inviter is busy. Try again in a moment."
case errors.Is(err, invite.ErrNotAnswered):
return "The inviter received your request, but the connection ended before it answered. Try again: asking twice is safe."
case errors.Is(err, invite.ErrUnreachable):
return "Could not reach the person who invited you. They must be online with the app open. Try again later."
case errors.Is(err, invite.ErrTooLarge), errors.Is(err, invite.ErrProtocol):
return "The inviter sent an answer this app cannot use. Ask for a new invite."
}
return "Could not join: " + err.Error()
}
// ownerError turns an error of kolo-invite into the sentence the owner's window shows, and keeps the cause.
func ownerError(err error) error {
var msg string
switch {
case err == nil:
return nil
case errors.Is(err, invite.ErrExpired):
msg = "The invite expired before it was answered."
case errors.Is(err, invite.ErrUsedUp):
msg = "The invite has no uses left."
case errors.Is(err, invite.ErrRevoked):
msg = "The invite was revoked."
case errors.Is(err, invite.ErrNotFound):
msg = "That request or invite is gone: the person left, or the app restarted."
default:
return err
}
return &InviteError{Message: msg, Err: err}
}8Ligue os convites ao serviço
O serviço precisa direcionar uma conexão pelo que ela é: um peer da conversa, quem convidou e que um Join espera, ou uma pessoa que só tem conosco o tópico de um convite. Ele também inicia o laço de convites e pode entrar em uma conversa que veio de um convite.
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"
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 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, the only one we write
srv *kolosync.Server
sw *koloswarm.Swarm
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
push chan struct{} // a push to the pin is wanted
pinDone chan struct{} // closed when the pull from the pin at start is over
invDB kolostore.Backend // the invites' own store, used for nothing else
inv *invite.Inviter
mu sync.Mutex // guards the fields below
peers map[string]*koloswarm.Peer
members map[string]*member
replicas map[string]*kolostore.Replica
pinned map[string]uint64 // per author: entries below this index came from the pin
locked map[string]int // per author: entries that wait for a key
pin pinState
active bool // in a conversation: it has its key and its pin
joining *joinAttempt // the Join that waits for its inviter
cancelJoin context.CancelFunc // stops that Join
requests map[invite.RequestID]invite.Event // the requests that wait for Approve or Deny
showMu sync.Mutex // one message is shown at a time, so they keep their order
pullMu sync.Mutex // one pull at a time, since a replica takes one
pushMu sync.Mutex // one push at a time
}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 c.log, err = openOwnLog(c.store, c.id); err != nil {
return err
}
c.peers = map[string]*koloswarm.Peer{}
c.replicas = map[string]*kolostore.Replica{}
c.pinned = map[string]uint64{}
c.locked = map[string]int{}
if c.members, err = loadMembers(c.set.DataDir); err != nil {
return err
}
c.ctx, c.cancel = context.WithCancel(context.Background())
c.push = make(chan struct{}, 1)
swarmCfg := &koloswarm.Config{LookupInterval: c.set.LookupInterval, MaxTopics: swarmTopics}
if c.sw, err = koloswarm.New(c.ctx, c.set.Listen, c.id, swarmCfg); err != nil {
return err
}
if err = c.sw.Bootstrap(c.ctx, []netip.AddrPort{c.set.bootstrap}); err != nil {
return err
}
log.Print("kolo-id ", c.id.PublicKeyString())
c.wg.Go(c.swarmLoop)
if err = c.openInvites(); err != nil {
return err
}
conv, found, err := c.savedConversation() // from the configuration, or from the invite that made us a member
if err != nil || !found {
return err // a joiner waits for Join
}
return c.enter(conv)
}Adicione a chatservice.go:
// enter makes this chat a member of the conversation: it has the key and the pin, offers its log, pulls from the
// pin first and then from the peers, and joins the conversation's topic. Start calls it for an owner or a member
// that joined earlier, and Join for a new member.
func (c *ChatService) enter(conv conversation) (err error) {
c.set.useConversation(conv)
if c.aead, err = chacha20poly1305.NewX(c.set.conversationKey[:]); err != nil {
return err
}
if c.token, err = capability(c.set, c.id, c.log.ID()); err != nil {
return err
}
c.srv = kolosync.NewServer(c.authorize)
if err = c.srv.Offer(c.log); err != nil {
return err
}
c.pinDone = make(chan struct{})
c.mu.Lock()
c.active = true // what the goroutines below read was written before this
c.mu.Unlock()
c.wg.Go(c.pushLoop)
c.wg.Go(func() { // on open: the pin first, then the peers
defer close(c.pinDone)
if err := c.pullFromPin(c.ctx); err != nil {
log.Print("pin pull: ", err)
}
})
c.pushSoon()
c.wg.Go(func() { // join the conversation's topic
err := c.sw.Join(c.ctx, c.topic(), &koloswarm.JoinOptions{Announce: true, Lookup: true})
if err != nil && c.ctx.Err() == nil {
log.Print("join: ", err)
}
})
return nil
}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()
if c.store != nil {
errs = append(errs, c.store.Close()) // also closes the log and the replicas
}
if c.invDB != nil {
errs = append(errs, c.invDB.Close())
}
c.mu.Lock()
c.active, c.joining, c.cancelJoin = false, nil, nil
c.mu.Unlock()
c.id, c.store, c.sw, c.cancel, c.inv, c.invDB = nil, nil, nil, nil, nil, nil
return errors.Join(errs...)
}Em chatservice.go, troque swarmLoop por:
// swarmLoop handles every peer the swarm connects.
func (c *ChatService) swarmLoop() {
for {
ev, err := c.sw.Next(c.ctx)
if err != nil {
if c.ctx.Err() == nil {
log.Print("swarm: ", err)
}
return
}
if ev.Kind == koloswarm.Connected && ev.Peer != nil {
c.route(ev.Peer)
}
}
}Adicione a chatservice.go:
// route decides what a connection is for, since one protocol serves it: the inviter that a Join waits for, a
// peer of the conversation (chat and sync), or a person that has only an invite's topic with us, whose
// requests the inviter answers.
func (c *ChatService) route(p *koloswarm.Peer) {
switch {
case c.offerToJoin(p):
case !c.isActive():
case slices.Contains(p.Topics(), c.topic()):
c.addPeer(p)
default:
c.wg.Go(func() { c.inv.ServePeer(c.ctx, p) })
}
}Em chatservice.go, troque Send por:
// Send seals the text with the conversation key and appends it to our log. Then it hands it to every peer
// that is connected, and to the pin for those who are not. A pin that fails never fails the Send.
func (c *ChatService) Send(text string) error {
if len(text) > maxMessage {
return errors.New("message too long")
}
if c.log == nil {
return errors.New("not started")
}
if !c.isActive() {
return ErrNotInConversation
}
sealed, err := c.seal(text)
if err != nil {
return err
}
index, err := c.log.Append(sealed)
if err != nil {
return err
}
c.mu.Lock()
peers := make([]*koloswarm.Peer, 0, len(c.peers))
for _, p := range c.peers {
peers = append(peers, p)
}
c.mu.Unlock()
for _, p := range peers {
if err := c.sendTo(p, wireMsg{Kind: "msg", Index: index, Sealed: sealed}); err != nil {
log.Print("direct send: ", err) // the pin and the next sync still carry it
}
}
c.pushSoon()
return nil
}9O que a janela faz com isso
Só poucas linhas da janela chamam o serviço. O painel para entrar cola o código e chama Join:
Join(code)
.then(() => onJoined())
.catch((err) => setError(errorText(err)))O painel para convidar escolhe as opções e chama CreateInvite:
CreateInvite({ ttlSeconds: seconds, uses: Number(uses) || 1, requireApproval: approval })
.then((info) => {
setCodes((prev) => ({ ...prev, [info.id]: info.code }))
setInvites((prev) => [...prev, info])
})
.catch((err) => setError(errorText(err)))E cada pedido que espera tem dois botões:
<button type="button" className="btn" onClick={() => answer(Approve, r.request)}>Approve</button>
<button type="button" className="btn btn--ghost" onClick={() => answer(Deny, r.request)}>Deny</button>10Rode três instâncias
Com o nó de bootstrap e o pin rodando, compile o app, inicie o dono com a chave da conversa e a chave do pin, e inicie quem entra em outro terminal sem elas:
# 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/bobNa janela do dono clique em Invite, deixe marcado "Require my approval" e crie o convite. Copie o código, cole na janela de quem entra e clique em Join. A janela do dono mostra quem quer entrar: clique em Approve e a pessoa entra na conversa, e as mensagens vão nos dois sentidos. Feche quem entrou, envie duas mensagens do dono e abra de novo: elas aparecem uma vez cada, em ordem, marcadas "synced from pin". Tente uma terceira instância com um código vencido, esgotado ou revogado e ela é recusada com uma frase clara.
11O que um convite protege e o que não protege
O código leva uma impressão digital da chave do dono e um segredo, nunca um endereço. A chave da conversa viaja só na resposta, que vai cifrada para quem pediu e assinada pelo dono, e é guardada só no diretório de dados com modo 0600. Ela não aparece em logs, erros nem eventos.
Conheça os limites. Cada membro que entra emite a própria capability do pin, então o operador do pin precisa listá-los em -owners. O código de um convite é mostrado uma vez, na criação; depois de um reinício o convite ainda pode ser revogado, mas não mostrado de novo. Um membro novo lê o histórico dos membros que encontra. Qualquer membro pode convidar, não há papéis, e ainda não há como remover um membro nem trocar a chave. Os pedidos em espera não sobrevivem a um reinício e o dono precisa estar online para aprovar.
12O pin é obrigatório neste passo
Um convite que não precisa de aprovação já existe: deixe "Require my approval" desmarcado e o novo membro entra assim que cola o código.
O pin é obrigatório neste passo: o convite sempre leva o endereço e a chave dele, e cada membro emite uma capability. O exemplo pronto torna o pin opcional. Sem ele, os convites não levam pin e as mensagens chegam às pessoas só enquanto elas estão online. Ele também mostra uma única lista de salas, uma para cada conversa.
Próximos passos
- O mesmo fluxo em um pequeno programa de terminal, com a própria saída esperada: Convide alguém para um grupo, em um programa de terminal.
- Leia como rodar um pin de verdade: Rode um peer de fixação em uma VPS.
- Para comparar seus arquivos com os prontos, use a tag
step-4do repositório do starter.