kolo docsbeta

Invite someone to a group, in a terminal program

A step-by-step guide. A member makes an invite code, someone joins with it, and the member approves, denies or revokes.

On this page

A group needs a way to let someone new in. With kolo-invite, a member makes an invite code and sends it to the person, in a chat or a message. That person runs the app with the code, the member sees the request and answers yes or no, and the new member gets what it needs to find the group.

In this guide you write one small program and run it twice: as Alice, who starts a group, and as Bob, who joins it. Then you try a deny, a revoke and an expiry. Everything stays on your computer, on the address 127.0.0.1, with a bootstrap node in a third terminal.

1Check what you need

You need Go 1.26 or newer and four terminal windows. Build a chat in your terminal shows how to install Go. Open the four windows and keep them side by side:

Open the Terminal app and press Cmd+N three times for three more windows.

Here Terminal 1 runs the bootstrap node, Terminal 2 runs Alice, Terminal 3 runs Bob and the fourth terminal runs the people who try to join later.

2Create a module and get the libraries

In Terminal 2, make a folder for the program and go into it:

bash
mkdir kolo-group && cd kolo-group

Create a Go module and add the four Kolo libraries the program uses: kolo-invite for the invites, kolo-swarm to find and connect to peers, kolo-store to keep the invites on disk and kolo-id for each member's key.

Terminal
go mod init example.com/kolo-group
Terminal
go get github.com/ciranda-dev/kolo-invite@v0.1.0 github.com/ciranda-dev/kolo-swarm@v0.1.0 github.com/ciranda-dev/kolo-store@v0.1.0 github.com/ciranda-dev/kolo-id@v0.1.0

Go downloads them with what they need and adds them to go.mod.

3Write the program

Create a file named main.go in the kolo-group folder and paste this program into it. Each member runs it with a folder of its own, -dir, for its key, its invites and the group's topic. Without -join it starts a new group, or goes back to the one it is in. With -join it asks to join with an invite code.

main.go
// Command group runs one member of a small group: it makes invite codes, answers join requests, or joins with a code.
package main

import (
	"bufio"
	"context"
	"crypto/rand"
	"errors"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"log"
	"net/netip"
	"os"
	"os/signal"
	"path/filepath"
	"slices"
	"strings"
	"time"

	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 main() {
	boot := flag.String("bootstrap", "127.0.0.1:7447", "IP:PORT of the bootstrap node")
	dir := flag.String("dir", "", "folder for this member's key and invites (required)")
	join := flag.String("join", "", "invite code to join a group with")
	name := flag.String("name", "", "name sent with the join request")
	ttl := flag.Duration("ttl", 10*time.Minute, "how long a new invite can be used")
	flag.Parse()
	if *dir == "" {
		log.Fatal("-dir is required")
	}
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	log.SetFlags(log.Ltime)
	if err := run(ctx, *boot, *dir, *join, *name, *ttl); err != nil && ctx.Err() == nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context, boot, dir, join, name string, ttl time.Duration) error {
	server, err := netip.ParseAddrPort(boot)
	if err != nil {
		return err
	}
	// An invite code names this key, so it must stay the same across runs.
	id, err := loadIdentity(filepath.Join(dir, "identity.key"))
	if err != nil {
		return err
	}
	db, err := kolostore.OpenPebble(filepath.Join(dir, "invites"))
	if err != nil {
		return err
	}
	defer db.Close()
	in, err := invite.Open(db, id, nil)
	if err != nil {
		return err
	}
	defer in.Close()
	sw, err := koloswarm.New(ctx, "127.0.0.1:0", id, nil)
	if err != nil {
		return err
	}
	defer sw.Close()
	if err := sw.Bootstrap(ctx, []netip.AddrPort{server}); err != nil {
		return err
	}
	log.Printf("me %x", id.PublicKey()[:4])

	groupFile := filepath.Join(dir, "group")
	topic, err := readTopic(groupFile) // zero until this member is in a group
	if err != nil {
		return err
	}
	var code invite.Code
	joining := join != ""
	switch {
	case joining && topic != (koloswarm.Topic{}):
		return errors.New("already in a group")
	case joining:
		if code, err = invite.Parse(join); err != nil {
			return err
		}
		if err := sw.Join(ctx, code.Topic(), &koloswarm.JoinOptions{Lookup: true}); err != nil {
			return err
		}
		log.Printf("looking for the inviter of %s", code)
	default:
		if topic == (koloswarm.Topic{}) {
			rand.Read(topic[:])
			if err := os.WriteFile(groupFile, topic[:], 0o600); err != nil {
				return err
			}
			log.Print("started a new group")
		}
		if err := sw.Join(ctx, topic, nil); err != nil {
			return err
		}
		log.Print("in the group, type invite to make an invite code")
	}
	// Announce takes the swarm's free topics for invites, so it starts after the group topic is joined.
	go in.Announce(ctx, sw)

	peers := feed(ctx, sw.Next)
	invites := feed(ctx, in.Next)
	sc := bufio.NewScanner(os.Stdin)
	lines := feed(ctx, func(context.Context) (string, error) {
		if !sc.Scan() {
			return "", io.EOF
		}
		return strings.TrimSpace(sc.Text()), nil
	})
	answers := make(chan answer, 1)
	var waiting []invite.Event // join requests waiting for y or n, oldest first
	for {
		select {
		case <-ctx.Done():
			return ctx.Err()

		case ev := <-peers:
			switch {
			case ev.Kind == koloswarm.Lost:
				log.Printf("peer %x lost", ev.PublicKey[:4])
			case ev.Kind != koloswarm.Connected:
			case topic != (koloswarm.Topic{}) && slices.Contains(ev.Peer.Topics(), topic):
				log.Printf("member %x connected", ev.Peer.PublicKey()[:4])
			case joining && code.Matches(ev.Peer.PublicKey()):
				log.Printf("asking %x to let us in", ev.Peer.PublicKey()[:4])
				go func() { answers <- ask(ctx, ev.Peer, id, code, name) }()
			default:
				go in.ServePeer(ctx, ev.Peer)
			}

		case a := <-answers:
			if a.err != nil {
				return fmt.Errorf("join: %w", a.err)
			}
			// Leave the invite topic first: the group topic then comes on a new connection.
			sw.Leave(code.Topic())
			topic, joining = a.topic, false
			if err := os.WriteFile(groupFile, topic[:], 0o600); err != nil {
				return err
			}
			if err := sw.Join(ctx, topic, nil); err != nil {
				return err
			}
			log.Print("joined the group, type invite to make an invite code")

		case ev := <-invites:
			switch ev.Kind {
			case invite.Requested:
				waiting = append(waiting, ev)
				log.Printf("%x asks to join as %q: type y to approve or n to deny", ev.Joiner[:4], ev.Data)
			case invite.Withdrawn:
				waiting = slices.DeleteFunc(waiting, func(w invite.Event) bool { return w.Request == ev.Request })
				log.Printf("%x left before an answer", ev.Joiner[:4])
			case invite.Joined:
				log.Printf("%x joined as %q", ev.Joiner[:4], ev.Data)
			case invite.Ended:
				log.Printf("invite %.8s ended: %s", ev.Invite, ev.State)
			}

		case line := <-lines:
			if err := command(in, line, &waiting, topic, ttl); err != nil {
				log.Print(err)
			}
		}
	}
}

// command runs one line typed by the user.
func command(in *invite.Inviter, line string, waiting *[]invite.Event, topic koloswarm.Topic, ttl time.Duration) error {
	switch line {
	case "invite":
		if topic == (koloswarm.Topic{}) {
			return errors.New("join a group first")
		}
		s, info, err := in.Create(&invite.CreateOptions{TTL: ttl, Manual: true})
		if err != nil {
			return err
		}
		log.Printf("invite %.8s, valid until %s, for one person. Send them this code:", info.ID, info.Expires.Format(time.TimeOnly))
		fmt.Println(s)
	case "y", "n":
		if len(*waiting) == 0 {
			return errors.New("no request is waiting")
		}
		req := (*waiting)[0].Request
		*waiting = (*waiting)[1:]
		if line == "n" {
			return in.Deny(req)
		}
		return in.Approve(req, topic[:]) // the joiner gets the group's topic
	case "list":
		infos, err := in.List()
		if err != nil {
			return err
		}
		for _, i := range infos {
			log.Printf("invite %.8s: %s, %d of %d used", i.ID, i.State, i.Used, i.MaxUses)
		}
	case "revoke":
		infos, err := in.List()
		if err != nil {
			return err
		}
		for _, i := range infos {
			if i.State == invite.Active {
				if err := in.Revoke(i.ID); err != nil {
					return err
				}
			}
		}
	default:
		return errors.New("commands: invite, y, n, list, revoke")
	}
	return nil
}

type answer struct {
	topic koloswarm.Topic
	err   error
}

// ask sends a join request on the inviter's connection and returns the group topic the inviter answers with.
func ask(ctx context.Context, p *koloswarm.Peer, id *koloid.Identity, code invite.Code, name string) answer {
	ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) // a person has to answer
	defer cancel()
	payload, err := invite.JoinConn(ctx, p.Conn(), id, code, &invite.JoinOptions{Data: []byte(name), MaxPayload: 32})
	if err != nil {
		return answer{err: err}
	}
	if len(payload) != len(koloswarm.Topic{}) {
		return answer{err: errors.New("the answer is not a group topic")}
	}
	return answer{topic: koloswarm.Topic(payload)}
}

// feed sends what next returns on a channel, until next fails or ctx ends.
func feed[T any](ctx context.Context, next func(context.Context) (T, error)) <-chan T {
	c := make(chan T)
	go func() {
		for {
			v, err := next(ctx)
			if err != nil {
				return
			}
			select {
			case c <- v:
			case <-ctx.Done():
				return
			}
		}
	}()
	return c
}

// readTopic returns the group topic saved at path, or a zero topic if there is none yet.
func readTopic(path string) (koloswarm.Topic, error) {
	b, err := os.ReadFile(path)
	switch {
	case errors.Is(err, fs.ErrNotExist):
		return koloswarm.Topic{}, nil
	case err != nil:
		return koloswarm.Topic{}, err
	case len(b) != len(koloswarm.Topic{}):
		return koloswarm.Topic{}, errors.New("the group file is not a topic")
	}
	return koloswarm.Topic(b), nil
}

// loadIdentity reads the key at path, or makes one and saves it there with mode 0600.
func loadIdentity(path string) (*koloid.Identity, error) {
	id, err := koloid.Load(path)
	if !errors.Is(err, fs.ErrNotExist) {
		return id, err
	}
	if id, err = koloid.Generate(); err != nil {
		return nil, err
	}
	return id, id.SaveNew(path)
}

How it fits together:

  • One swarm and one event loop. feed turns the swarm's events, the inviter's events and the lines you type into channels, so a single select handles them all.
  • When a peer connects, the loop decides what it is. A peer that shares the group's topic is a member. A peer whose key matches the code in use is the inviter, and JoinConn asks it to let us in, in its own goroutine, since a person has to answer. Every other peer gets ServePeer, which answers invite requests on that connection.
  • Announce keeps the swarm joined to the topics of the live invites. It starts after the group's topic is joined, because it takes every free topic of the swarm for invites.
  • Every invite needs approval (Manual), is for one person and is valid for -ttl, 10 minutes by default. When Alice approves, the payload she sends is the group's topic.
  • The key is saved in the folder with mode 0600 and must stay the same, since a code carries a fingerprint of the inviter's key. The invites live in a Pebble store in the same folder, so they survive a restart.
  • What a joiner sends with -name comes from someone else, so the program prints it with %q.

4Start a bootstrap node in Terminal 1

The bootstrap node helps peers find each other. If kolo-node is not installed yet, install it as in Build a chat in your terminal. Then, in Terminal 1, start it on your computer only:

bash
kolo-node run -listen 127.0.0.1:7447 -identity "$(mktemp -d)/node.key" -first

-first starts a new network: this node has no other entry nodes to join. It prints three lines and keeps running. Your times and key will differ:

Text
time=2026-11-12T04:05:44.555+07:00 level=INFO msg=identity key=15f09167b8cdf405d2bdf6923fe75d5b63b0cd44fd410673afaa7006cda1a64b created=true
time=2026-11-12T04:05:44.555+07:00 level=INFO msg=started version=v0.1.0 addr=127.0.0.1:7447
time=2026-11-12T04:05:44.555+07:00 level=INFO msg=network mode=first entries=0

5Start the group as Alice in Terminal 2

In Terminal 2, make a temporary folder for Alice and start her:

bash
ALICE="$(mktemp -d)"
go run . -dir "$ALICE"

Alice makes a key and a new group:

Text
04:05:47 me f8c6cf7f
04:05:47 started a new group
04:05:47 in the group, type invite to make an invite code

6Make an invite and share the code

In Terminal 2, type invite and press Enter:

Text
04:05:48 invite 9c6c8a1b, valid until 04:15:48, for one person. Send them this code:
koloinv03p6txxqnbpccd4ujnmbtiynufzx7lvzzazwugnh3hd4h65yqqblm4xamynhjhejktktg5fdso5yl37avxcmq

Your code will differ. It holds a fingerprint of Alice's key and a secret, never an address. Whoever has the code can ask to join, so send it only to the person you invite, in a way you trust, such as a direct message. Approval, a single use and a short TTL limit what a leaked code can do.

7Join as Bob in Terminal 3

In Terminal 3, go to the same kolo-group folder (use the path where you created it):

Terminal
cd kolo-group

Then make a folder for Bob and run the program with Alice's code (paste your own):

bash
BOB="$(mktemp -d)"
go run . -dir "$BOB" -name Bob -join koloinv03p6txxqnbpccd4ujnmbtiynufzx7lvzzazwugnh3hd4h65yqqblm4xamynhjhejktktg5fdso5yl37avxcmq

Bob's swarm looks up the invite's topic, finds Alice there and connects to her. The code tells Bob which key is Alice's, so he sends his request to no one else:

Text
04:05:50 me a75d3d88
04:05:50 looking for the inviter of invite 9c6c8a1bef2f16ef57c1a6265543505c
04:05:50 asking f8c6cf7f to let us in

In Terminal 2, Alice sees the request:

Text
04:05:50 a75d3d88 asks to join as "Bob": type y to approve or n to deny

8Approve the request

In Terminal 2, type y and press Enter. Alice accepts Bob, and the single-use invite is used up:

Text
04:05:52 a75d3d88 joined as "Bob"
04:05:52 invite 9c6c8a1b ended: used up
04:05:52 peer a75d3d88 lost
04:05:53 member a75d3d88 connected

In Terminal 3, Bob gets the group's topic:

Text
04:05:52 joined the group, type invite to make an invite code
04:05:52 peer f8c6cf7f lost
04:05:53 member f8c6cf7f connected

Bob left the invite's topic, which closed that first connection (the two lost lines), and joined the group's topic, which brought a new connection between the two members. He saved the topic in his folder, so next time he runs without -join. Bob can now type invite too: any member can invite.

9Deny a request

In Terminal 2, type invite again:

Text
04:05:55 invite 8a07d6f7, valid until 04:15:55, for one person. Send them this code:
koloinv03p6txxqnbpccd4ujnmbtiynufywcsysfs73t527fbg4fmquauvgeth4zi72ed7ugu6u4qxnbdbjpfub3mwha

In a fourth terminal, go to the same kolo-group folder (use the path where you created it):

Terminal
cd kolo-group

Then make a folder for Carol and run the program with the new code (paste your own):

bash
CAROL="$(mktemp -d)"
go run . -dir "$CAROL" -name Carol -join koloinv03p6txxqnbpccd4ujnmbtiynufywcsysfs73t527fbg4fmquauvgeth4zi72ed7ugu6u4qxnbdbjpfub3mwha

When her request shows up in Terminal 2, type n:

Text
04:05:58 dc38e082 asks to join as "Carol": type y to approve or n to deny
04:05:59 peer dc38e082 lost

Carol's program prints the answer and stops:

Text
04:05:58 me dc38e082
04:05:58 looking for the inviter of invite 8a07d6f700c6f11dfafacc6b7a87bc85
04:05:58 asking f8c6cf7f to let us in
04:05:59 join: invite: denied
exit status 1

A deny is stored: Carol gets invite: denied every time she asks again with this code. The invite itself stays active for someone else.

10Revoke an invite

In Terminal 2, type invite once more, then revoke. It revokes every active invite, here the one Carol was denied with and the new one:

Text
04:06:00 invite 0c476029, valid until 04:16:00, for one person. Send them this code:
koloinv03p6txxqnbpccd4ujnmbtiynuf2wrnjlewrba3vgp7b6inmt3ch4rlzmyxlqeemk2ktbefauobihazl3ewpsa
04:06:02 invite 8a07d6f7 ended: revoked
04:06:02 invite 0c476029 ended: revoked

In the fourth terminal, run the program with a new folder and the new code (paste your own), this time as Dave:

bash
DAVE="$(mktemp -d)"
go run . -dir "$DAVE" -name Dave -join koloinv03p6txxqnbpccd4ujnmbtiynuf2wrnjlewrba3vgp7b6inmt3ch4rlzmyxlqeemk2ktbefauobihazl3ewpsa

Dave's program prints the answer and stops:

Text
04:06:03 me 5d08681f
04:06:03 looking for the inviter of invite 0c476029c0abd75d9a0e58a35478271c
04:06:03 asking f8c6cf7f to let us in
04:06:03 join: invite: revoked
exit status 1

An ended invite still answers like this for 5 minutes (Linger). Then its secret is erased and its topic left, so a late joiner finds no one to ask. Type list to see every invite Alice made:

Text
04:06:04 invite 9c6c8a1b: used up, 1 of 1 used
04:06:04 invite 8a07d6f7: revoked, 0 of 1 used
04:06:04 invite 0c476029: revoked, 0 of 1 used

Revoking stops new joins. It does not take anything back from Bob: a member who was accepted keeps the group's topic.

11Let an invite expire

Stop Alice with Ctrl-C in Terminal 2 and start her again with a short TTL:

bash
go run . -dir "$ALICE" -ttl 20s

Type list. Her key, her group and her invites are still there, and Bob connects again:

Text
04:06:06 me f8c6cf7f
04:06:06 in the group, type invite to make an invite code
04:06:06 member a75d3d88 connected
04:06:06 invite 9c6c8a1b: used up, 1 of 1 used
04:06:06 invite 8a07d6f7: revoked, 0 of 1 used
04:06:06 invite 0c476029: revoked, 0 of 1 used

Type invite and wait 20 seconds:

Text
04:06:07 invite 45d79304, valid until 04:06:27, for one person. Send them this code:
koloinv03p6txxqnbpccd4ujnmbtiynufycnolkk3r4rcks77irkwg432f3h3hm6gbx4yuhg6vpzblq7ftuezdydsk4q
04:06:27 invite 45d79304 ended: expired

In the fourth terminal, run the program with a new folder and that code (paste your own), this time as Erin:

bash
ERIN="$(mktemp -d)"
go run . -dir "$ERIN" -name Erin -join koloinv03p6txxqnbpccd4ujnmbtiynufycnolkk3r4rcks77irkwg432f3h3hm6gbx4yuhg6vpzblq7ftuezdydsk4q

Erin's program prints the answer and stops:

Text
04:06:29 me 91b38570
04:06:29 looking for the inviter of invite 45d793045f175bcbf070eee6a4912b37
04:06:29 asking f8c6cf7f to let us in
04:06:29 join: invite: expired
exit status 1

Expiry counts only on Alice's clock. The joiner sends no time, so there is no skew between the two, and once Alice has seen the end, setting her clock back does not reopen the invite.

12Come back later

Stop Bob with Ctrl-C in Terminal 3 and run him again with only his folder:

bash
go run . -dir "$BOB"

He goes back to the group:

Text
04:06:30 me a75d3d88
04:06:30 in the group, type invite to make an invite code
04:06:30 member f8c6cf7f connected

To finish, press Ctrl-C in Terminal 3, Terminal 2 and then Terminal 1.

What just happened

  • The code carried a fingerprint of Alice's key and a 256-bit secret. Bob found Alice on a topic derived from the secret, checked her key against the fingerprint, and sent a request encrypted to a key derived from the secret and signed with his own key.
  • Alice decided alone, with her own clock and her own store. A use is counted on disk before the answer goes out, so a single-use invite never lets two people in.
  • The bootstrap node and the DHT saw the invite's topic, never the code. They could see that Bob's address looked up a topic that Alice's key announced. See Topics.
  • The group's topic is how members find each other, not a secret: DHT servers see it too. A real application sends what grants access in the payload, for example a log ID and a capability, and checks each member's key. Joiners lists the keys an invite accepted, with what each one sent.

Before you build on it

  • A joiner's swarm looks the invite's topic up when it starts, then every 10 minutes (kolo-swarm's LookupInterval) plus up to a fifth of that at random. A joiner that starts before the inviter is online can wait up to about 12 minutes.
  • A swarm joins 16 topics at once by default (MaxTopics), the group's and the invites' together. Invites past that wait for a free topic, so give invites a TTL and revoke the ones you no longer need.
  • ServePeer must be the only one accepting streams on its connection. This program runs nothing else with members. An application that runs another protocol with them decides per connection which one serves it, for example by topic, as here.
  • JoinConn also works on a connection the joiner already has with the inviter, which skips the DHT lookup.
  • The kolo-invite page lists every limit, the security notes and the errors.

What was not tested

Every run behind this guide was on one computer, on 127.0.0.1. Real NAT and the Windows commands were not tested.

Next steps