kolo docsbeta

kolo-invite

Códigos de invitación para un grupo. Un miembro crea uno, alguien se une con él, y el miembro aprueba o rechaza.

En esta página

Una invitación deja entrar a alguien nuevo en un grupo. Un miembro, quien invita, crea una invitación y recibe un código corto para enviarlo. La persona que se une usa el código, y quien invita acepta la petición en el acto o la aprueba o rechaza. El código lleva una huella de la clave de kolo-id de quien invita y un secreto de 256 bits, nunca una dirección: quien se une encuentra a quien invita en un topic de kolo-swarm derivado del secreto, o usa una conexión que ya tiene. Quien invita guarda sus invitaciones y quién se unió en un backend de kolo-store, así que un reinicio las conserva. La petición de unirse y su respuesta se sellan con HPKE (RFC 9180), y todo valor público se deriva del secreto de la invitación con HKDF (RFC 5869), así que el secreto en sí nunca viaja. El paquete de Go se llama invite. Una invitación de dispositivo vincula en cambio un dispositivo nuevo a una persona, con un certificado de kolo-id.

Todos los pasos

Unirse con un código de invitación

Le pasas el código a quien se une tú mismo. No lleva ninguna dirección: quien se une encuentra a quien invita a través del DHT.

  1. Quien invita crea 32 bytes aleatorios, el secreto. El código es koloinv0 y 84 caracteres base32: una huella de la clave de quien invita, el secreto y una suma de control. Del secreto salen el ID de la invitación, un topic, un valor de autenticación y una clave de cifrado.
  2. Quien invita se anuncia en el topic de la invitación. Quien se une lee el código, busca el topic y solo se queda con un peer cuya clave coincida con la huella.
  3. Quien se une envía OPEN y recibe un reto nuevo de 32 bytes. Su REQUEST va sellada con HPKE para la clave de la invitación: el valor de autenticación, su clave, una clave para la respuesta, sus datos y su firma.
  4. Quien invita envía RECEIVED enseguida y luego comprueba la petición. Una invitación automática acepta al momento; una manual espera a Accept o Deny.
  5. ANSWER va sellada para la clave de respuesta de quien se une: aceptada con el payload, o denegada, caducada, agotada o revocada.

Instalación

go get github.com/ciranda-dev/kolo-invite

Necesita Go 1.26 o posterior, por crypto/hpke. Compila sin cgo. Invita a alguien a un grupo, en un programa de terminal recorre un programa completo paso a paso.

Inicio rápido

Este programa ejecuta un nodo de bootstrap, alguien que invita y alguien que se une, todo por loopback, con las invitaciones en un directorio temporal. Alice crea una invitación que necesita su aprobación, Bob se une con el código y Alice lo aprueba.

main.go
package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/netip"
	"os"
	"path/filepath"
	"time"

	kolodht "github.com/ciranda-dev/kolo-dht"
	koloid "github.com/ciranda-dev/kolo-id"
	invite "github.com/ciranda-dev/kolo-invite"
	kolostore "github.com/ciranda-dev/kolo-store"
	koloswarm "github.com/ciranda-dev/kolo-swarm"
)

func identity() *koloid.Identity {
	id, err := koloid.Generate()
	if err != nil {
		log.Fatal(err)
	}
	return id
}

// swarm looks its topics up every 5 seconds instead of every 10 minutes, so Bob finds Alice's invite fast.
func swarm(ctx context.Context, id *koloid.Identity, server netip.AddrPort) *koloswarm.Swarm {
	sw, err := koloswarm.New(ctx, "127.0.0.1:0", id, &koloswarm.Config{LookupInterval: 5 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	if err := sw.Bootstrap(ctx, []netip.AddrPort{server}); err != nil {
		log.Fatal(err)
	}
	return sw
}

func main() {
	dir, err := os.MkdirTemp("", "kolo-invite")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// A bootstrap node on loopback, so peers can find each other.
	server, err := kolodht.New(ctx, "127.0.0.1:0", identity(), &kolodht.Config{Server: true})
	if err != nil {
		log.Fatal(err)
	}
	defer server.Close()
	saddr := server.Addr().(*net.UDPAddr).AddrPort()

	// Alice, the inviter: her invites live in dir.
	alice := identity()
	db, err := kolostore.OpenPebble(filepath.Join(dir, "invites"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	in, err := invite.Open(db, alice, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer in.Close()
	asw := swarm(ctx, alice, saddr)
	defer asw.Close()
	go in.Announce(ctx, asw)
	go func() {
		for {
			ev, err := asw.Next(ctx)
			if err != nil {
				return
			}
			if ev.Kind == koloswarm.Connected {
				go in.ServePeer(ctx, ev.Peer)
			}
		}
	}()
	go func() {
		for {
			ev, err := in.Next(ctx)
			if err != nil {
				return
			}
			if ev.Kind == invite.Requested {
				fmt.Printf("request from %q\n", ev.Data)
				if err := in.Approve(ev.Request, []byte("welcome to the group")); err != nil {
					log.Print(err)
				}
			}
		}
	}()

	s, info, err := in.Create(&invite.CreateOptions{TTL: time.Hour, Manual: true})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("invite code, %d characters: %s\n", len(s), s)

	// Bob, the joiner, got the code from Alice in a message.
	bob := identity()
	bsw := swarm(ctx, bob, saddr)
	defer bsw.Close()
	code, err := invite.Parse(s)
	if err != nil {
		log.Fatal(err)
	}
	if err := bsw.Join(ctx, code.Topic(), &koloswarm.JoinOptions{Lookup: true}); err != nil {
		log.Fatal(err)
	}
	for {
		ev, err := bsw.Next(ctx)
		if err != nil {
			log.Fatal(err)
		}
		if ev.Kind != koloswarm.Connected || !code.Matches(ev.Peer.PublicKey()) {
			continue
		}
		payload, err := invite.JoinConn(ctx, ev.Peer.Conn(), bob, code, &invite.JoinOptions{Data: []byte("Bob")})
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("bob joined: %s\n", payload)
		break
	}
	bsw.Leave(code.Topic())

	joiners, err := in.Joiners(info.ID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("alice's store: %d joiner, who sent %q\n", len(joiners), joiners[0].Data)
}

Imprime esto, con un código nuevo en cada ejecución:

Texto
invite code, 92 characters: koloinv0tttsxqasttqy4saldb5klkuuqj3f5oaoiyznmxnpyeeeivyqzsta3exv4cfgqos2rupudbqrbi5eh7zdviqa
request from "Bob"
bob joined: welcome to the group
alice's store: 1 joiner, who sent "Bob"

El código es lo único que Alice envía a Bob, por el medio en que ella confíe. La aplicación mantiene su único swarm y su propio bucle de eventos: Announce se ejecuta a su lado, y el bucle llama a ServePeer del lado de quien invita y a JoinConn del lado de quien se une. Joiners lee el almacén, así que ese registro sobrevive a un reinicio. Aquí los swarms buscan sus topics cada 5 segundos, porque Bob puede buscar antes de que Alice haya anunciado; con el valor por defecto de kolo-swarm podría esperar hasta unos 12 minutos a la siguiente búsqueda.

Vincular un dispositivo

Una invitación de dispositivo añade un dispositivo nuevo a una persona, con certificados de dispositivo de kolo-id. Un dispositivo aprobador crea la invitación, el dispositivo nuevo muestra 12 dígitos, la persona los teclea en el aprobador, y el aprobador firma un certificado para la clave del dispositivo nuevo y lo devuelve dentro de la respuesta sellada. La clave de persona, derivada de las 24 palabras, nunca vive en un dispositivo, y una invitación nunca lleva las palabras. Necesita kolo-id v0.1.0.

En el dispositivo aprobador, cuya identidad es la que recibe Open:

  • CreateDevice(opts) crea una invitación Manual de un solo uso. El código dura DefaultDeviceTTL, 5 minutos, salvo que DeviceOptions.TTL fije otro valor positivo, y Info.Device es true. Muestra el código solo al dispositivo nuevo.
  • Con un evento Requested, PendingLink(req) devuelve la clave del dispositivo nuevo y el nombre que eligió, nunca los dígitos. La persona teclea en MatchDevice(typed) los 12 dígitos que muestra el dispositivo nuevo, y esta devuelve un DeviceMatch para la petición pendiente con esos dígitos, o ErrFingerprint. Los espacios se ignoran y la comparación tarda un tiempo constante. Si la misma clave vuelve a pedir con otro nombre, la coincidencia deja de valer (ErrNotFound) y la persona teclea los dígitos otra vez.
  • ApproveDevice(match, &DeviceApproval{...}) vincula un dispositivo normal. Signer es la identidad de este dispositivo, Cert su certificado de aprobador y Serial el número de serie del certificado nuevo, como mínimo 1, elegido por quien llama. Un certificado de aprobador caducado, o uno normal, es ErrNotApprover.
  • ApproveApprover(match, &ApproverApproval{...}) vincula un aprobador. Person es una función que deriva la clave de persona de las 24 palabras tecleadas en este dispositivo, por ejemplo con koloid.Phrase.Person. Solo se ejecuta después de comprobar la coincidencia, y la clave que devuelve se usa una vez y se borra antes de que la llamada vuelva, tanto si sale bien como en cada error. Hace falta exactamente uno de ExpectPerson (la persona a la que ya pertenece este dispositivo) y FirstDevice, o la llamada devuelve ErrPersonRequired. Otra clave de persona, como una frase mal tecleada con una suma de control válida, es ErrPersonMismatch y no firma nada.
  • Deny(req) rechaza una petición de dispositivo y quema el código. Una petición que nadie responde dentro de Options.DevicePendingTTL, 2 minutos por defecto, se retira y también quema el código. Quien se une y cancela no lo quema, y quien vuelve a pedir conserva el plazo de su primera petición. Approve sobre una invitación de dispositivo es ErrInvalidArgument.

En el dispositivo nuevo, DeviceFingerprint(code, inviterKey, deviceKey) da los 12 dígitos que mostrar, y JoinDevice envía la petición y devuelve un DeviceLink con la clave de persona y el certificado terminado. DeviceJoinOptions necesita exactamente uno de Person, la clave de persona que el dispositivo espera, y FirstDevice, o la llamada devuelve ErrPersonRequired. JoinDevice comprueba que el certificado nombra la clave de este dispositivo, se encadena con la clave de persona, tiene firmas válidas y lo firmó quien invita o la clave de persona. Cualquier otra cosa es ErrProtocol. Guarda el certificado con koloid.SaveCert y preséntalo a los grupos con el paquete devices de kolo-braid.

Este programa es examples/linkdevice del repositorio. Un portátil vincula un teléfono como dispositivo normal y una tableta como aprobador, en loopback y en memoria.

main.go
// Command linkdevice links two new devices to a person on loopback, in memory: a phone as an ordinary device, approved by
// the laptop, and a tablet as an approver, approved by the laptop after the person types the 24 words on it.
package main

import (
	"context"
	"crypto/ed25519"
	"fmt"
	"log"
	"net"
	"net/netip"
	"time"

	koloid "github.com/ciranda-dev/kolo-id"
	invite "github.com/ciranda-dev/kolo-invite"
	kolosecure "github.com/ciranda-dev/kolo-secure"
	kolostore "github.com/ciranda-dev/kolo-store"
	koloswarm "github.com/ciranda-dev/kolo-swarm"
)

func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

// peer is what ServePeer needs to know about a connection.
type peer struct{ conn *kolosecure.Conn }

func (p peer) Conn() koloswarm.Conn         { return p.conn }
func (p peer) PublicKey() ed25519.PublicKey { return p.conn.RemotePublicKey() }
func (p peer) Addr() netip.AddrPort {
	return p.conn.RemoteAddr().(*net.UDPAddr).AddrPort()
}
func (p peer) Topics() []koloswarm.Topic { return nil }

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// The person creates a phrase on the laptop, and the person key certifies the laptop as an approver. The key is
	// derived only here and then cleared: it is never stored.
	phrase, err := koloid.GeneratePhrase()
	check(err)
	words := phrase.Words()
	person, err := phrase.Person()
	check(err)
	phrase.Clear()
	personKey := person.PublicKey()
	laptop, err := koloid.Generate()
	check(err)
	offer, err := person.OfferDeviceCert(laptop.PublicKey(), &koloid.IssueOptions{Serial: 1, Approver: true})
	check(err)
	laptopCert, err := laptop.AcceptDeviceCert(offer, personKey)
	check(err)
	person.Clear()

	// The laptop is the inviter. Its application serves every connection it accepts.
	db := kolostore.NewMemory()
	defer db.Close()
	in, err := invite.Open(db, laptop, nil)
	check(err)
	defer in.Close()
	ln, err := kolosecure.Listen(ctx, "127.0.0.1:0", laptop, nil)
	check(err)
	defer ln.Close()
	go func() {
		for {
			c, err := ln.Accept(ctx)
			if err != nil {
				return
			}
			go in.ServePeer(ctx, peer{c})
		}
	}()

	// Link the phone: an ordinary device. The code goes to the phone out of band.
	phone, err := koloid.Generate()
	check(err)
	code := newCode(in)
	conn, err := kolosecure.Dial(ctx, ln.Addr().String(), phone, laptop.PublicKey(), nil)
	check(err)
	defer conn.Close()
	shown, err := invite.DeviceFingerprint(code, laptop.PublicKey(), phone.PublicKey())
	check(err)
	fmt.Println("the phone shows:", shown)
	done := make(chan *invite.DeviceLink, 1)
	go func() {
		link, err := invite.JoinDevice(ctx, conn, phone, code, &invite.DeviceJoinOptions{Name: "Maria's phone", Person: personKey})
		check(err)
		done <- link
	}()
	req := nextRequest(ctx, in)
	fmt.Printf("the laptop shows the request of %q and asks for the digits the phone shows\n", req.Name)
	// The person types the digits the phone shows; only what matches a pending request can be approved.
	match, err := in.MatchDevice(shown)
	check(err)
	check(in.ApproveDevice(match, &invite.DeviceApproval{Signer: laptop, Cert: laptopCert, Serial: 1}))
	link := <-done
	fmt.Println("phone is an ordinary device of the person:", link.Person.Equal(personKey) && !link.Cert.Approver())

	// Link the tablet as an approver: the person types the 24 words on the laptop, which derives the person key, signs
	// and clears it at once. The words never leave the laptop.
	tablet, err := koloid.Generate()
	check(err)
	code = newCode(in)
	conn2, err := kolosecure.Dial(ctx, ln.Addr().String(), tablet, laptop.PublicKey(), nil)
	check(err)
	defer conn2.Close()
	shown, err = invite.DeviceFingerprint(code, laptop.PublicKey(), tablet.PublicKey())
	check(err)
	go func() {
		link, err := invite.JoinDevice(ctx, conn2, tablet, code, &invite.DeviceJoinOptions{Name: "Maria's tablet", Person: personKey})
		check(err)
		done <- link
	}()
	req = nextRequest(ctx, in)
	match, err = in.MatchDevice(shown)
	check(err)
	derive := func() (*koloid.Identity, error) {
		typed, err := koloid.ParseWords(words)
		if err != nil {
			return nil, err
		}
		defer typed.Clear()
		return typed.Person()
	}
	check(in.ApproveApprover(match, &invite.ApproverApproval{Person: derive, ExpectPerson: laptopCert.Person(), Serial: 2}))
	link = <-done
	fmt.Println("tablet is an approver of the person:", link.Person.Equal(personKey) && link.Cert.Approver())
}

func newCode(in *invite.Inviter) invite.Code {
	s, _, err := in.CreateDevice(nil)
	check(err)
	code, err := invite.Parse(s)
	check(err)
	return code
}

// nextRequest waits for the next request of a link-a-device invite and returns what an approver shows.
func nextRequest(ctx context.Context, in *invite.Inviter) invite.LinkRequest {
	for {
		ev, err := in.Next(ctx)
		check(err)
		if ev.Kind == invite.Requested {
			req, err := in.PendingLink(ev.Request)
			check(err)
			return req
		}
	}
}

Imprime esto, con otros dígitos en cada ejecución:

Texto
the phone shows: 379 379 009 487
the laptop shows the request of "Maria's phone" and asks for the digits the phone shows
phone is an ordinary device of the person: true
tablet is an approver of the person: true

Los dígitos se teclean, nunca se pulsan: una aplicación no debe calcularlos en el aprobador ni mostrarlos allí para confirmarlos, porque la barrera solo aguanta mientras la persona teclea lo que muestra el dispositivo nuevo. Para que un dispositivo normal pase a ser aprobador sin invitación, la persona teclea las 24 palabras en ese dispositivo, que comprueba que la clave derivada es igual a DeviceLink.Person y se certifica a sí mismo con kolo-id; no viaja nada.

Referencia de la API

La referencia de la API se genera a partir del código Go y está en inglés.

Paquete invite · github.com/ciranda-dev/kolo-invite · v0.1.0

Package invite pairs new members with an existing one: an inviter creates an invite, a joiner uses it, and the inviter accepts, approves or denies.

An invite code is a short string that carries a fingerprint of the inviter's kolo-id key and a 256-bit secret, never an address. The joiner finds the inviter on a kolo-swarm topic derived one-way from the secret, or uses a connection it already has, sends a request sealed with HPKE (RFC 9180) to a key derived from the secret and signed with its kolo-id key, and gets a sealed accept with a payload, or an explicit deny, expired, used up or revoked answer. The inviter enforces expiry on its own clock, counts uses atomically and durably, and keeps its invites and joiners in a kolo-store backend. Like kolo-sync, it works per connection: the application keeps its swarm and event loop, runs Announce, and calls ServePeer or JoinConn on its peers.

Experimental: the API may change before v1.0.0.

Constantes

const (
	// DefaultDeviceTTL is how long a link-a-device code lasts when DeviceOptions.TTL is zero.
	DefaultDeviceTTL = 5 * time.Minute
	// DefaultMaxDeviceName is the default of Options.MaxDeviceName and DeviceJoinOptions.MaxName, in bytes.
	DefaultMaxDeviceName = 64
	// DefaultMaxDevicePayload is the default of DeviceJoinOptions.MaxPayload, in bytes: an answer is under 600.
	DefaultMaxDevicePayload = 4096
)

The link-a-device defaults.

const Linger = 5 * time.Minute

Linger is how long an ended invite stays announced and still answers (stored accepts, denies, its state); then its secret is erased.

const Prefix = "koloinv0"

Prefix starts every invite code written in lower case; its last character is the format version.

Variables

var (
	// ErrInvalidArgument means a nil identity, backend, swarm, peer or connection, bad Options or CreateOptions, a
	// swarm of another identity, or a store of another inviter.
	ErrInvalidArgument = errors.New("invite: invalid argument")
	// ErrInvalidCode means a string that is not an invite code: wrong prefix or version, mixed case, bad base32,
	// wrong length or checksum.
	ErrInvalidCode = errors.New("invite: invalid invite code")
	// ErrNotFound means no invite or no pending request with that ID.
	ErrNotFound = errors.New("invite: not found")
	// ErrClosed means the Inviter is closed.
	ErrClosed = errors.New("invite: closed")
	// ErrDenied means the inviter denied the request.
	ErrDenied = errors.New("invite: denied")
	// ErrExpired means the invite expired on the inviter's clock.
	ErrExpired = errors.New("invite: expired")
	// ErrUsedUp means the invite has no uses left.
	ErrUsedUp = errors.New("invite: used up")
	// ErrRevoked means the inviter revoked the invite.
	ErrRevoked = errors.New("invite: revoked")
	// ErrInvalid means the inviter could not authenticate the request: it does not know the invite, or the request
	// does not decrypt or verify.
	ErrInvalid = errors.New("invite: request refused as invalid")
	// ErrRateLimited means the inviter refused the request under its rate limits; try again later.
	ErrRateLimited = errors.New("invite: rate limited")
	// ErrBusy means the inviter could not take the request now (too many pending requests in all or from this
	// source, or its storage failed), or Announce is already running.
	ErrBusy = errors.New("invite: busy")
	// ErrTooLarge means join data over the inviter's MaxData, a payload over the joiner's MaxPayload, or a payload
	// too large to send.
	ErrTooLarge = errors.New("invite: too large")
	// ErrProtocol means a malformed, truncated or unexpected message, another protocol version, or a peer that is
	// not the inviter.
	ErrProtocol = errors.New("invite: protocol error")
	// ErrUnreachable means the stream or connection failed, or ctx ended, before the inviter received the request.
	ErrUnreachable = errors.New("invite: inviter unreachable")
	// ErrNotAnswered means the inviter received the request, but the connection failed or ctx ended before its answer.
	ErrNotAnswered = errors.New("invite: request not answered")
	// ErrNotApprover means the certificate that ApproveDevice was given is not an unexpired approver certificate, or the
	// signer is not an approver; only an approver may link a device.
	ErrNotApprover = errors.New("invite: signer is not an approver")
	// ErrFingerprint means MatchDevice found no pending link-a-device request with the typed fingerprint.
	ErrFingerprint = errors.New("invite: fingerprint does not match")
	// ErrPersonMismatch means the person key given to ApproveApprover is not the one the approving device belongs to.
	ErrPersonMismatch = errors.New("invite: person key is not the expected one")
	// ErrPersonRequired means ApproveApprover or JoinDevice was given neither the person it expects nor FirstDevice.
	ErrPersonRequired = errors.New("invite: expected person or FirstDevice required")
	// ErrIDCollision means a new invite got the 128-bit ID of a stored one; it does not happen in practice.
	ErrIDCollision = errors.New("invite: invite ID collision")
)

Funciones

func DeviceFingerprint

func DeviceFingerprint(code Code, inviter, device ed25519.PublicKey) (string, error)

DeviceFingerprint returns the fingerprint the new device shows for code, the inviter's key (its connection's remote key) and its own device key. The code must be the inviter's (Code.Matches), else ErrInvalidArgument.

func JoinConn

func JoinConn(ctx context.Context, conn koloswarm.Conn, id *koloid.Identity, code Code, opts *JoinOptions) ([]byte, error)

JoinConn asks the inviter of code, on conn, to let id join, and returns the payload of the accept. conn must be a connection to the inviter (code.Matches its remote key), for example from a Connected event of a swarm that joined code.Topic(); the inviter must run ServePeer on it. JoinConn opens one stream and waits for the answer as long as ctx allows: a Manual invite waits for a person, so give ctx a deadline or cancel it.

The answers are ErrDenied, ErrExpired, ErrUsedUp, ErrRevoked, ErrInvalid, ErrRateLimited, ErrBusy and ErrTooLarge. A failed connection or ctx ending is ErrUnreachable before the inviter received the request and ErrNotAnswered after; both wrap the cause, and asking again is safe.

Tipos

type ApproverApproval

type ApproverApproval struct {
	// Person derives the person key from the words the person typed on this device. It is called only after the match checks
	// pass, without the inviter's lock; its key is cleared before ApproveApprover returns, whatever the result.
	Person func() (*koloid.Identity, error)
	// ExpectPerson is the person key this device already belongs to; another key is ErrPersonMismatch and nothing is signed.
	ExpectPerson ed25519.PublicKey
	// FirstDevice says this device has no person yet, so there is nothing to expect. Exactly one of ExpectPerson and
	// FirstDevice is required (ErrPersonRequired): the person key cannot be checked otherwise.
	FirstDevice bool
	// Serial is the serial of the new certificate, at least 1, chosen by the caller.
	Serial uint64
	// ExpiresAt is zero for a certificate that never expires.
	ExpiresAt time.Time
}

ApproverApproval is the choices of ApproveApprover.

type Code

type Code struct {
	// contains filtered or unexported fields
}

Code is a parsed invite code. It holds the invite secret behind a pointer, so it prints only its ID, also inside other values.

func Parse
func Parse(s string) (Code, error)

Parse reads an invite code: all in lower case, or all in upper case. It does not trim spaces.

func (Code) Format
func (c Code) Format(f fmt.State, _ rune)

Format prints String for every verb.

func (Code) GoString
func (c Code) GoString() string

GoString returns the same as String.

func (Code) ID
func (c Code) ID() ID

ID returns the invite's ID; zero for a zero Code.

func (Code) Matches
func (c Code) Matches(key ed25519.PublicKey) bool

Matches reports whether key is the inviter's kolo-id key: a 16-byte fingerprint of it is in the code.

func (Code) String
func (c Code) String() string

String returns the invite ID as hex, never the secret.

func (Code) Topic
func (c Code) Topic() koloswarm.Topic

Topic returns the kolo-swarm topic on which the inviter announces the invite; zero for a zero Code.

type CreateOptions

type CreateOptions struct {
	// TTL is how long the invite can be used, on the inviter's clock; zero means it never expires.
	TTL time.Duration
	// MaxUses is how many joiners can be accepted; zero means 1 (single use).
	MaxUses int
	// Manual makes each request wait for Approve or Deny; otherwise requests within the invite rules are accepted.
	Manual bool
	// Payload is what an auto-approved joiner receives, at most 1 GiB; it must be empty with Manual.
	Payload []byte
}

CreateOptions describes a new invite.

type DeviceApproval

type DeviceApproval struct {
	// Signer is the approving device's identity; its key must be the Inviter's.
	Signer *koloid.Identity
	// Cert is the approver certificate of Signer.
	Cert *koloid.DeviceCert
	// Serial is the serial of the new certificate, at least 1, chosen by the caller.
	Serial uint64
	// ExpiresAt is zero for a certificate that never expires.
	ExpiresAt time.Time
}

DeviceApproval is the choices of ApproveDevice.

type DeviceJoinOptions

type DeviceJoinOptions struct {
	// Name is the name the approver sees; required, letters, numbers, marks, punctuation, symbols and single spaces.
	Name string
	// MaxName is the longest Name in bytes: default DefaultMaxDeviceName. An inviter with a smaller Options.MaxDeviceName refuses
	// a longer one.
	MaxName int
	// MaxPayload bounds the answer JoinDevice accepts, in bytes: default DefaultMaxDevicePayload.
	MaxPayload int
	// Person is the person key the new device expects to join; another key is ErrProtocol.
	Person ed25519.PublicKey
	// FirstDevice says this device belongs to no person yet. Exactly one of Person and FirstDevice is required
	// (ErrPersonRequired): without a person to compare, the approver's person key cannot be checked.
	FirstDevice bool
	// contains filtered or unexported fields
}

DeviceJoinOptions sets what JoinDevice sends and accepts.

type DeviceMatch

type DeviceMatch struct {
	// contains filtered or unexported fields
}

DeviceMatch is a pending link-a-device request whose fingerprint the person typed. Only MatchDevice makes one, and the two approve calls take nothing else. An application must not compute the fingerprint itself (DeviceFingerprint is for the new device): it must ask the person to type what the new device shows. The match names the request as it was when matched: if the same key asks again with another name, the match no longer applies.

func (DeviceMatch) Request
func (m DeviceMatch) Request() RequestID

Request returns the request the match names, for example to look its name up with PendingLink.

type DeviceOptions

type DeviceOptions struct {
	// TTL is how long the code can be used, on the inviter's clock: default DefaultDeviceTTL; negative is an error.
	TTL time.Duration
}

DeviceOptions describes a link-a-device invite.

type Event

type Event struct {
	Kind    EventKind
	Invite  ID
	Request RequestID
	Joiner  ed25519.PublicKey
	Data    []byte
	State   State
}

Event is one thing that happened to the invites; which fields are set depends on Kind.

type EventKind

type EventKind int

EventKind says what an Event reports.

const (
	// Requested means Joiner asks to join through a Manual invite, with its Data; answer with Approve or Deny.
	// Requested events are never dropped.
	Requested EventKind = iota + 1
	// Withdrawn means a request reported by Requested left before Approve or Deny: the joiner left or the invite ended.
	Withdrawn
	// Joined means Joiner was accepted, with its Data; Request is set for a Manual invite.
	Joined
	// Ended means the invite reached State: expired, used up or revoked.
	Ended
)

The event kinds.

func (EventKind) String
func (k EventKind) String() string

String returns the kind's name.

type ID

type ID [16]byte

ID identifies an invite; it is derived from the invite secret and reveals nothing about it.

func (ID) String
func (id ID) String() string

String returns the ID as hex.

type Info

type Info struct {
	ID      ID
	Created time.Time
	// Expires is the end of the TTL, zero for none.
	Expires time.Time
	// Ended is when the invite stopped being usable, zero while Active.
	Ended   time.Time
	MaxUses int
	Used    int
	Manual  bool
	// Device is set for a link-a-device invite made by CreateDevice.
	Device bool
	State  State
}

Info describes an invite.

type Inviter

type Inviter struct {
	// contains filtered or unexported fields
}

Inviter creates invites and answers the requests that use them. It is safe for concurrent use.

func Open
func Open(db kolostore.Backend, id *koloid.Identity, opts *Options) (*Inviter, error)

Open loads the invites stored in db, a kolo-store backend used for nothing else, for the inviter id. It does not close db. The backend holds the secrets and payloads of live invites in clear: keep it private.

func (Inviter) Announce
func (in *Inviter) Announce(ctx context.Context, sw *koloswarm.Swarm) error

Announce keeps sw joined, announce only, to the topics of the live invites, oldest first, until ctx ends or the Inviter is closed, then leaves them. It never reads sw's events. sw must be opened with the Inviter's identity. A topic sw cannot join (MaxTopics, a network error) is tried again with backoff from 1s to 1 minute. One Announce runs at a time; another returns ErrBusy.

func (Inviter) Approve
func (in *Inviter) Approve(req RequestID, payload []byte) error

Approve accepts a pending request and sends payload (at most 1 GiB) to the joiner. It returns ErrExpired, ErrUsedUp or ErrRevoked if the invite ended, also when that ended the request, and ErrNotFound if the joiner left.

func (Inviter) ApproveApprover
func (in *Inviter) ApproveApprover(m DeviceMatch, a *ApproverApproval) error

ApproveApprover links the matched device as an APPROVER of the person key a.Person derives, signed once and cleared at once. The words never reach this library or the network. The other errors are those of ApproveDevice.

func (Inviter) ApproveDevice
func (in *Inviter) ApproveDevice(m DeviceMatch, a *DeviceApproval) error

ApproveDevice links the matched device as an ordinary device of the person of a.Cert. ErrNotApprover means a.Cert is not an unexpired approver certificate of a.Signer; the other errors are those of Approve. The signed offer reaches the new device inside the answer.

func (Inviter) Close
func (in *Inviter) Close() error

Close stops the Inviter: Announce and ServePeer return ErrClosed and pending requests are left unanswered. Later calls return ErrClosed, except Stats. It does not close the backend. A second Close returns nil.

func (Inviter) Create
func (in *Inviter) Create(opts *CreateOptions) (string, Info, error)

Create makes a new invite, stores it, and returns its code and its Info. The code is the invite's secret: give it only to the joiner.

func (Inviter) CreateDevice
func (in *Inviter) CreateDevice(opts *DeviceOptions) (string, Info, error)

CreateDevice makes a link-a-device invite: Manual, one use, short-lived, burned by a refusal or an unanswered request. The code is the invite's secret: show it only to the new device. The rules are in docs/guide.md.

func (Inviter) Deny
func (in *Inviter) Deny(req RequestID) error

Deny refuses a pending request; the joiner gets ErrDenied, now and whenever it asks again with this invite. Like Approve, it checks the invite's state first and returns the same errors. A refusal of a link-a-device request also burns its code, in memory at once; a failed store write of that end is retried by the clock and is not an error here, and one that is still failing when the process stops is lost (the invite then lives on until its TTL).

func (Inviter) Joiners
func (in *Inviter) Joiners(id ID) ([]Joiner, error)

Joiners returns the joiners the invite accepted, from the store, in key order.

func (Inviter) List
func (in *Inviter) List() ([]Info, error)

List returns every stored invite, ended ones included, oldest first.

func (Inviter) MatchDevice
func (in *Inviter) MatchDevice(typed string) (DeviceMatch, error)

MatchDevice finds the pending link-a-device request whose fingerprint is typed, the digits the person read on the new device's screen (spaces are ignored). It returns ErrFingerprint when none matches. The comparison takes the same time for every digit.

func (Inviter) Next
func (in *Inviter) Next(ctx context.Context) (Event, error)

Next returns the next event, waiting until there is one, ctx ends or the Inviter is closed.

func (Inviter) Revoke
func (in *Inviter) Revoke(id ID) error

Revoke ends an active invite now; pending requests are answered revoked. An invite that already ended is left as it is.

func (Inviter) ServePeer
func (in *Inviter) ServePeer(ctx context.Context, p Peer) error

ServePeer answers the invite requests p sends until its connection ends (nil), ctx ends (its error) or the Inviter is closed (ErrClosed). It must be the only caller of AcceptStream on p's connection. A peer whose shared topics are all invite topics, and that has had no stream for Timeout, is disconnected: knowing a topic is not enough to hold a connection.

func (Inviter) Stats
func (in *Inviter) Stats() Stats

Stats returns the Inviter's gauges and totals; it is safe to call at any time, also after Close.

type JoinOptions

type JoinOptions struct {
	// Data is sent to the inviter with the request, for example a display name; the inviter refuses more than its
	// MaxData (default 64 KiB) with ErrTooLarge.
	Data []byte
	// MaxPayload caps the payload JoinConn accepts, in bytes; a larger one is ErrTooLarge. Default 1 MiB.
	MaxPayload int
	// contains filtered or unexported fields
}

JoinOptions sets what JoinConn sends and accepts.

type Joiner

type Joiner struct {
	Key    ed25519.PublicKey
	Data   []byte
	Joined time.Time
}

Joiner is a joiner an invite accepted, as stored.

type LinkRequest

type LinkRequest struct {
	Request RequestID
	Invite  ID
	// Device is the key the request is signed with, the key that would be certified.
	Device ed25519.PublicKey
	// Name is the name the new device chose; it proves nothing, so two requests with one name differ only by their fingerprints.
	Name string
}

LinkRequest is what an approver shows for a pending link-a-device request. It has no fingerprint: the person types the one the new device shows into MatchDevice.

type Options

type Options struct {
	// Timeout bounds the messages of a stream until its request is decided, the write of each answer, and how long
	// a connection that shares only invite topics may stay without a stream. Default 30s.
	Timeout time.Duration
	// PendingTTL withdraws a request that waited this long for Approve or Deny, as if its joiner had left; the joiner
	// may ask again. Zero means a request waits until it is decided, the joiner leaves or the invite ends.
	PendingTTL time.Duration
	// MaxData caps the join data the Inviter receives in one request, in bytes. Default 64 KiB.
	MaxData int
	// MaxPending caps the requests waiting for Approve or Deny, all invites. Default 1024.
	MaxPending int
	// MaxPendingPerSource caps the pending requests from one source. Default 16.
	MaxPendingPerSource int
	// MaxPendingDevices caps the requests waiting for ApproveDevice, Approve or Deny on link-a-device invites, all invites
	// together; the next one is refused with ErrBusy. Default 4: one new device and a few retries.
	MaxPendingDevices int
	// DevicePendingTTL is how long a link-a-device request waits for a person; then it is withdrawn and the invite is
	// revoked, so the code is burned. Default 2 minutes.
	DevicePendingTTL time.Duration
	// MaxDeviceName caps the device name of a link-a-device request, in bytes. Default DefaultMaxDeviceName, range 1 to MaxData.
	MaxDeviceName int
	// MaxStreams caps the streams handled at once on one connection. Default 8.
	MaxStreams int
	// SourceRate caps the requests per minute from one source, in a bucket of that size. Default 60.
	SourceRate int
	// InviteRate caps the requests per minute for one invite, in a bucket of that size. Default 600.
	InviteRate int
	// MaxSources caps the sources the rate limiter tracks; a new source past it is rate limited. Default 4096.
	MaxSources int
	// MaxEvents caps the queued Joined, Withdrawn and Ended events; past it the oldest is dropped. Default 1024.
	MaxEvents int
}

Options sets the safety bounds of an Inviter. A zero field takes its default; a negative one is ErrInvalidArgument.

type Peer

type Peer interface {
	Conn() koloswarm.Conn
	Addr() netip.AddrPort
	PublicKey() ed25519.PublicKey
	Topics() []koloswarm.Topic
}

Peer is a connected peer as kolo-swarm reports it in a Connected event; *koloswarm.Peer satisfies it.

type RequestID

type RequestID uint64

RequestID identifies a pending request for Approve and Deny; it stays the same when the joiner asks again.

type State

type State int

State is the state of an invite.

const (
	// Active means the invite can be used.
	Active State = iota + 1
	// Expired means the invite's TTL is over on the inviter's clock.
	Expired
	// UsedUp means the invite accepted MaxUses joiners.
	UsedUp
	// Revoked means Revoke ended the invite.
	Revoked
)

The invite states.

func (State) String
func (s State) String() string

String returns the state's name.

type Stats

type Stats struct {
	Active    int // invites that can be used
	Ended     int // invites that ended, lingering ones included
	Announced int // invite topics Announce has joined on the swarm
	Pending   int // requests waiting for Approve or Deny

	Requests       uint64 // requests received
	Accepted       uint64 // joiners accepted, each counted once
	Denied         uint64 // Deny calls that answered a request
	RefusedInvalid uint64 // requests that did not authenticate
	RefusedLimited uint64 // requests refused by a rate limit
	RefusedBusy    uint64 // requests refused for MaxPending, MaxPendingPerSource or a storage error
	RefusedEnded   uint64 // requests answered expired, used up or revoked
	RefusedLarge   uint64 // requests over MaxData
	StreamsRefused uint64 // streams reset past MaxStreams
	IdleClosed     uint64 // connections closed for sharing only invite topics without a stream for Timeout
	EventsDropped  uint64 // events dropped past MaxEvents
}

Stats are an Inviter's gauges and totals; the totals only grow.

Conviene saber

Todos los pasos

Usos, caducidad y revocación

La caducidad y los usos solo están en el almacén de quien invita, nunca en el código.

  1. Una invitación empieza Active, con una caducidad (ninguna si el TTL es 0) y un número de usos (1 si no se indica). Aquí tiene 3.
  2. Aceptar cuenta un uso y guarda a quien se une. Si vuelve a preguntar, recibe la misma respuesta y no se cuenta ningún uso.
  3. Denegar guarda un no para esa persona y no gasta ningún uso. La invitación sigue Active para los demás.
  4. La invitación termina en un estado: UsedUp cuando se gasta el último uso, Expired al llegar su caducidad, Revoked cuando la revocas. Revoked gana a UsedUp, y UsedUp a Expired.
  5. Cinco minutos después del final se borra el secreto y se abandona el topic, así que el código deja de funcionar. Revocar no quita nada a los peers que ya se unieron.

Límites

  • Solo IPv4, como kolo-swarm. Los límites de frecuencia cuentan por origen: la dirección IPv4 remota de la conexión, o su clave remota si no tiene dirección.
  • Options reúne los límites de quien invita. Un campo a cero toma su valor por defecto, y uno negativo es ErrInvalidArgument.
  • Timeout, 30s: limita los mensajes de un stream hasta que se decide su petición, y la escritura de cada respuesta. Un peer que solo comparte topics de invitación con quien invita y lleva ese tiempo sin ningún stream se desconecta. La comprobación se hace cada Timeout/4, así que el cierre llega entre Timeout y 1,25 veces Timeout.
  • MaxData, 64 KiB (como mucho 1 GiB): los datos de unión de una petición. Más es ErrTooLarge, y se rechaza por la longitud de la trama antes de leer los datos.
  • MaxPending, 1024: peticiones que esperan Approve o Deny, sumando todas las invitaciones. MaxPendingPerSource, 16: lo mismo, desde un solo origen. Por encima de cualquiera de los dos, una petición recibe ErrBusy.
  • PendingTTL, ninguno por defecto: cuánto espera una petición Manual a Approve o Deny antes de retirarse, como si su solicitante se hubiera ido. Cero espera hasta que se decide, así que una aplicación que expone invitaciones Manual ampliamente debería fijarlo, por ejemplo en una hora: sin él, quien tenga un código puede mantener peticiones pendientes hasta llenar MaxPending.
  • MaxStreams, 8: streams atendidos a la vez en una conexión. Los que sobran se cancelan.
  • Los datos de unión son un nombre o una clave, no un archivo: mantén MaxData pequeño. Un frame se lee en un búfer que crece con los bytes que llegan, así que un peer que envía solo una cabecera no hace que el invitador reserve nada para la longitud declarada, pero uno que envía el cuerpo entero puede hacer que un stream retenga hasta MaxData bytes (MaxStreams por MaxData por conexión).
  • El backend guarda en claro los secretos y las cargas de las invitaciones vivas, así que mantenlo privado.
  • SourceRate, 60 peticiones por minuto desde un origen, e InviteRate, 600 por minuto para una invitación, cada uno con ráfagas de hasta ese número. Por encima de cualquiera de los dos, una petición recibe ErrRateLimited.
  • MaxSources, 4096: orígenes que sigue el limitador de frecuencia. Se olvida un origen cuyo margen ya se ha recargado del todo, y un origen nuevo queda limitado cuando no se puede olvidar ninguno.
  • MaxEvents, 1024: eventos Joined, Withdrawn y Ended en cola. Por encima, se descarta el más antiguo y se cuenta en Stats.EventsDropped. Los eventos Requested nunca se descartan, y nunca hay más que peticiones pendientes.
  • JoinOptions.MaxPayload, 1 MiB: la carga útil más grande que acepta quien se une. Más es ErrTooLarge.
  • MaxPendingDevices, 4: peticiones pendientes de invitaciones para vincular un dispositivo, sumando todas las invitaciones. Por encima, una petición recibe ErrBusy.
  • MaxDeviceName, 64 bytes (de 1 a MaxData): el nombre de un dispositivo nuevo. Un nombre son letras, números, marcas, puntuación y símbolos en UTF-8 con un solo espacio entre ellos, sin espacio al principio, al final ni doble, y sin caracteres de control, de formato, invisibles o ignorables por defecto. Cualquier otro nombre se rechaza como inválido.
  • DevicePendingTTL, 2 minutos: cuánto espera una petición para vincular un dispositivo a la persona antes de retirarse y quemar su código. DeviceOptions.TTL, 5 minutos por defecto, es cuánto dura un código de dispositivo; se admite cualquier valor positivo.
  • En el dispositivo nuevo, DeviceJoinOptions.MaxName es 64 bytes y MaxPayload 4096 bytes; una respuesta ocupa menos de 600 bytes. Una oferta ocupa como mucho 450 bytes, el límite de kolo-id.
  • El registro guardado de una invitación de dispositivo es la versión 1 y termina con una marca device. Los demás registros de invitación son de la versión 0.
  • CreateOptions: un TTL a cero no caduca nunca. Un MaxUses a cero significa 1, y no hay límite superior. Payload ocupa como mucho 1 GiB y tiene que estar vacío con Manual; para una carga útil distinta por persona, usa Manual y llama a Approve desde el código.
  • Las cargas útiles y los datos de unión ocupan como mucho 1 GiB, porque la longitud de una trama es un uint32. Las tramas OPEN y CHALLENGE ocupan como mucho 64 bytes. Cualquier otra trama ocupa como mucho max(512, Padmé(n + 256)) + 256 bytes, donde n es MaxData para las peticiones, en quien invita, o MaxPayload para las respuestas, en quien se une, y una más larga se rechaza por su longitud antes de leer su cuerpo.
  • Un código tiene 92 caracteres: koloinv0 (el 0 es la versión del formato) y base32. Parse lo acepta todo en minúsculas o todo en mayúsculas, y no recorta espacios.
  • Linger, 5 minutos: cuánto tiempo una invitación terminada sigue anunciada y sigue respondiendo. Después se borra su secreto y se abandona su topic, y quien perdió su aceptación ya no puede recuperarla.
  • Announce comparte el MaxTopics del swarm (por defecto 16 en kolo-swarm, como mucho 32) con los topics propios de la aplicación, y toma para las invitaciones todos los que queden libres, las más antiguas primero. Únete a tus propios topics antes de arrancar Announce, o sube MaxTopics para que quepan todos: un Join posterior puede fallar con el error de MaxTopics de kolo-swarm. Un topic al que el swarm no puede unirse (no quedan libres, un error de red) se reintenta con una espera creciente de 1s a 1 minuto; Stats.Announced muestra cuántos están anunciados. Nadie que quiera unirse encuentra una invitación contada en Stats.Active pero no anunciada: solo se llega a ella por una conexión que ya exista. Una invitación antigua que nunca caduca y nunca se usa conserva su topic, y las más nuevas esperan detrás: dales un TTL, o revoca con Revoke las que ya no necesites.
  • El swarm de quien se une busca un topic al unirse a él y después cada LookupInterval (por defecto 10 minutos en kolo-swarm) más hasta una quinta parte de ese tiempo al azar. Quien se une antes de que quien invita esté en línea puede esperar ese tiempo, hasta unos 12 minutos por defecto; un LookupInterval más corto ayuda.
  • Approve y Deny comprueban primero el estado de la invitación y devuelven ErrExpired, ErrUsedUp o ErrRevoked si terminó, también cuando ese final es lo que terminó la petición (por ejemplo, la otra de dos peticiones pendientes de una invitación de un solo uso después de aprobar la primera). Recuerdan las últimas MaxPending peticiones así.
  • El almacenamiento solo crece con lo que hace la aplicación, nunca con lo que envían los peers: un registro por invitación (unos 100 bytes más su carga útil), uno por persona aceptada (su carga útil y sus datos) y una marca por cada Deny. Los registros de las invitaciones terminadas se quedan, para List y Joiners.

Seguridad

  • El código lleva una huella de 16 bytes de la clave de quien invita. Quien se une solo habla con un peer cuya clave de kolo-secure autenticada coincide con ella, y después vincula la clave completa a la petición. Hacerse pasar por quien invita exige una segunda preimagen de un valor de 128 bits para esa clave concreta.
  • El secreto tiene 256 bits y nunca llega a la red. La DHT ve un topic derivado de él en un solo sentido, y la petición viaja sellada con HPKE (RFC 9180) dentro de una conexión de kolo-secure, firmada por la clave de kolo-id de quien se une con el contexto kolo-invite/request/v0. No se puede adivinar offline, así que no se usa ningún PAKE.
  • Los servidores de la DHT que guardan el topic de una invitación ven la clave y la dirección de quien la anuncia y de cada peer que la busca. Pueden relacionar la dirección de quien se une con la clave de quien invita en el momento de la unión, y ver cuánto tiempo sigue anunciada la invitación. No pueden saber qué invitación es, ni leer la petición ni responderla. Una conexión que ya tengas con quien invita se ahorra la búsqueda.
  • Cada stream empieza con un desafío nuevo de 32 bytes de quien invita, vinculado a la petición. Una petición capturada falla en cualquier otro stream, y un stream admite una sola petición.
  • Los usos se cuentan en un único lote duradero del almacén antes de enviar la respuesta, bajo un solo cerrojo, así que las uniones simultáneas nunca superan MaxUses. Quien vuelve a preguntar después de ser aceptado recibe la misma carga útil y no gasta ningún uso. Un rechazo se guarda igual: esa persona recibe ErrDenied cada vez que vuelve a preguntar con esta invitación.
  • La caducidad solo se comprueba con el reloj de quien invita, sin margen; quien se une no envía ninguna hora. Un Approve después de la caducidad es ErrExpired, incluso para una petición que llegó antes. Cuando quien invita ve un final, lo guarda, y retrasar el reloj nunca reabre la invitación. Retrasarlo antes de eso alarga la invitación lo mismo, y adelantarlo la termina antes.
  • Las peticiones y las respuestas se rellenan hasta longitudes Padmé con un mínimo de 512 bytes, así que un rechazo, una negativa y una aceptación con una carga útil de hasta 508 bytes tienen el mismo tamaño en la red. Quien invita siempre envía RECEIVED antes de decidir o de dar una negativa, sea manual o no, también para una petición que se niega por su tamaño. Las cargas útiles y los datos de unión más grandes muestran su franja Padmé, como mucho alrededor de un 12 % por encima de su tamaño, y el tiempo hasta la respuesta sigue delatando una decisión manual.
  • Las invitaciones desconocidas y las peticiones que no se descifran o no se verifican reciben el mismo ErrInvalid. Los IDs y los topics salen del secreto de 256 bits y no se pueden enumerar. Una clave de respuesta o una clave encapsulada de orden bajo se rechaza antes de decidir o contar nada.
  • Los límites de frecuencia se aplican antes de cualquier trabajo de HPKE o de firma. Quien tenga un código Manual aún puede llenar MaxPending con muchas claves desde muchas direcciones. Quien invita ve cada una como un evento Requested y puede usar Deny o Revoke.
  • Las respuestas se sellan para una clave que quien se une crea en cada petición y no van firmadas: vienen de la clave de quien invita, por una conexión ligada a ella.
  • Un Code guarda su secreto detrás de un puntero e imprime solo su ID, también dentro de otros valores. Stats no contiene IDs, claves ni direcciones, así que se puede exportar como métricas con etiquetas fijas.
  • Revoke detiene las uniones nuevas y nada más. Quien ya fue aceptado conserva la carga útil que recibió, como cualquier peer conserva lo que ya le llegó.
  • El código de una invitación de dispositivo es el punto débil: quien lo vea puede enviar una petición antes que el dispositivo real. La persona tiene que teclear en MatchDevice los 12 dígitos que muestra el dispositivo nuevo, y las llamadas de aprobación solo aceptan el DeviceMatch que devuelve. Una aplicación que muestra los dígitos en la pantalla del aprobador para pulsarlos, o que los calcula ella misma, pierde esta barrera.
  • Los dígitos son HKDF-SHA256 (RFC 5869) sobre el secreto de la invitación, ligado a la clave de quien invita y a la del dispositivo, leído módulo 10^12: 39,9 bits. En la máquina que midió el repositorio, encontrar una clave de dispositivo con una huella de 12 dígitos elegida lleva unos 127 días de núcleo, y hacerlo dentro de los 2 minutos que puede esperar una petición exigiría unos 90 000 núcleos. Son cifras medidas y extrapoladas.
  • Una petición de dispositivo rechazada o sin respuesta quema el código en memoria al momento, aunque falle el disco. Quien tenga un código puede llenar MaxPendingDevices y bloquear el dispositivo real; el aprobador ve cada petición y puede revocar el código con Revoke y empezar de nuevo.
  • Solo un dispositivo aprobador vincula un dispositivo, así que un dispositivo normal robado no puede vincular nada. Un aprobador robado puede vincular dispositivos hasta que se revoque, como dicen las notas de seguridad de kolo-id.
  • Las 24 palabras nunca viajan en una invitación ni en ningún mensaje: ApproveApprover llama a una función que deriva la clave de persona, firma una vez y borra la clave.
  • El dispositivo nuevo comprueba lo que recibe: un certificado para otra clave de dispositivo, para otra persona distinta de la que fijó, firmado por una tercera clave o con una firma incorrecta es ErrProtocol.
  • Un nombre puede imitar a otro con letras de aspecto parecido. Son los dígitos, no el nombre, los que identifican la petición.

Límites conocidos

  • ServePeer tiene que ser lo único que llama a AcceptStream en su conexión. Una aplicación que ejecuta otro protocolo de streams con el mismo peer decide en cada conexión cuál la atiende.
  • kolo-swarm no avisa al otro lado de un topic al que te unes más tarde en una conexión que ya existe. Después de JoinConn, quien se une abandona el topic de la invitación antes de unirse al topic del grupo: kolo-swarm cierra entonces al momento la conexión que solo era de la invitación, y el topic del grupo llega con una conexión nueva que lo lleva desde el principio. Si no, quien invita la ve solo con el topic de la invitación y la cierra pasado Timeout.
  • Las peticiones pendientes solo existen mientras quien se une espera en su stream, y ninguna sobrevive a un reinicio. Los eventos tampoco se guardan: Joiners es el registro duradero.
  • Close deja sin respuesta las peticiones pendientes, y quienes esperaban reciben ErrNotAnswered.
  • Todas las pruebas se ejecutan en 127.0.0.1, así que no se ha probado un paso de NAT real.
  • Experimental. La API puede cambiar antes de la v1.0.0.

Errores

ErrorMensaje
ErrBusyinvite: busy
ErrClosedinvite: closed
ErrDeniedinvite: denied
ErrExpiredinvite: expired
ErrFingerprintinvite: fingerprint does not match
ErrIDCollisioninvite: invite ID collision
ErrInvalidinvite: request refused as invalid
ErrInvalidArgumentinvite: invalid argument
ErrInvalidCodeinvite: invalid invite code
ErrNotAnsweredinvite: request not answered
ErrNotApproverinvite: signer is not an approver
ErrNotFoundinvite: not found
ErrPersonMismatchinvite: person key is not the expected one
ErrPersonRequiredinvite: expected person or FirstDevice required
ErrProtocolinvite: protocol error
ErrRateLimitedinvite: rate limited
ErrRevokedinvite: revoked
ErrTooLargeinvite: too large
ErrUnreachableinvite: inviter unreachable
ErrUsedUpinvite: used up

Comprueba los errores con errors.Is, porque la mayoría llegan envueltos con detalle, como invite: invalid invite code: checksum mismatch. Quien se une recibe la mayoría de las respuestas de quien invita como el propio valor de error: ErrDenied, ErrExpired, ErrUsedUp, ErrRevoked, ErrInvalid, ErrRateLimited o ErrBusy. ErrTooLarge llega envuelto: datos de unión por encima del MaxData de quien invita, datos de más de 1 GiB que JoinConn rechaza antes de enviar nada, o una carga útil por encima de MaxPayload. Un rechazo siempre llega como ErrDenied, nunca como un tiempo de espera agotado. ErrUnreachable (antes de que quien invita reciba la petición) y ErrNotAnswered (después) envuelven la causa, ctx.Err() incluido, y volver a preguntar es seguro. Del lado de quien invita, Approve y Deny devuelven ErrExpired, ErrUsedUp o ErrRevoked cuando la invitación terminó, y ErrNotFound cuando quien se une se fue, y un segundo Announce mientras otro está en marcha devuelve ErrBusy. Los errores del backend, tanto de lectura como de escritura y también los de Open, vuelven como invite: store: ... envolviendo el error del backend; tras una escritura fallida no cambia nada. Open, y Joiners para un registro de quien se unió, devuelven un error que envuelve kolostore.ErrCorrupt para datos guardados que no se decodifican o no cuadran. Con las invitaciones de dispositivo, MatchDevice devuelve ErrFingerprint cuando ninguna petición pendiente tiene los dígitos tecleados, ApproveDevice devuelve ErrNotApprover cuando su certificado no es un certificado de aprobador vigente del firmante, ApproveApprover y JoinDevice devuelven ErrPersonRequired sin una persona esperada ni FirstDevice, y ApproveApprover devuelve ErrPersonMismatch cuando la clave derivada no es ExpectPerson.

Referencias