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