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<