Files
allmende/internal/api/reports.go
T
nilsandClaude Sonnet 5.5 6d55222ac5 abuse reports: signed reports, gossip and sync, a local hide rule, visitor tips
A report is signed by a node operator (device key and certificate) and
gossiped on one global topic. Each node decides whose reports count: the
operator's own report hides a listing on that node, one trusted report of
illegal content hides it, and --hide-after trusted scam reports hide it
(--trust-reporter names others). Hidden listings stay stored and reachable.
Visitors can tip the node's operator off with a proof-of-work request that
hides nothing.

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

228 lines
7.5 KiB
Go

package api
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"time"
"git.stinnesbeck.com/nils/allmende/internal/jcs"
"git.stinnesbeck.com/nils/allmende/internal/pow"
"git.stinnesbeck.com/nils/allmende/internal/report"
"git.stinnesbeck.com/nils/allmende/internal/store"
)
// --- public ------------------------------------------------------------------
// getReports tells what this node makes of the reports about a listing: the
// counts, and whether its own rules hide it. Reports decide nothing for other
// nodes, so this is one node's view.
func (s *server) getReports(w http.ResponseWriter, r *http.Request) {
author, id := r.URL.Query().Get("author"), r.URL.Query().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
}
sum, err := s.Store.Summary(r.Context(), author, id)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
noStore(w)
writeJSON(w, http.StatusOK, sum)
}
// signalRequest is what a visitor's browser sends to tip the operator off. It
// is not signed (a visitor has no key), only backed by proof-of-work: the
// SHA-256 of its canonical encoding has leading zero bits, as with messages.
// Field order matters only for the canonical form: pow sorts before v, and the
// browser mines the same bytes.
type signalRequest struct {
Category string `json:"category"`
CreatedAt int64 `json:"created_at"`
Listing struct {
Author string `json:"author"`
ID string `json:"id"`
} `json:"listing"`
Note string `json:"note"`
PoW uint64 `json:"pow"`
Version int `json:"v"`
}
// postSignal records a visitor's tip. Tips stay on this node: they hide
// nothing and are not gossiped; the operator reads them and may sign a report.
func (s *server) postSignal(w http.ResponseWriter, r *http.Request) {
if !s.limiter.allow(clientIP(r)) {
w.Header().Set("Retry-After", "60")
fail(w, http.StatusTooManyRequests, "too many requests from this address; try again in a minute")
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 2048))
if err != nil {
fail(w, http.StatusRequestEntityTooLarge, "request too large")
return
}
var q signalRequest
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(&q); err != nil {
fail(w, http.StatusBadRequest, "invalid JSON body")
return
}
canon, err := jcs.Marshal(&q)
if err != nil || !bytes.Equal(canon, body) {
fail(w, http.StatusBadRequest, "the request must be in canonical JSON form")
return
}
probe := report.Report{Version: report.Version, Listing: report.Ref{Author: q.Listing.Author, ID: q.Listing.ID}, Category: q.Category, Note: q.Note}
switch {
case q.Version != report.Version:
fail(w, http.StatusBadRequest, "unsupported version")
return
case !report.ValidCategory(q.Category) || q.Category == report.Withdrawn:
fail(w, http.StatusBadRequest, "unknown category")
return
case len(q.Listing.Author) != 64 || !isLowerHex(q.Listing.Author) || len(q.Listing.ID) != 32 || !isLowerHex(q.Listing.ID):
fail(w, http.StatusBadRequest, "listing must name a 64-hex author and a 32-hex id")
return
case len(q.Note) > report.MaxNote || !validTipNote(probe.Note):
fail(w, http.StatusBadRequest, "the note is too long or has control characters")
return
}
now := s.Clock()
if d := time.Unix(q.CreatedAt, 0).Sub(now); d > report.MaxClockSkew || d < -report.MaxClockSkew {
fail(w, http.StatusBadRequest, "created_at is too far from this node's clock")
return
}
work := pow.LeadingZeroBits(canon)
if work < s.MessageDifficulty {
fail(w, http.StatusBadRequest, "not enough proof-of-work")
return
}
if _, err := s.Store.Region(r.Context(), q.Listing.Author, q.Listing.ID); errors.Is(err, store.ErrNotFound) {
fail(w, http.StatusNotFound, "this node does not know that listing")
return
} else if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
sum := sha256.Sum256(canon)
err = s.Store.AddSignal(r.Context(), store.Signal{
Hash: hex.EncodeToString(sum[:]), Author: q.Listing.Author, ListingID: q.Listing.ID,
Category: q.Category, Note: q.Note, Work: work,
})
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusAccepted)
}
func validTipNote(s string) bool {
for _, c := range s {
if c < 0x20 || c == 0x7f {
return false
}
}
return true
}
// --- the operator (admin token) ---------------------------------------------
type signalView struct {
store.Signal
Title string `json:"title,omitempty"`
}
// listSignals is the operator's queue of visitor tips, strongest first.
func (s *server) listSignals(w http.ResponseWriter, r *http.Request) {
tips, err := s.Store.Signals(r.Context())
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
out := make([]signalView, 0, len(tips))
for _, g := range tips {
v := signalView{Signal: g}
if l, err := s.Store.Get(r.Context(), g.Author, g.ListingID); err == nil {
v.Title = l.Title
}
out = append(out, v)
}
noStore(w)
writeJSON(w, http.StatusOK, out)
}
// dismissSignals throws away the tips about one listing.
func (s *server) dismissSignals(w http.ResponseWriter, r *http.Request) {
author, id := r.PathValue("author"), r.PathValue("id")
if len(author) != 64 || !isLowerHex(author) || len(id) != 32 || !isLowerHex(id) {
fail(w, http.StatusBadRequest, "malformed listing")
return
}
if _, err := s.Store.DeleteSignals(r.Context(), author, id); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
w.WriteHeader(http.StatusNoContent)
}
type reportBody struct {
Listing struct {
Author string `json:"author"`
ID string `json:"id"`
} `json:"listing"`
Category string `json:"category"`
Note string `json:"note"`
}
// postReport signs a report as this node's operator and gossips it. The
// operator's own report hides the listing on this node at once; others
// count it only if they trust this operator. Category "withdrawn" takes an
// earlier report back. The tips about the listing are cleared.
func (s *server) postReport(w http.ResponseWriter, r *http.Request) {
var b reportBody
if !decodeBody(w, r, &b) {
return
}
now := s.Clock()
rep := &report.Report{
Listing: report.Ref{Author: b.Listing.Author, ID: b.Listing.ID},
Category: b.Category,
Note: b.Note,
CreatedAt: now.Unix(),
ExpiresAt: now.Add(report.MaxLifetime).Unix(),
}
if err := rep.Seal(s.Device, s.Difficulty); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
if err := s.Node.PublishReport(r.Context(), rep); 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.ErrRevoked):
fail(w, http.StatusConflict, "this node's device has been revoked; run 'allmende recover'")
default:
fail(w, http.StatusInternalServerError, "internal error")
}
return
}
if _, err := s.Store.DeleteSignals(r.Context(), b.Listing.Author, b.Listing.ID); err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
sum, err := s.Store.Summary(r.Context(), b.Listing.Author, b.Listing.ID)
if err != nil {
fail(w, http.StatusInternalServerError, "internal error")
return
}
writeJSON(w, http.StatusOK, sum)
}