Files
nilsandClaude Sonnet 5.5 3799faddcf api: a per-client rate limit on the HTTP API, with trusted proxies for X-Forwarded-For
600 /api/ requests a minute per client address (--requests-per-minute), 429 with Retry-After; static UI files and the node's own machine are exempt. The real client behind a reverse proxy is read from X-Forwarded-For only when the connection comes from a --trusted-proxy, taking the last entry that is not itself a trusted proxy. k8s: TRUSTED_PROXY in config.env (the private ranges) is passed as --trusted-proxy.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
2026-11-19 00:35:21 +01:00

612 lines
18 KiB
Go

package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"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(s.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):
var we *store.WorkError
if errors.As(err, &we) {
// The price of this listing's queue has risen: say what it is now.
writeJSON(w, http.StatusTooManyRequests, map[string]any{
"error": "this listing is receiving many messages; it now needs more proof-of-work",
"required_bits": we.Required,
})
return
}
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})
}
// getRequiredWork tells a buyer's browser how much proof-of-work a message to
// a listing needs right now. The price rises while the listing's queue fills,
// so the browser asks before it mines.
func (s *server) getRequiredWork(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
author, id := q.Get("author"), q.Get("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "author must be 64 and id 32 hex characters")
return
}
bits, err := s.Store.RequiredWork(r.Context(), message.Ref{Author: author, ID: id})
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
noStore(w)
writeJSON(w, http.StatusOK, map[string]int{"bits": bits})
}
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"`
// LastDir is who wrote last: "in" (the buyer) or "out" (the owner).
LastDir string `json:"last_dir"`
// NeedsReply: the buyer wrote last and the message is readable.
NeedsReply bool `json:"needs_reply"`
// Preview is the start of the latest message (empty when it is hidden).
Preview string `json:"preview,omitempty"`
// Effort is the proof-of-work, in bits, of the buyer's first envelope.
Effort int `json:"effort"`
// GrantUntil is when the latest address release ends; 0 if none was sent.
GrantUntil int64 `json:"grant_until,omitempty"`
}
const previewRunes = 120
// threadViews summarises the owner's conversations, optionally of one listing.
func (s *server) threadViews(r *http.Request, listingID string) ([]threadView, error) {
threads, err := s.Store.Threads(r.Context(), s.Device.Cert.Author)
if err != nil {
return nil, err
}
out := make([]threadView, 0, len(threads))
for _, t := range threads {
if listingID != "" && t.Listing.ID != listingID {
continue
}
v := threadView{Listing: t.Listing.ID, Thread: t.Thread, Messages: t.Messages, Hidden: t.Hidden,
Replied: t.Replied, FirstAt: t.FirstAt, LastAt: t.LastAt}
msgs, err := s.Store.ThreadMessages(r.Context(), t.Listing, t.Thread)
if err != nil {
return nil, err
}
firstIn := true
for _, m := range msgs {
if m.Dir == store.InboxIn && firstIn {
v.Effort, firstIn = hexZeroBits(m.Hash), false
}
v.LastDir = m.Dir
v.NeedsReply = m.Dir == store.InboxIn && !m.Hidden
v.Preview = ""
switch {
case m.Hidden:
case m.Plain.Type == message.TypeGrant:
v.GrantUntil = m.Plain.ValidUntil
default:
v.Preview = truncateRunes(m.Plain.Text, previewRunes)
}
}
out = append(out, v)
}
return out, nil
}
// hexZeroBits counts the leading zero bits of a hex-encoded hash.
func hexZeroBits(h string) int {
n := 0
for _, c := range h {
d := strings.IndexRune("0123456789abcdef", c)
if d < 0 {
return n
}
if d == 0 {
n += 4
continue
}
for bit := 3; bit >= 0 && d&(1<<bit) == 0; bit-- {
n++
}
return n
}
return n
}
func truncateRunes(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n]) + "…"
}
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
}
out, err := s.threadViews(r, r.URL.Query().Get("listing"))
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
type mineView struct {
ID string `json:"id"`
Title string `json:"title"`
Kind string `json:"kind,omitempty"`
Price *listing.Price `json:"price,omitempty"`
ExpiresAt int64 `json:"expires_at"`
Threads int `json:"threads"`
NeedsReply int `json:"needs_reply"`
Hidden int `json:"hidden"`
AddressSaved bool `json:"address_saved"`
}
// mine lists the owner's live listings with what the inbox holds for each.
func (s *server) mine(w http.ResponseWriter, r *http.Request) {
if _, err := s.Inbox.Collect(r.Context()); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
ls, err := s.Store.ByAuthor(r.Context(), s.Device.Cert.Author)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
threads, err := s.threadViews(r, "")
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]mineView, 0, len(ls))
for _, l := range ls {
v := mineView{ID: l.ID, Title: l.Title, Kind: l.Kind, Price: l.Price, ExpiresAt: l.ExpiresAt}
for _, t := range threads {
if t.Listing != l.ID {
continue
}
v.Threads++
if t.NeedsReply {
v.NeedsReply++
}
if t.Hidden > 0 {
v.Hidden++
}
}
if _, err := s.Store.GetAddress(r.Context(), message.Ref{Author: l.Author, ID: l.ID}); err == nil {
v.AddressSaved = true
} else if !errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out = append(out, v)
}
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)
}
func (s *server) blockThread(w http.ResponseWriter, r *http.Request) {
s.blockOrUnblock(w, r, s.Inbox.Block)
}
func (s *server) unblockThread(w http.ResponseWriter, r *http.Request) {
s.blockOrUnblock(w, r, s.Inbox.Unblock)
}
func (s *server) blockOrUnblock(w http.ResponseWriter, r *http.Request, do func(context.Context, message.Ref, string) error) {
ref, thread, ok := s.threadRef(w, r)
if !ok {
return
}
switch err := do(r.Context(), ref, thread); {
case err == nil:
w.WriteHeader(http.StatusNoContent)
case errors.Is(err, inbox.ErrNoThread), errors.Is(err, inbox.ErrNotOwner):
fail(w, http.StatusNotFound, "no such conversation")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
}
type blockedView struct {
Listing string `json:"listing"`
Thread string `json:"thread"`
BlockedAt int64 `json:"blocked_at"`
}
// listBlocked lists the conversations the owner blocked, so a block can be lifted.
func (s *server) listBlocked(w http.ResponseWriter, r *http.Request) {
bs, err := s.Store.BlockedThreads(r.Context(), s.Device.Cert.Author)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]blockedView, 0, len(bs))
for _, b := range bs {
out = append(out, blockedView{Listing: b.Listing.ID, Thread: b.Thread, BlockedAt: b.BlockedAt})
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
// 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
}
// 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
}