Files
allmende/internal/api/messages.go
T
nilsandClaude Sonnet 5.5 3b0351c774 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>
2026-11-17 19:44:59 +01:00

421 lines
12 KiB
Go

package api
import (
"bytes"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"git.stinnesbeck.com/nils/allmende/internal/inbox"
"git.stinnesbeck.com/nils/allmende/internal/listing"
"git.stinnesbeck.com/nils/allmende/internal/message"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
const (
defaultPostsPerMinute = 30
maxMailboxPage = 100
)
// --- public relay endpoints -------------------------------------------------
//
// A browser-only buyer talks to the network through these: it posts an
// encrypted envelope and polls its mailbox. The node sees only ciphertext.
func (s *server) postMessage(w http.ResponseWriter, r *http.Request) {
if !s.limiter.allow(clientIP(r)) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many messages from this address; try again in a minute")
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, message.MaxSize+1))
if err != nil {
fail(w, http.StatusRequestEntityTooLarge, "message too large")
return
}
var e message.Envelope
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&e); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON body")
return
}
// Only the canonical encoding travels, so everyone derives the same hash.
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, body) {
fail(w, http.StatusBadRequest, "the envelope must be in canonical JSON form")
return
}
region, err := s.Store.Region(r.Context(), e.Listing.Author, e.Listing.ID)
if errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "this node does not know that listing")
return
}
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if err := s.Node.PublishMessage(r.Context(), region, &e); err != nil {
switch {
case errors.Is(err, store.ErrInvalid):
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), store.ErrInvalid.Error()+": "))
case errors.Is(err, store.ErrNoListing):
fail(w, http.StatusNotFound, "that listing is not live here (anymore), or its owner changed device")
case errors.Is(err, store.ErrQueueFull):
fail(w, http.StatusTooManyRequests, "the queue for this listing is full of messages with more proof-of-work; mine more and retry")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
return
}
h, _ := e.Hash()
writeJSON(w, http.StatusAccepted, map[string]string{"hash": h})
}
func (s *server) getMailbox(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
tag := q.Get("mailbox")
if len(tag) != 32 || !isLowerHex(tag) {
fail(w, http.StatusBadRequest, "mailbox must be 32 hex characters")
return
}
var since int64
if v := q.Get("since"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 0 {
fail(w, http.StatusBadRequest, "since must be a non-negative integer")
return
}
since = n
}
limit := maxMailboxPage
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > maxMailboxPage {
fail(w, http.StatusBadRequest, "limit must be 1-100")
return
}
limit = n
}
items, err := s.Store.Mailbox(r.Context(), tag, since, limit)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
// Ciphertext addressed by an unguessable tag: any site may read it, but it
// must not be cached, or a reply would show up late.
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("["))
for i, e := range items {
b, err := e.Bytes()
if err != nil {
continue
}
if i > 0 {
w.Write([]byte(","))
}
w.Write(b)
}
w.Write([]byte("]"))
}
func isLowerHex(s string) bool {
for i := 0; i < len(s); i++ {
c := s[i]
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
return false
}
}
return true
}
// --- the owner's inbox (admin token) ------------------------------------------
type threadView struct {
Listing string `json:"listing"`
Thread string `json:"thread"`
Messages int `json:"messages"`
Hidden int `json:"hidden"`
Replied bool `json:"replied"`
FirstAt int64 `json:"first_at"`
LastAt int64 `json:"last_at"`
}
func (s *server) listThreads(w http.ResponseWriter, r *http.Request) {
if _, err := s.Inbox.Collect(r.Context()); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
threads, err := s.Store.Threads(r.Context(), s.Device.Cert.Author)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]threadView, 0, len(threads))
for _, t := range threads {
out = append(out, threadView{t.Listing.ID, t.Thread, t.Messages, t.Hidden, t.Replied, t.FirstAt, t.LastAt})
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
type messageView struct {
Hash string `json:"hash"`
Dir string `json:"dir"`
Hidden bool `json:"hidden,omitempty"`
Reason string `json:"reason,omitempty"`
ReceivedAt int64 `json:"received_at"`
Type string `json:"type"`
N int64 `json:"n"`
SentAt int64 `json:"sent_at"`
Text string `json:"text,omitempty"`
Address string `json:"address,omitempty"`
Phone string `json:"phone,omitempty"`
Email string `json:"email,omitempty"`
Note string `json:"note,omitempty"`
ValidUntil int64 `json:"valid_until,omitempty"`
}
func (s *server) getThread(w http.ResponseWriter, r *http.Request) {
ref, thread, ok := s.threadRef(w, r)
if !ok {
return
}
if _, err := s.Inbox.Collect(r.Context()); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
msgs, err := s.Store.ThreadMessages(r.Context(), ref, thread)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if len(msgs) == 0 {
fail(w, http.StatusNotFound, "no such conversation")
return
}
out := make([]messageView, 0, len(msgs))
for _, m := range msgs {
p := m.Plain
v := messageView{Hash: m.Hash, Dir: m.Dir, ReceivedAt: m.ReceivedAt, Type: p.Type, N: p.N, SentAt: p.SentAt,
Text: p.Text, Address: p.Address, Phone: p.Phone, Email: p.Email, Note: p.Note, ValidUntil: p.ValidUntil}
if m.Hidden {
// Withheld: the buyer broke the first-message rules (a link, or too long).
v.Hidden, v.Reason, v.Text = true, "a first message must be short and contain no links", ""
}
out = append(out, v)
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
type replyBody struct {
Type string `json:"type"`
Text string `json:"text"`
Address string `json:"address"`
Phone string `json:"phone"`
Email string `json:"email"`
Note string `json:"note"`
ValidDays int `json:"valid_days"`
}
func (s *server) reply(w http.ResponseWriter, r *http.Request) {
ref, thread, ok := s.threadRef(w, r)
if !ok {
return
}
var b replyBody
if !decodeBody(w, r, &b) {
return
}
env, err := s.Inbox.Send(r.Context(), ref, thread, inbox.Reply{
Type: b.Type, Text: b.Text, Address: b.Address, Phone: b.Phone, Email: b.Email, Note: b.Note, ValidDays: b.ValidDays,
})
switch {
case err == nil:
h, _ := env.Hash()
writeJSON(w, http.StatusOK, map[string]string{"hash": h})
case errors.Is(err, inbox.ErrNoThread), errors.Is(err, inbox.ErrNotOwner):
fail(w, http.StatusNotFound, "no such conversation")
case errors.Is(err, inbox.ErrInvalid):
fail(w, http.StatusBadRequest, strings.TrimPrefix(err.Error(), inbox.ErrInvalid.Error()+": "))
case errors.Is(err, store.ErrNotFound):
fail(w, http.StatusConflict, "the listing is gone, so the reply cannot be routed")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
}
func (s *server) deleteThread(w http.ResponseWriter, r *http.Request) {
ref, thread, ok := s.threadRef(w, r)
if !ok {
return
}
found, err := s.Store.DeleteThread(r.Context(), ref, thread)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if !found {
fail(w, http.StatusNotFound, "no such conversation")
return
}
w.WriteHeader(http.StatusNoContent)
}
// threadRef reads {id} and {thread} from the path. The listing is always the
// node's own: the inbox holds nobody else's conversations.
func (s *server) threadRef(w http.ResponseWriter, r *http.Request) (message.Ref, string, bool) {
id, thread := r.PathValue("id"), r.PathValue("thread")
if len(id) != 32 || !isLowerHex(id) || len(thread) != 64 || !isLowerHex(thread) {
fail(w, http.StatusBadRequest, "malformed listing id or thread")
return message.Ref{}, "", false
}
return message.Ref{Author: s.Device.Cert.Author, ID: id}, thread, true
}
// --- the exact address (admin token) ------------------------------------------
func (s *server) putAddress(w http.ResponseWriter, r *http.Request) {
l, ok := s.own(w, r)
if !ok {
return
}
var a store.Address
if !decodeBody(w, r, &a) {
return
}
for _, f := range []struct {
name, v string
min, max int
nl bool
}{
{"address", a.Address, 1, message.MaxAddress, true},
{"phone", a.Phone, 0, message.MaxPhone, false},
{"email", a.Email, 0, message.MaxEmail, false},
} {
if len(f.v) > f.max {
fail(w, http.StatusBadRequest, f.name+" is too long")
return
}
if err := listing.ValidText(f.v, f.min, f.max, f.nl); err != nil {
fail(w, http.StatusBadRequest, f.name+": "+err.Error())
return
}
}
if err := s.Store.SetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}, a); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *server) getAddress(w http.ResponseWriter, r *http.Request) {
l, ok := s.own(w, r)
if !ok {
return
}
a, err := s.Store.GetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID})
if errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "no address saved for this listing")
return
}
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
noStore(w)
writeJSON(w, http.StatusOK, a)
}
func (s *server) deleteAddress(w http.ResponseWriter, r *http.Request) {
l, ok := s.own(w, r)
if !ok {
return
}
if err := s.Store.DeleteAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusNoContent)
}
// --- helpers ------------------------------------------------------------------
func noStore(w http.ResponseWriter) { w.Header().Set("Cache-Control", "no-store") }
// decodeBody reads a small JSON object strictly: no unknown fields, no
// trailing data.
func decodeBody(w http.ResponseWriter, r *http.Request, v any) bool {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody))
dec.DisallowUnknownFields()
if err := dec.Decode(v); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON body: "+err.Error())
return false
}
if _, err := dec.Token(); err != io.EOF {
fail(w, http.StatusBadRequest, "unexpected data after JSON body")
return false
}
return true
}
// clientIP is the peer address of the connection. Forwarding headers are not
// trusted: they are trivial to forge. Behind a reverse proxy every client then
// shares one allowance, which is the safe failure.
func clientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
// limiter allows each key a number of events per fixed window.
type limiter struct {
mu sync.Mutex
limit int
window time.Duration
clock func() time.Time
hits map[string]*bucket
}
type bucket struct {
start time.Time
n int
}
func newLimiter(limit int, window time.Duration, clock func() time.Time) *limiter {
return &limiter{limit: limit, window: window, clock: clock, hits: map[string]*bucket{}}
}
func (l *limiter) allow(key string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clock()
if len(l.hits) > 10000 { // forget idle clients
for k, b := range l.hits {
if now.Sub(b.start) >= l.window {
delete(l.hits, k)
}
}
}
b := l.hits[key]
if b == nil || now.Sub(b.start) >= l.window {
l.hits[key] = &bucket{start: now, n: 1}
return true
}
if b.n >= l.limit {
return false
}
b.n++
return true
}