kolo docsbeta

Paso 4: Invita a alguien a un grupo

Añade invitaciones al chat: el dueño crea una invitación con caducidad, número de usos y aprobación, y la otra persona se une con el código y recibe por él la clave de la conversación.

En esta página

En el paso anterior guardaste mensajes para peers sin conexión. Ahora añades invitaciones, para que el dueño pueda traer a alguien a la conversación sin enviar la clave de la conversación en claro a ningún sitio.

El dueño crea una invitación con caducidad, número de usos y, si quiere, un paso de aprobación. La otra persona pega el código, el dueño aprueba, y la app del nuevo miembro recibe la clave de la conversación y los ajustes del pin dentro de la respuesta, cifrados solo para esa persona. Una invitación caducada, agotada, denegada o revocada falla con una frase clara.

Este paso es solo backend: pegas el código Go de abajo en el proyecto del paso anterior. La ventana de este paso, con su panel de invitaciones, ya está hecha, y la traes con un comando.

1Comprueba lo que necesitas

Necesitas lo mismo que en el paso 3: Go 1.26 o superior, Node.js, wails3, openssl, el nodo de bootstrap y un pin local. Parte del proyecto que terminaste en el paso 3.

2Trae la ventana y la biblioteca

La ventana de este paso tiene un panel para crear invitaciones, otro para unirse con un código y las solicitudes que esperan respuesta. Ya está hecha: tráela desde la etiqueta step-4. Después añade kolo-invite, que crea y responde las invitaciones. La etiqueta también tiene la versión terminada de cada archivo de abajo, por si quieres comparar el tuyo.

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

3Deja que la conversación venga de una invitación

Un dueño sigue arrancando con una clave de conversación y un pin, como en el paso 3. Quien se une arranca sin ninguno: los recibe de la invitación. Por eso los ajustes ahora aceptan un arranque sin clave, y dicen con claridad cuando solo se da la mitad del par.

En config.go, sustituye Config por:

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

En config.go, sustituye LoadConfig por:

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

En config.go, sustituye settings por:

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

En config.go, sustituye resolve por:

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

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

Añade a config.go:

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

4Decide qué lleva una invitación

El dueño elige cuánto vive una invitación, cuántas personas pueden usarla y si necesita aprobación. Lo que recibe el nuevo miembro es el grant: la invitación lo cifra solo para quien se une, y nada más en la app lleva la clave de la conversación. Contiene la clave, la dirección y la clave pública del pin, y la cabecera firmada del log del dueño, que es lo que el nuevo miembro necesita para encontrar al dueño y leer su log desde el pin. No contiene ningún token del pin: una capacidad la firma el dueño de un log y cubre solo ese log, así que el nuevo miembro emite la suya, como en el paso 3. Los rechazos vuelven como un InviteError, con una frase para la ventana y el error de kolo-invite como causa.

Crea invite.go con:

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

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

Añade a invite.go:

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

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

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

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

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

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

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

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

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

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

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

5Crea, responde y revoca invitaciones

Create de kolo-invite devuelve el código. Una invitación que no necesita aprobación lleva el grant desde el principio; una que la necesita lo recibe cuando el dueño aprueba. Cada invitación activa ocupa un tema del swarm, así que la app limita cuántas pueden estar activas. Un segundo bucle informa de lo que pasa con las invitaciones y conoce a quienes se unen. Cuando llega una solicitud, quien se une ha enviado con ella la cabecera de su propio log: una solicitud sin ella se rechaza, y una buena se muestra en la ventana del dueño. El dueño aprueba o deniega, y revocar una invitación la detiene al instante, aunque le queden usos y tiempo.

Añade a invite.go:

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

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

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

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

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

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

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

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

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

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

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

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

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

6Únete con el código

Quien se une empieza sin clave y sin pin. Encuentra a quien invita en un tema derivado del código, pregunta y espera la respuesta. Solo cuando llega la respuesta deja el tema de la invitación y entra en el tema de la conversación. La respuesta se comprueba antes de usarla, y se guarda primero, porque el payload es la única copia que tiene quien se une. Después la app entra en la conversación como lo hace un dueño.

Añade a invite.go:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

7Di con claridad qué salió mal

Una invitación denegada, caducada, agotada o revocada no es un stack trace. La ventana de quien se une recibe una frase que dice qué pasó y qué hacer, y el dueño recibe lo mismo para las invitaciones y solicitudes que gestiona.

Añade a invite.go:

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

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

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

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

8Conecta las invitaciones al servicio

El servicio tiene que dirigir una conexión según para qué es: un peer de la conversación, quien invita y a quien espera un Join, o una persona que solo tiene con nosotros el tema de una invitación. También arranca el bucle de invitaciones y puede entrar en una conversación que vino de una invitación.

En chatservice.go, sustituye el bloque de imports por:

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

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

En chatservice.go, sustituye ChatService por:

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

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

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

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

En chatservice.go, sustituye start por:

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

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

Añade a chatservice.go:

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

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

En chatservice.go, sustituye shutdown por:

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

En chatservice.go, sustituye swarmLoop por:

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

Añade a chatservice.go:

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

En chatservice.go, sustituye Send por:

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

9Qué hace la ventana con esto

Solo unas pocas líneas de la ventana llaman al servicio. El panel para unirse pega el código y llama a Join:

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

El panel para invitar elige las opciones y llama a CreateInvite:

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

Y cada solicitud que espera tiene dos botones:

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

10Ejecuta tres instancias

Con el nodo de bootstrap y el pin en marcha, compila la app, arranca al dueño con la clave de la conversación y la clave del pin, y arranca a quien se une en otro terminal sin ellas:

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

En la ventana del dueño pulsa Invite, deja marcado "Require my approval" y crea la invitación. Copia el código, pégalo en la ventana de quien se une y pulsa Join. La ventana del dueño muestra quién quiere unirse: pulsa Approve y entra en la conversación, y los mensajes van en ambos sentidos. Cierra a quien se unió, envía dos mensajes desde el dueño y ábrelo otra vez: aparecen una vez cada uno, en orden, marcados "synced from pin". Prueba una tercera instancia con un código caducado, agotado o revocado y se rechaza con una frase clara.

11Qué protege una invitación y qué no

El código lleva una huella de la clave del dueño y un secreto, nunca una dirección. La clave de la conversación viaja solo en la respuesta, que va cifrada para quien preguntó y firmada por el dueño, y se guarda solo en el directorio de datos con modo 0600. No aparece en logs, errores ni eventos.

Conoce los límites. Cada miembro que se une emite su propia capacidad del pin, así que el operador del pin debe listarlos en -owners. El código de una invitación se muestra una vez, al crearla; tras un reinicio la invitación aún se puede revocar, pero no volver a mostrar. Un miembro nuevo lee el historial de los miembros que conoce. Cualquier miembro puede invitar, no hay roles, y aún no hay forma de quitar a un miembro ni de rotar la clave. Las solicitudes en espera no sobreviven a un reinicio y el dueño debe estar en línea para aprobar.

12El pin es obligatorio en este paso

Una invitación que no necesita aprobación ya existe: deja desmarcado "Require my approval" y el nuevo miembro entra en cuanto pega el código.

El pin es obligatorio en este paso: la invitación siempre lleva su dirección y su clave, y cada miembro emite una capacidad. El ejemplo terminado hace el pin opcional. Sin él, las invitaciones no llevan pin y los mensajes llegan a la gente solo mientras está en línea. También muestra una sola lista de salas, una por conversación.

Siguientes pasos