kolo docsbeta

kolo-invite

Invite codes for a group. A member creates one, someone joins with it, and the member approves or denies.

On this page

An invite lets someone new into a group. A member, the inviter, creates an invite and gets a short code to send. The person who joins uses the code, and the inviter accepts the request at once or approves or denies it. The code 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 from the secret, or uses a connection it already has. The inviter keeps its invites and who joined in a kolo-store backend, so a restart keeps them. The join request and its answer are sealed with HPKE (RFC 9180), and every public value is derived from the invite secret with HKDF (RFC 5869), so the secret itself never travels. The Go package is named invite. A device invite links a new device to a person instead, with a kolo-id certificate.

All steps

Joining with an invite code

You pass the code to the joiner yourself. It holds no address: the joiner finds the inviter through the DHT.

  1. The inviter makes 32 random bytes, the secret. The code is koloinv0 and 84 base32 characters: a fingerprint of the inviter's key, the secret and a checksum. From the secret come the invite ID, a topic, an auth value and an encryption key.
  2. The inviter announces itself on the invite's topic. The joiner reads the code, looks the topic up and keeps only a peer whose key matches the fingerprint.
  3. The joiner sends OPEN and gets a fresh 32-byte challenge. Its REQUEST is sealed with HPKE to the invite's key: the auth value, its key, a key for the answer, its data and its signature.
  4. The inviter sends RECEIVED at once, then checks the request. An automatic invite accepts now; a manual one waits for Accept or Deny.
  5. ANSWER is sealed to the joiner's answer key: accepted with the payload, or denied, expired, used up or revoked.

Install

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

Needs Go 1.26 or later, for crypto/hpke. Builds without cgo. Invite someone to a group, in a terminal program goes through a full program step by step.

Quick start

This program runs a bootstrap node, an inviter and a joiner on loopback, with the invites in a temporary directory. Alice creates an invite that needs her approval, Bob joins with the code, and Alice approves him.

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)
}

It prints, with a new code each run:

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

The code is the only thing Alice sends to Bob, in any way she trusts. The application keeps its one swarm and its own event loop: Announce runs next to it, and the loop calls ServePeer on the inviter's side and JoinConn on the joiner's. Joiners reads the store, so that record survives a restart. The swarms here look their topics up every 5 seconds, since Bob may look before Alice has announced; with the kolo-swarm default he could wait up to about 12 minutes for the next lookup.

A device invite adds a new device to a person, with kolo-id device certificates. An approver device creates the invite, the new device shows 12 digits, the person types them on the approver, and the approver signs a certificate for the new device's key and returns it inside the sealed answer. The person key, derived from the 24 words, never lives on a device, and an invite never carries the words. This needs kolo-id v0.1.0.

On the approver device, whose identity is the one given to Open:

  • CreateDevice(opts) makes a Manual invite with one use. The code lasts DefaultDeviceTTL, 5 minutes, unless DeviceOptions.TTL sets another positive value, and Info.Device is true. Show the code to the new device only.
  • On a Requested event, PendingLink(req) returns the new device's key and the name it chose, never the digits. The person types the 12 digits the new device shows into MatchDevice(typed), which returns a DeviceMatch for the pending request with those digits, or ErrFingerprint. Spaces are ignored and the comparison takes constant time. When the same key asks again with another name, the match no longer applies (ErrNotFound) and the person types the digits again.
  • ApproveDevice(match, &DeviceApproval{...}) links an ordinary device. Signer is this device's identity, Cert its approver certificate and Serial the serial of the new certificate, at least 1, chosen by the caller. An expired approver certificate, or an ordinary one, is ErrNotApprover.
  • ApproveApprover(match, &ApproverApproval{...}) links an approver. Person is a function that derives the person key from the 24 words typed on this device, for example with koloid.Phrase.Person. It runs only after the match is checked, and the key it returns is used once and cleared before the call returns, on success and on every error. Exactly one of ExpectPerson (the person this device already belongs to) and FirstDevice is required, or the call returns ErrPersonRequired. Another person key, such as a mistyped phrase with a valid checksum, is ErrPersonMismatch and signs nothing.
  • Deny(req) refuses a device request and burns the code. A request nobody answers within Options.DevicePendingTTL, 2 minutes by default, is withdrawn and burns the code too. A joiner that cancels does not burn it, and one that asks again keeps the deadline of its first request. Approve on a device invite is ErrInvalidArgument.

On the new device, DeviceFingerprint(code, inviterKey, deviceKey) gives the 12 digits to show, and JoinDevice sends the request and returns a DeviceLink with the person key and the finished certificate. DeviceJoinOptions needs exactly one of Person, the person key the device expects, and FirstDevice, or the call returns ErrPersonRequired. JoinDevice checks that the certificate names this device's key, chains to the person key, has valid signatures and was signed by the inviter or by the person key. Anything else is ErrProtocol. Save the certificate with koloid.SaveCert and present it to groups with the devices package of kolo-braid.

This program is examples/linkdevice from the repository. A laptop links a phone as an ordinary device and a tablet as an approver, on loopback and in memory.

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
		}
	}
}

It prints, with other digits each run:

Text
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

The digits are typed, never clicked: an application must not compute them on the approver or show them there to be confirmed, because the barrier holds only while the person types what the new device shows. To make an ordinary device an approver without an invite, the person types the 24 words on that device, which checks that the derived key equals DeviceLink.Person and certifies itself with kolo-id; nothing travels.

API reference

The API reference is generated from the Go source and is in English.

Package 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.

Constants

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")
)

Functions

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.

Types

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.

Good to know

All steps

Uses, expiry and revoke

The expiry and the uses live only in the inviter's store, never in the code.

  1. An invite starts Active, with an expiry (none when the TTL is 0) and a number of uses (1 when not set). Here it has 3.
  2. Accept counts one use and stores the joiner. If that joiner asks again, it gets the same answer and no use is counted.
  3. Deny stores a no for that joiner and uses nothing. The invite stays Active for others.
  4. The invite ends in one state: UsedUp when the last use is taken, Expired at its expiry time, Revoked when you revoke it. Revoked wins over UsedUp, and UsedUp over Expired.
  5. Five minutes after the end, the secret is erased and the topic is left, so the code stops working. Revoke takes nothing back from peers who already joined.

Limits

  • IPv4 only, like kolo-swarm. The rate limits count per source: the connection's remote IPv4 address, or its remote key when it has none.
  • Options holds the inviter's bounds. A zero field takes its default, and a negative one is ErrInvalidArgument.
  • Timeout, 30s: bounds the messages of a stream until its request is decided, and the write of each answer. A peer that shares only invite topics with the inviter and has had no stream for that long is disconnected. The check runs every Timeout/4, so the close comes between Timeout and 1.25 times Timeout.
  • MaxData, 64 KiB (at most 1 GiB): the join data of one request. More is ErrTooLarge, refused from the frame length before the data is read.
  • MaxPending, 1024: requests waiting for Approve or Deny, over all invites. MaxPendingPerSource, 16: the same, from one source. Past either, a request gets ErrBusy.
  • PendingTTL, none by default: how long a Manual request waits for Approve or Deny before it is withdrawn, as if its joiner had left. Zero waits until it is decided, so an application that exposes Manual invites widely should set it, for example to an hour: without it a holder of a code can keep requests pending until MaxPending is full.
  • MaxStreams, 8: streams handled at once on one connection. More are reset.
  • Join data is a name or a key, not a file: keep MaxData small. A frame is read into a buffer that grows with the bytes that arrive, so a peer that sends only a header makes the inviter allocate nothing for the declared length, but one that sends the whole body can make a stream hold up to MaxData bytes (MaxStreams times MaxData per connection).
  • The backend holds the secrets and payloads of live invites in clear, so keep it private.
  • SourceRate, 60 requests per minute from one source, and InviteRate, 600 per minute for one invite, each in a bucket of that size. Past either, a request gets ErrRateLimited.
  • MaxSources, 4096: sources the rate limiter tracks. A full bucket is forgotten, and a new source is rate limited when none can be.
  • MaxEvents, 1024: queued Joined, Withdrawn and Ended events. Past it the oldest is dropped and counted in Stats.EventsDropped. Requested events are never dropped, and there are never more of them than pending requests.
  • JoinOptions.MaxPayload, 1 MiB: the largest payload a joiner accepts. More is ErrTooLarge.
  • MaxPendingDevices, 4: pending requests of link-a-device invites, over all invites. Past it, a request gets ErrBusy.
  • MaxDeviceName, 64 bytes (1 to MaxData): the name of a new device. A name is UTF-8 letters, numbers, marks, punctuation, symbols and single spaces between them, with no leading, trailing or double space and no control, format, invisible or default-ignorable character. Any other name is refused as invalid.
  • DevicePendingTTL, 2 minutes: how long a link-a-device request waits for the person before it is withdrawn and its code burned. DeviceOptions.TTL, 5 minutes by default, is how long a device code lasts; any positive value is allowed.
  • On the new device, DeviceJoinOptions.MaxName is 64 bytes and MaxPayload 4096 bytes; an answer is under 600 bytes. An offer is at most 450 bytes, the kolo-id bound.
  • The stored record of a link-a-device invite is version 1 and ends with a device flag. Every other invite record is version 0.
  • CreateOptions: a zero TTL never expires. A zero MaxUses means 1, and there is no upper bound. Payload is at most 1 GiB and must be empty with Manual; for a payload per joiner, use Manual and call Approve from code.
  • Payloads and join data are at most 1 GiB, since a frame length is a uint32. OPEN and CHALLENGE frames are at most 64 bytes. Every other frame is at most max(512, Padmé(n + 256)) + 256 bytes, where n is MaxData for requests on the inviter or MaxPayload for answers on the joiner, and a longer one is refused from its length before its body is read.
  • A code is 92 characters: koloinv0 (the 0 is the format version) and base32. Parse takes it all in lower case or all in upper case, and does not trim spaces.
  • Linger, 5 minutes: how long an ended invite stays announced and still answers. Then its secret is erased and its topic left, and a joiner whose accept was lost can no longer get it again.
  • Announce shares the swarm's MaxTopics (kolo-swarm default 16, at most 32) with the application's own topics, and takes every free one for invites, oldest first. Join your own topics before you start Announce, or raise MaxTopics to fit both: a Join after it can fail with kolo-swarm's MaxTopics error. A topic the swarm cannot join (no free topic, a network error) is tried again with a backoff from 1s to 1 minute; Stats.Announced shows how many are announced. An invite counted in Stats.Active but not announced cannot be found by joiners, only reached on a connection they already have. An old invite that never expires and is never used keeps its topic, and newer ones wait behind it: give invites a TTL, or Revoke the ones you no longer need.
  • A joiner's swarm looks a topic up when it joins it, then every LookupInterval (kolo-swarm default 10 minutes) plus up to a fifth of it at random. A joiner that starts before the inviter is online can wait that long, up to about 12 minutes by default; a shorter LookupInterval helps.
  • Approve and Deny check the invite's state first, and return ErrExpired, ErrUsedUp or ErrRevoked when it ended, also when that end is what ended the request (for example the other of two pending requests on a single-use invite after the first was approved). They remember the last MaxPending such requests.
  • Storage grows only with what the application does, never with peer input: one record per invite (about 100 bytes plus its payload), one per accepted joiner (its payload and data), one marker per Deny. Records of ended invites stay, for List and Joiners.

Security

  • The code holds a 16-byte fingerprint of the inviter's key. The joiner talks only to a peer whose authenticated kolo-secure key matches it, then binds the full key into the request. Posing as the inviter needs a second preimage of a 128-bit value for that one key.
  • The secret has 256 bits and never reaches the network. The DHT sees a topic derived one way from it, and the request travels sealed with HPKE (RFC 9180) inside a kolo-secure connection, signed by the joiner's kolo-id key with the context kolo-invite/request/v0. It cannot be guessed offline, so no PAKE is used.
  • The DHT servers that store an invite's topic see the key and address of the inviter that announces it and of every peer that looks it up. They can link a joiner's address to the inviter's key at the time of the join, and see how long the invite stays announced. They cannot tell which invite it is, read the request or answer it. A connection you already have with the inviter skips the lookup.
  • Every stream starts with a fresh 32-byte challenge from the inviter, bound into the request. A captured request fails on any other stream, and a stream takes one request.
  • Uses are counted in one durable store batch before the answer is sent, under one lock, so concurrent joins never go over MaxUses. A joiner that asks again after being accepted gets the same payload and uses nothing. A deny is stored the same way: that joiner gets ErrDenied every time it asks again with this invite.
  • Expiry is checked only against the inviter's clock, with no leeway; the joiner sends no time. An Approve after the expiry is ErrExpired, even for a request that came in before. Once the inviter sees an end, it stores it, and a clock set back never reopens the invite. A clock set back before that extends the invite by as much, and one set forward ends it early.
  • Requests and answers are padded to Padmé lengths with a 512-byte floor, so a deny, a refusal and an accept with a payload of up to 508 bytes look the same size on the wire. The inviter always sends RECEIVED before it decides or refuses, manual or not, also for a request refused for its size. Larger payloads and join data show their Padmé bucket, at most about 12% above their size, and the time to an answer still shows a manual decision.
  • Unknown invites, and requests that do not decrypt or verify, get the same ErrInvalid. IDs and topics come from the 256-bit secret and cannot be enumerated. A low-order answer key or encapsulated key is refused before anything is decided or counted.
  • Rate limits run before any HPKE or signature work. Someone who holds a Manual code can still fill MaxPending with many keys from many addresses. The inviter sees each one as a Requested event and can Deny or Revoke.
  • Answers are sealed to a key the joiner makes for each request and are not signed: they come from the inviter's key, on a connection pinned to it.
  • A Code keeps its secret behind a pointer and prints only its ID, also inside other values. Stats holds no IDs, keys or addresses, so it can be exported as metrics with fixed labels.
  • Revoke stops new joins, nothing more. A joiner that was accepted keeps the payload it got, as any peer keeps what it already received.
  • The code of a device invite is the weak point: someone who sees it can send a request before the real device. The person must type the 12 digits the new device shows into MatchDevice, and the approve calls take only the DeviceMatch it returns. An application that shows the digits on the approving screen to be clicked, or computes them itself, loses this barrier.
  • The digits are HKDF-SHA256 (RFC 5869) over the invite secret, bound to the inviter's key and the device key, read modulo 10^12: 39.9 bits. On the machine the repository measured, finding a device key with a chosen 12-digit fingerprint takes about 127 core-days, and doing it within the 2 minutes a request may wait would take about 90 000 cores. These figures are measured and extrapolated.
  • A refused or unanswered device request burns the code in memory at once, even when the disk fails. Someone who holds a code can fill MaxPendingDevices and block the real device; the approver sees every request and can Revoke the code and start again.
  • Only an approver device links a device, so a stolen ordinary device cannot link anything. A stolen approver can link devices until it is revoked, as the kolo-id security notes say.
  • The 24 words never travel in an invite or any message: ApproveApprover calls a function that derives the person key, signs once and clears the key.
  • The new device checks what it gets: a certificate for another device key, for another person than the one it pinned, signed by a third key or with a bad signature is ErrProtocol.
  • A name can imitate another with look-alike letters. The digits, not the name, identify the request.

Known limits

  • ServePeer must be the only caller of AcceptStream on its connection. An application that runs another stream protocol with the same peer decides per connection which one serves it.
  • kolo-swarm does not tell the other side about a topic joined later on an existing connection. After JoinConn, a joiner leaves the invite topic before it joins the group's topic: kolo-swarm then closes the invite-only connection at once, and the group topic comes with a new connection that carries it from the start. Otherwise the inviter sees it with the invite topic only and closes it after Timeout.
  • Pending requests live only while their joiner waits on its stream, and none survives a restart. Events are not stored either: Joiners is the durable record.
  • Close leaves pending requests unanswered, and their joiners get ErrNotAnswered.
  • All tests run on 127.0.0.1, so real NAT traversal is not tested.
  • Experimental. The API may change before v1.0.0.

Errors

ErrorMessage
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

Test errors with errors.Is, since most come wrapped with detail, such as invite: invalid invite code: checksum mismatch. A joiner gets most of the inviter's answers as the error value itself: ErrDenied, ErrExpired, ErrUsedUp, ErrRevoked, ErrInvalid, ErrRateLimited or ErrBusy. ErrTooLarge comes wrapped: join data over the inviter's MaxData, data over 1 GiB that JoinConn refuses before it sends anything, or a payload over MaxPayload. A deny always arrives as ErrDenied, never as a timeout. ErrUnreachable (before the inviter received the request) and ErrNotAnswered (after) wrap the cause, ctx.Err() included, and asking again is safe. On the inviter, Approve and Deny return ErrExpired, ErrUsedUp or ErrRevoked when the invite ended and ErrNotFound when the joiner left, and a second Announce while one runs returns ErrBusy. Backend errors, reads and writes alike, Open's included, come back as invite: store: ... wrapping the backend's error; after a failed write nothing changes. Open, and Joiners for a stored joiner record, return an error wrapping kolostore.ErrCorrupt for stored data that does not decode or check out. For device invites, MatchDevice returns ErrFingerprint when no pending request has the typed digits, ApproveDevice returns ErrNotApprover when its certificate is not an unexpired approver certificate of the signer, ApproveApprover and JoinDevice return ErrPersonRequired without an expected person or FirstDevice, and ApproveApprover returns ErrPersonMismatch when the derived key is not ExpectPerson.

References