Implement end-to-end encrypted buyer/seller messaging

Wire format (internal/message): sealed boxes to the listing's device key
(X25519 + HKDF + ChaCha20-Poly1305), padded, proof-of-work stamped, with
signed owner replies and address grants. Relay validation, bounded queues,
gossip on per-region message topics and sync (store, p2p).

Owner side (internal/inbox, API): inbox with hidden link messages and a
per-day new-thread limit, replies, grants, and a private per-listing
address. Public POST/GET /api/v1/messages for buyers.

Browser: noble-based sealing and reply verification checked against a Go
fixture, contact form, conversation view, message list, de/en strings.

Docs: PROTOCOL.md messaging section matches the implementation.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 19:44:59 +01:00
co-authored by Claude Sonnet 5.5
parent b9e1b0c058
commit 3b0351c774
45 changed files with 8228 additions and 292 deletions
+152
View File
@@ -0,0 +1,152 @@
package p2p
import (
"context"
"errors"
"testing"
"time"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const msgRegion = "u1x"
func hello(t *testing.T, text string) *message.Plain {
t.Helper()
return &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: text}
}
func TestMessagesTravelBetweenBuyerGatewayAndOwner(t *testing.T) {
owner := startNode(t, nil, msgRegion)
gateway := startNode(t, nil, msgRegion)
connect(t, gateway, owner)
l := owner.listing(t, "u1xjhx")
if err := owner.Publish(context.Background(), l); err != nil {
t.Fatal(err)
}
eventually(t, "gateway learns the listing", func() bool {
_, err := gateway.s.Get(context.Background(), l.Author, l.ID)
return err == nil
})
// The buyer's browser sends through the gateway.
tk, err := message.NewThreadKey()
if err != nil {
t.Fatal(err)
}
env, err := message.SealToOwner(l, tk, hello(t, "Ist die Wohnung noch frei?"), time.Now(), msgDifficulty)
if err != nil {
t.Fatal(err)
}
if err := gateway.PublishMessage(context.Background(), msgRegion, env); err != nil {
t.Fatal(err)
}
var got []*message.Envelope
eventually(t, "owner receives the message", func() bool {
got, _ = owner.s.OwnerMessages(context.Background(), l.Author)
return len(got) == 1
})
plain, err := got[0].OpenAsOwner(owner.dev)
if err != nil || plain.Text != "Ist die Wohnung noch frei?" {
t.Fatalf("owner could not read it: %v %+v", err, plain)
}
// The owner answers; the reply waits in the gateway's mailbox.
reply := &message.Plain{Type: message.TypeText, Thread: plain.Thread, N: 1, SentAt: time.Now().Unix(), Text: "Ja!"}
renv, err := message.SealToBuyer(owner.dev, message.Ref{Author: l.Author, ID: l.ID}, reply, time.Now(), msgDifficulty)
if err != nil {
t.Fatal(err)
}
if err := owner.PublishMessage(context.Background(), msgRegion, renv); err != nil {
t.Fatal(err)
}
mailbox, _ := tk.Mailbox()
var box []*message.Envelope
eventually(t, "reply reaches the gateway's mailbox", func() bool {
box, _ = gateway.s.Mailbox(context.Background(), mailbox, 0, 10)
return len(box) == 1
})
back, err := box[0].OpenAsBuyer(tk)
if err != nil || back.Text != "Ja!" {
t.Fatalf("buyer could not read the reply: %v %+v", err, back)
}
}
func TestLateJoinersSyncMessagesAfterListings(t *testing.T) {
owner := startNode(t, nil, msgRegion)
l := owner.listing(t, "u1xjhx")
if err := owner.Publish(context.Background(), l); err != nil {
t.Fatal(err)
}
tk, _ := message.NewThreadKey()
env, err := message.SealToOwner(l, tk, hello(t, "hallo"), time.Now(), msgDifficulty)
if err != nil {
t.Fatal(err)
}
if err := owner.PublishMessage(context.Background(), msgRegion, env); err != nil {
t.Fatal(err)
}
reply := &message.Plain{Type: message.TypeText, Thread: tk.PublicHex(), N: 1, SentAt: time.Now().Unix(), Text: "ok"}
renv, _ := message.SealToBuyer(owner.dev, message.Ref{Author: l.Author, ID: l.ID}, reply, time.Now(), msgDifficulty)
if err := owner.PublishMessage(context.Background(), msgRegion, renv); err != nil {
t.Fatal(err)
}
// Joins later, and in another region as well, which must stay empty.
late := startNode(t, nil, msgRegion)
other := startNode(t, nil, "u1y")
connect(t, late, owner)
connect(t, other, owner)
eventually(t, "late joiner has the owner-bound message", func() bool {
got, _ := late.s.OwnerMessages(context.Background(), l.Author)
return len(got) == 1
})
mailbox, _ := tk.Mailbox()
eventually(t, "late joiner has the reply", func() bool {
box, _ := late.s.Mailbox(context.Background(), mailbox, 0, 10)
return len(box) == 1
})
if n, _ := other.s.MessageCount(context.Background()); n != 0 {
t.Fatalf("a node in another region holds %d envelopes", n)
}
}
func TestInvalidMessagesAreNotAccepted(t *testing.T) {
a := startNode(t, nil, msgRegion)
l := a.listing(t, "u1xjhx")
if err := a.Publish(context.Background(), l); err != nil {
t.Fatal(err)
}
tk, _ := message.NewThreadKey()
// No proof-of-work at this node's difficulty.
var weak *message.Envelope
for {
e, err := message.SealToOwner(l, tk, hello(t, "x"), time.Now(), 0)
if err != nil {
t.Fatal(err)
}
if w, _ := e.Work(); w < msgDifficulty {
weak = e
break
}
}
if err := a.PublishMessage(context.Background(), msgRegion, weak); !errors.Is(err, store.ErrInvalid) {
t.Fatalf("weak message: %v, want ErrInvalid", err)
}
// A listing this node does not hold.
b := startNode(t, nil, msgRegion)
foreign := b.listing(t, "u1xjhx")
env, _ := message.SealToOwner(foreign, tk, hello(t, "x"), time.Now(), msgDifficulty)
if err := a.PublishMessage(context.Background(), msgRegion, env); !errors.Is(err, store.ErrNoListing) {
t.Fatalf("unknown listing: %v, want ErrNoListing", err)
}
if n, _ := a.s.MessageCount(context.Background()); n != 0 {
t.Fatalf("rejected messages were stored (%d)", n)
}
}
+112 -5
View File
@@ -30,11 +30,15 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
listingTopicPrefix = "/allmende/1/listings/"
// messageTopicPrefix carries encrypted message envelopes, one topic per
// region next to the listing topic.
messageTopicPrefix = "/allmende/1/messages/"
// RevocationTopic carries identity revocations for the whole network.
RevocationTopic = "/allmende/1/revocations"
@@ -52,11 +56,14 @@ type Config struct {
Regions []string // geohash precision-3 cells to replicate
MDNS bool // discover peers on the local network
Difficulty int // required proof-of-work bits
SyncPageSize int // records per sync page (default 500)
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
Clock func() time.Time // default time.Now
Logger *slog.Logger
Difficulty int // required proof-of-work bits
// MessageDifficulty is the proof-of-work bits required of message
// envelopes; it must match the store's.
MessageDifficulty int
SyncPageSize int // records per sync page (default 500)
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
Clock func() time.Time // default time.Now
Logger *slog.Logger
}
// Node is a running participant.
@@ -74,6 +81,7 @@ type Node struct {
mu sync.Mutex
topics map[string]*pubsub.Topic
msgTopics map[string]*pubsub.Topic
subscribed []string
bootstrap []peer.AddrInfo
syncing map[peer.ID]bool
@@ -126,6 +134,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
ctx: nctx,
cancel: cancel,
topics: map[string]*pubsub.Topic{},
msgTopics: map[string]*pubsub.Topic{},
syncing: map[peer.ID]bool{},
bootstrap: bootstrap,
}
@@ -226,6 +235,24 @@ func (n *Node) Publish(ctx context.Context, l *listing.Listing) error {
return t.Publish(ctx, data)
}
// PublishMessage stores an envelope locally (which verifies it) and gossips it
// on the message topic of region. The node must replicate the region: owner-
// bound envelopes are only accepted for listings it holds.
func (n *Node) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
if _, err := n.cfg.Store.PutMessage(ctx, region, e); err != nil {
return err
}
data, err := e.Bytes()
if err != nil {
return err
}
t, err := n.messageTopic(region)
if err != nil {
return err
}
return t.Publish(ctx, data)
}
// PublishRevocation stores r locally and gossips it to the whole network.
func (n *Node) PublishRevocation(ctx context.Context, r *identity.Revocation) error {
if _, err := n.cfg.Store.PutRevocation(ctx, r); err != nil {
@@ -307,9 +334,56 @@ func (n *Node) subscribeRegion(region string) error {
}
})
}()
mt, err := n.messageTopic(region)
if err != nil {
return err
}
msub, err := mt.Subscribe()
if err != nil {
return err
}
n.wg.Add(1)
go func() {
defer n.wg.Done()
n.consume(msub, func(msg *pubsub.Message) {
e, ok := msg.ValidatorData.(*message.Envelope)
if !ok {
return
}
switch _, err := n.cfg.Store.PutMessage(n.ctx, region, e); {
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
default:
n.log.Warn("store message", "err", err)
}
})
}()
return nil
}
// messageTopic joins (once) the message topic for region.
func (n *Node) messageTopic(region string) (*pubsub.Topic, error) {
if !listing.ValidRegion(region) {
return nil, fmt.Errorf("p2p: invalid region %q", region)
}
n.mu.Lock()
defer n.mu.Unlock()
if t, ok := n.msgTopics[region]; ok {
return t, nil
}
name := messageTopicPrefix + region
if err := n.ps.RegisterTopicValidator(name, n.messageValidator(region),
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
return nil, err
}
t, err := n.ps.Join(name)
if err != nil {
return nil, err
}
n.msgTopics[region] = t
return t, nil
}
// regionTopic joins (once) the topic for region and installs its validator.
func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
if !listing.ValidRegion(region) {
@@ -360,6 +434,39 @@ func (n *Node) listingValidator(region string) pubsub.ValidatorEx {
}
}
// messageValidator checks what a relay can see: the envelope's structure,
// size and proof-of-work, and the listing it points to. It cannot read the
// content. Invalid envelopes cost the relaying peer score; ones this node
// cannot place (unknown listing, a device that changed) or whose clocks
// disagree are ignored without penalty.
func (n *Node) messageValidator(region string) pubsub.ValidatorEx {
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
if len(msg.Data) > message.MaxSize {
return pubsub.ValidationReject
}
var e message.Envelope
if err := json.Unmarshal(msg.Data, &e); err != nil {
return pubsub.ValidationReject
}
// Only the canonical encoding, so every node derives the same ID.
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, msg.Data) {
return pubsub.ValidationReject
}
err := n.cfg.Store.CheckMessage(ctx, region, &e)
switch {
case err == nil:
msg.ValidatorData = &e
return pubsub.ValidationAccept
case errors.Is(err, listing.ErrTimeWindow), errors.Is(err, store.ErrNoListing):
return pubsub.ValidationIgnore
case errors.Is(err, store.ErrInvalid):
return pubsub.ValidationReject
default:
return pubsub.ValidationIgnore // a local failure is not the peer's fault
}
}
}
func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listing, pubsub.ValidationResult) {
if len(data) > listing.MaxSize {
return nil, pubsub.ValidationReject
+14 -10
View File
@@ -18,7 +18,10 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const difficulty = 6
const (
difficulty = 6
msgDifficulty = 4
)
// testLogger is silent unless P2P_DEBUG is set.
func testLogger() *slog.Logger {
@@ -49,19 +52,20 @@ func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), r
if err != nil {
t.Fatal(err)
}
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
if err != nil {
t.Fatal(err)
}
cfg := Config{
Device: dev,
Store: s,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Regions: regions,
Difficulty: difficulty,
SyncPageSize: 3,
RedialInterval: 200 * time.Millisecond,
Logger: testLogger(),
Device: dev,
Store: s,
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
Regions: regions,
Difficulty: difficulty,
MessageDifficulty: msgDifficulty,
SyncPageSize: 3,
RedialInterval: 200 * time.Millisecond,
Logger: testLogger(),
}
if tweak != nil {
tweak(&cfg)
+68 -3
View File
@@ -4,6 +4,7 @@ import (
"bufio"
"context"
"encoding/json"
"errors"
"io"
"time"
@@ -12,6 +13,7 @@ import (
"git.stinnesbeck.com/nils/allmende/internal/identity"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
@@ -30,11 +32,12 @@ const (
)
type syncRequest struct {
Kind string `json:"kind"` // "listings" or "revocations"
Kind string `json:"kind"` // "listings", "messages" or "revocations"
Region string `json:"region,omitempty"`
AfterCreated int64 `json:"after_created,omitempty"`
AfterAuthor string `json:"after_author,omitempty"`
AfterID string `json:"after_id,omitempty"`
AfterAuthor string `json:"after_author,omitempty"` // listings
AfterID string `json:"after_id,omitempty"` // listings
AfterHash string `json:"after_hash,omitempty"` // messages
Limit int `json:"limit,omitempty"`
}
@@ -81,6 +84,27 @@ func (n *Node) handleSync(s network.Stream) {
return
}
}
case "messages":
if !listing.ValidRegion(req.Region) {
_ = s.Reset()
return
}
limit := req.Limit
if limit <= 0 || limit > n.cfg.SyncPageSize {
limit = n.cfg.SyncPageSize
}
items, err := n.cfg.Store.MessagesSince(n.ctx, req.Region,
store.MessageCursor{CreatedAt: req.AfterCreated, Hash: req.AfterHash}, limit)
if err != nil {
_ = s.Reset()
return
}
for _, e := range items {
if !write(e.Bytes()) {
_ = s.Reset()
return
}
}
case "revocations":
revs, err := n.cfg.Store.Revocations(n.ctx)
if err != nil {
@@ -147,6 +171,47 @@ func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
if err := n.syncRegion(ctx, p, region); err != nil {
return err
}
// After the listings: owner-bound messages are only accepted for
// listings we already hold.
if err := n.syncMessages(ctx, p, region); err != nil {
return err
}
}
return nil
}
func (n *Node) syncMessages(ctx context.Context, p peer.ID, region string) error {
var cur store.MessageCursor
for page := 0; page < maxSyncPages; page++ {
var count int
var last *message.Envelope
err := n.request(ctx, p, syncRequest{
Kind: "messages", Region: region, Limit: n.cfg.SyncPageSize,
AfterCreated: cur.CreatedAt, AfterHash: cur.Hash,
}, func(line []byte) {
var e message.Envelope
if json.Unmarshal(line, &e) != nil {
return
}
count++
last = &e
switch _, err := n.cfg.Store.PutMessage(ctx, region, &e); {
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
default:
n.log.Debug("sync: message rejected", "peer", p, "err", err)
}
})
if err != nil {
return err
}
if count < n.cfg.SyncPageSize || last == nil {
return nil
}
c, err := store.MessageCursorOf(last)
if err != nil {
return err
}
cur = c
}
return nil
}