Files
allmende/internal/identity/device.go
T
nilsandClaude Sonnet 5.5 d3efe5a3a7 Add device keys, revocation and libp2p gossip with sync
- identity: 12-word recovery phrase, device certificates, revocations,
  device key storage; the identity key is never stored on a node
- listing: signed by a device with an embedded certificate, domain-separated
  signatures, ErrTimeWindow for clock-related failures, region helpers
- store: revocations purge a device's listings; keyset-paged Since for sync
- p2p: gossipsub topic per geohash region plus a global revocation topic,
  validators run before relaying, /allmende/1/sync catch-up protocol,
  bootstrap peers and mDNS
- docs: key model, replication and conflict rules

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 17:43:25 +01:00

86 lines
2.1 KiB
Go

package identity
import (
"crypto/ed25519"
"encoding/json"
"errors"
"os"
"path/filepath"
"time"
)
// Device is what a running node holds: its own key plus the certificate that
// ties it to an identity. The identity key itself is never stored.
type Device struct {
Key *Identity
Cert *Cert
}
// Enroll creates a new device key and certifies it with the identity key.
func Enroll(root *Identity, now time.Time, validFor time.Duration) (*Device, error) {
key, err := Generate()
if err != nil {
return nil, err
}
cert, err := IssueCert(root, key.PublicKeyHex(), now, now.Add(validFor))
if err != nil {
return nil, err
}
return &Device{Key: key, Cert: cert}, nil
}
const (
deviceKeyFile = "device.key"
deviceCertFile = "device.cert"
)
// Save writes the device key (refusing to overwrite) and certificate into dir.
func (d *Device) Save(dir string) error {
if err := d.Key.Save(filepath.Join(dir, deviceKeyFile)); err != nil {
return err
}
return d.SaveCert(dir)
}
// SaveCert (over)writes only the certificate, e.g. after renewal.
func (d *Device) SaveCert(dir string) error {
data, err := json.Marshal(d.Cert)
if err != nil {
return err
}
path := filepath.Join(dir, deviceCertFile)
tmp := path + ".tmp"
if err := os.WriteFile(tmp, data, 0o644); err != nil {
return err
}
return os.Rename(tmp, path)
}
// LoadDevice reads a device saved by Save and checks that key and
// certificate belong together.
func LoadDevice(dir string) (*Device, error) {
key, err := Load(filepath.Join(dir, deviceKeyFile))
if err != nil {
return nil, err
}
data, err := os.ReadFile(filepath.Join(dir, deviceCertFile))
if err != nil {
return nil, err
}
var cert Cert
if err := json.Unmarshal(data, &cert); err != nil {
return nil, err
}
if err := cert.Check(); err != nil {
return nil, err
}
if cert.Device != key.PublicKeyHex() {
return nil, errors.New("identity: certificate does not match device key")
}
return &Device{Key: key, Cert: &cert}, nil
}
// PrivateKey exposes the raw key so the p2p layer can use it as the node's
// libp2p identity. Handle with care.
func (i *Identity) PrivateKey() ed25519.PrivateKey { return i.priv }