Add runnable node, HTTP API, all-devices revocation and reconnect sync
- cmd/node: init (recovery phrase onboarding), run, recover - api: public reads of canonical signed records, token-protected writes - identity: RevokeAll voids every device certified before a cutoff, so recovery works with only the phrase; store purges by certificate age - p2p: redial bootstrap peers, sync on every new connection (in-flight guard only), validate bootstrap addresses up front - docs: API, recovery semantics, peer-ID change on recovery Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
)
|
||||
|
||||
func cmdInit(args []string) error {
|
||||
fs := flag.NewFlagSet("init", flag.ExitOnError)
|
||||
data := dataFlag(fs)
|
||||
fs.Parse(args)
|
||||
|
||||
if _, err := os.Stat(filepath.Join(*data, "device.key")); err == nil {
|
||||
return fmt.Errorf("%s is already set up. To get access back after losing this machine, use 'node recover'", *data)
|
||||
}
|
||||
|
||||
root, phrase, err := identity.NewRoot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
words := strings.Fields(phrase)
|
||||
showPhrase(words)
|
||||
|
||||
// Only ask for confirmation when a person is at the keyboard.
|
||||
if term.IsTerminal(int(os.Stdin.Fd())) {
|
||||
if err := confirmPhrase(bufio.NewReader(os.Stdin), words); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
dev, err := identity.Enroll(root, time.Now(), certLifetime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// The identity key is not saved anywhere: only the phrase can recreate it.
|
||||
if err := dev.Save(*data); err != nil {
|
||||
return err
|
||||
}
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeToken(*data, token); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Printf("\nDone. This machine is set up as a device of identity %s…\n", dev.Cert.Author[:12])
|
||||
fmt.Printf("Your device certificate is valid until %s.\n\n", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
|
||||
fmt.Printf("Next: node run --region <region> --data %s\n", *data)
|
||||
fmt.Printf("The admin token for publishing is in %s\n", filepath.Join(*data, tokenFile))
|
||||
return nil
|
||||
}
|
||||
|
||||
func showPhrase(words []string) {
|
||||
fmt.Print(`
|
||||
Your recovery phrase
|
||||
--------------------
|
||||
These 12 words ARE your identity. They are shown only once and are not stored
|
||||
on this computer. Write them on paper and keep them somewhere safe.
|
||||
|
||||
With them you can recover your account if this computer is lost, broken or
|
||||
hacked. Anyone who has them can act as you, so never type them into a website
|
||||
or share them.
|
||||
`)
|
||||
for i := 0; i < len(words); i += 3 {
|
||||
fmt.Printf(" %2d. %-12s %2d. %-12s %2d. %-12s\n",
|
||||
i+1, words[i], i+2, words[i+1], i+3, words[i+2])
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
// confirmPhrase asks for two random words so the user has really written
|
||||
// the phrase down.
|
||||
func confirmPhrase(in *bufio.Reader, words []string) error {
|
||||
picks, err := twoDistinct(len(words))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("To make sure you wrote it down, please enter two of the words.")
|
||||
for _, i := range picks {
|
||||
for {
|
||||
fmt.Printf("Word number %d: ", i+1)
|
||||
line, err := in.ReadString('\n')
|
||||
if err != nil && (!errors.Is(err, io.EOF) || line == "") {
|
||||
return errors.New("no input; run 'node init' again in a terminal")
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(line), words[i]) {
|
||||
break
|
||||
}
|
||||
fmt.Println("That is not the right word. Check your notes and try again.")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func twoDistinct(n int) ([2]int, error) {
|
||||
a, err := rand.Int(rand.Reader, big.NewInt(int64(n)))
|
||||
if err != nil {
|
||||
return [2]int{}, err
|
||||
}
|
||||
b, err := rand.Int(rand.Reader, big.NewInt(int64(n-1)))
|
||||
if err != nil {
|
||||
return [2]int{}, err
|
||||
}
|
||||
x, y := int(a.Int64()), int(b.Int64())
|
||||
if y >= x {
|
||||
y++
|
||||
}
|
||||
if x > y {
|
||||
x, y = y, x
|
||||
}
|
||||
return [2]int{x, y}, nil
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// Command node runs an Allmende node.
|
||||
//
|
||||
// node init first-time setup: creates your identity and shows your recovery phrase
|
||||
// node run run the node (replicates listings, serves the HTTP API)
|
||||
// node recover restore from the recovery phrase after a lost or compromised machine
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
certLifetime = 365 * 24 * time.Hour
|
||||
|
||||
dbFile = "allmende.db"
|
||||
tokenFile = "admin.token"
|
||||
)
|
||||
|
||||
const usage = `Allmende: a free, distributed marketplace for homes.
|
||||
|
||||
Usage:
|
||||
node init [--data DIR] create your identity (first run)
|
||||
node run [--data DIR] --region u1x run the node
|
||||
node recover [--data DIR] restore access using your recovery phrase
|
||||
|
||||
Run "node <command> -h" for the options of a command.
|
||||
`
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
fmt.Fprint(os.Stderr, usage)
|
||||
os.Exit(2)
|
||||
}
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "init":
|
||||
err = cmdInit(os.Args[2:])
|
||||
case "run":
|
||||
err = cmdRun(os.Args[2:])
|
||||
case "recover":
|
||||
err = cmdRecover(os.Args[2:])
|
||||
case "help", "-h", "--help":
|
||||
fmt.Print(usage)
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "unknown command %q\n\n%s", os.Args[1], usage)
|
||||
os.Exit(2)
|
||||
}
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "error:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// --- shared helpers -------------------------------------------------------
|
||||
|
||||
func defaultDataDir() string {
|
||||
if d := os.Getenv("ALLMENDE_DATA"); d != "" {
|
||||
return d
|
||||
}
|
||||
if x := os.Getenv("XDG_DATA_HOME"); x != "" {
|
||||
return filepath.Join(x, "allmende")
|
||||
}
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "allmende-data"
|
||||
}
|
||||
return filepath.Join(home, ".local", "share", "allmende")
|
||||
}
|
||||
|
||||
func dataFlag(fs *flag.FlagSet) *string {
|
||||
return fs.String("data", defaultDataDir(), "directory for keys and the database (env ALLMENDE_DATA)")
|
||||
}
|
||||
|
||||
// listFlag is a repeatable, comma-separated string flag.
|
||||
type listFlag []string
|
||||
|
||||
func (l *listFlag) String() string { return strings.Join(*l, ",") }
|
||||
func (l *listFlag) Set(v string) error {
|
||||
for _, p := range strings.Split(v, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
*l = append(*l, p)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
// writeToken replaces the admin token file, readable only by the owner.
|
||||
func writeToken(dir, token string) error {
|
||||
path := filepath.Join(dir, tokenFile)
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, []byte(token+"\n"), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
func readToken(dir string) string {
|
||||
b, err := os.ReadFile(filepath.Join(dir, tokenFile))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
// cmdRecover restores access from the recovery phrase. It voids every device
|
||||
// certified so far (including a stolen one), enrolls this machine as a fresh
|
||||
// device, and re-signs this node's own listings so they carry on. It also
|
||||
// serves as the yearly certificate renewal.
|
||||
func cmdRecover(args []string) error {
|
||||
fs := flag.NewFlagSet("recover", flag.ExitOnError)
|
||||
data := dataFlag(fs)
|
||||
difficulty := fs.Int("difficulty", listing.DefaultDifficulty, "proof-of-work bits; must match the network")
|
||||
fs.Parse(args)
|
||||
|
||||
phrase, err := readPhrase()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
root, err := identity.FromPhrase(phrase)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
author := root.PublicKeyHex()
|
||||
ctx := context.Background()
|
||||
|
||||
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
// Remember our listings: the revocation below purges them from the store.
|
||||
own, err := st.ByAuthor(ctx, author)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
rev, err := identity.RevokeAll(root, now, *difficulty)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Enrolled at the same instant: a certificate issued at the cutoff stays valid.
|
||||
dev, err := identity.Enroll(root, now, certLifetime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := retireOldDevice(*data, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dev.Save(*data); err != nil {
|
||||
return err
|
||||
}
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeToken(*data, token); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := st.PutRevocation(ctx, rev); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
republished := 0
|
||||
for _, old := range own {
|
||||
l := *old
|
||||
l.Seq = old.Seq + 1
|
||||
l.CreatedAt = now.Unix()
|
||||
if max := now.Add(listing.MaxLifetime).Unix(); l.ExpiresAt > max {
|
||||
l.ExpiresAt = max
|
||||
}
|
||||
if err := l.Seal(dev, *difficulty); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := st.Put(ctx, &l); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "warning: could not re-sign listing %s: %v\n", old.ID, err)
|
||||
continue
|
||||
}
|
||||
republished++
|
||||
}
|
||||
|
||||
fmt.Printf("Recovered identity %s…\n", author[:12])
|
||||
fmt.Println(" - All earlier devices of this identity have been revoked.")
|
||||
fmt.Printf(" - This machine is now a new device (certificate valid until %s).\n",
|
||||
time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
|
||||
fmt.Printf(" - %d of your listings were re-signed from this device.\n", republished)
|
||||
fmt.Println(" - A new admin token was written; the old one no longer works.")
|
||||
fmt.Println("\nStart the node with 'node run' so the revocation spreads through the network.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// retireOldDevice moves a previous device's files aside so the revoked key is
|
||||
// never used again but is not silently destroyed either.
|
||||
func retireOldDevice(dir string, now time.Time) error {
|
||||
for _, name := range []string{"device.key", "device.cert"} {
|
||||
src := filepath.Join(dir, name)
|
||||
if _, err := os.Stat(src); errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
dst := fmt.Sprintf("%s.revoked-%d", src, now.Unix())
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readPhrase reads the recovery phrase without echoing it when possible.
|
||||
func readPhrase() (string, error) {
|
||||
fd := int(os.Stdin.Fd())
|
||||
if term.IsTerminal(fd) {
|
||||
fmt.Fprint(os.Stderr, "Recovery phrase (12 words; what you type is hidden): ")
|
||||
b, err := term.ReadPassword(fd)
|
||||
fmt.Fprintln(os.Stderr)
|
||||
return string(b), err
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(os.Stdin, 4096))
|
||||
return string(b), err
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/api"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
announceFirst = 10 * time.Second
|
||||
announceInterval = 30 * time.Minute
|
||||
certWarnBefore = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
func cmdRun(args []string) error {
|
||||
fs := flag.NewFlagSet("run", flag.ExitOnError)
|
||||
data := dataFlag(fs)
|
||||
var regions, bootstrap, listen listFlag
|
||||
fs.Var(®ions, "region", "geohash region (3 characters, e.g. u1x) to replicate; repeatable")
|
||||
fs.Var(&bootstrap, "bootstrap", "multiaddr of a known peer (…/p2p/<id>); repeatable")
|
||||
fs.Var(&listen, "listen", "libp2p listen multiaddr; repeatable (default: all interfaces, random ports)")
|
||||
httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API")
|
||||
noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network")
|
||||
difficulty := fs.Int("difficulty", listing.DefaultDifficulty,
|
||||
"proof-of-work bits; must match the rest of the network")
|
||||
fs.Parse(args)
|
||||
|
||||
if len(regions) == 0 {
|
||||
return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)")
|
||||
}
|
||||
|
||||
dev, err := identity.LoadDevice(*data)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return fmt.Errorf("%s is not set up yet: run 'node init' first", *data)
|
||||
}
|
||||
return err
|
||||
}
|
||||
until := time.Until(time.Unix(dev.Cert.ExpiresAt, 0))
|
||||
if until <= 0 {
|
||||
return errors.New("this device's certificate has expired; run 'node recover' to renew it")
|
||||
}
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
if until < certWarnBefore {
|
||||
log.Warn("device certificate expires soon; run 'node recover' to renew it",
|
||||
"expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
|
||||
}
|
||||
|
||||
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
node, err := p2p.New(ctx, p2p.Config{
|
||||
Device: dev,
|
||||
Store: st,
|
||||
ListenAddrs: listen,
|
||||
Bootstrap: bootstrap,
|
||||
Regions: regions,
|
||||
MDNS: !*noMDNS,
|
||||
Difficulty: *difficulty,
|
||||
Logger: log,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer node.Close()
|
||||
|
||||
token := readToken(*data)
|
||||
if token == "" {
|
||||
log.Warn("no admin token found; publishing through the API is disabled")
|
||||
}
|
||||
handler := api.New(api.Config{
|
||||
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
|
||||
})
|
||||
|
||||
ln, err := net.Listen("tcp", *httpAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 60 * time.Second, // publishing mines proof-of-work
|
||||
IdleTimeout: 2 * time.Minute,
|
||||
}
|
||||
go func() {
|
||||
if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Error("http server", "err", err)
|
||||
stop()
|
||||
}
|
||||
}()
|
||||
|
||||
log.Info("node running",
|
||||
"peer_id", node.ID().String(), "identity", dev.Cert.Author[:12]+"…",
|
||||
"regions", []string(regions), "http", ln.Addr().String())
|
||||
for _, a := range node.Addrs() {
|
||||
log.Info("listening", "addr", a)
|
||||
}
|
||||
if host, _, _ := net.SplitHostPort(ln.Addr().String()); host != "127.0.0.1" && host != "::1" {
|
||||
log.Warn("the HTTP API is reachable from other machines; put it behind TLS if it is public")
|
||||
}
|
||||
|
||||
go announce(ctx, log, node, st, dev.Cert.Author)
|
||||
|
||||
<-ctx.Done()
|
||||
log.Info("shutting down")
|
||||
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
return srv.Shutdown(shutdown)
|
||||
}
|
||||
|
||||
// announce periodically re-gossips this identity's revocations and live
|
||||
// listings. Gossip only reaches peers connected at that moment; this makes
|
||||
// sure newcomers hear about them without waiting for a sync.
|
||||
func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.Store, author string) {
|
||||
timer := time.NewTimer(announceFirst)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
if revs, err := st.Revocations(ctx); err == nil {
|
||||
for _, r := range revs {
|
||||
if r.Author == author {
|
||||
if err := node.PublishRevocation(ctx, r); err != nil {
|
||||
log.Debug("announce revocation", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if own, err := st.ByAuthor(ctx, author); err == nil {
|
||||
for _, l := range own {
|
||||
if err := node.Publish(ctx, l); err != nil {
|
||||
log.Debug("announce listing", "id", l.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
timer.Reset(announceInterval)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user