// Package api is the node's HTTP interface. // // Reading is public: it serves the signed listing records exactly as // replicated, so a browser can verify every signature itself and does not // have to trust the gateway. Writing (publish, update, delete) acts as the // node's owner and requires the admin bearer token. package api import ( "context" "crypto/subtle" "encoding/json" "errors" "fmt" "io" "net/http" "slices" "strconv" "strings" "time" "git.stinnesbeck.com/nils/allmende/internal/identity" "git.stinnesbeck.com/nils/allmende/internal/inbox" "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/p2p" "git.stinnesbeck.com/nils/allmende/internal/store" "git.stinnesbeck.com/nils/allmende/web" ) const ( maxBody = 64 << 10 defaultLifetime = 30 // days ) // Config wires the API to a running node. type Config struct { Store *store.Store Node *p2p.Node Device *identity.Device Regions []string Token string // admin bearer token; empty disables all writes Difficulty int Clock func() time.Time // MessageDifficulty is reported to browsers so they can mine the // proof-of-work of the messages they send. MessageDifficulty int // PostsPerMinute limits envelopes accepted per client address; 0 means 30. PostsPerMinute int // Inbox is the owner's conversations. Without it the owner endpoints are // absent; relaying messages for buyers still works. Inbox *inbox.Inbox // RegionKeeper lets the owner change the regions the node follows while it // runs. Without it Regions is fixed and the endpoint is absent. RegionKeeper RegionKeeper // CertKeeper renews the device certificate from the recovery phrase. Without // it the endpoint is absent and the node reports that it cannot renew. CertKeeper CertKeeper } // CertKeeper renews this node's device certificate and makes it stick: the // same device key, a new certificate, saved, and the node's own listings // signed with it where the old one would run out first. type CertKeeper interface { // CanRenew is false for an identity made without a recovery phrase. CanRenew() bool Renew(root *identity.Identity) (*identity.Cert, error) } // RegionKeeper holds the regions a node follows: it applies and remembers a change. type RegionKeeper interface { Regions() []string SetRegions([]string) error } // MaxRegions is how many regions one node may follow: it replicates everything // in them, so this keeps "follow the world" from being one click. const MaxRegions = 20 // regions is what the node follows now, never nil: the UI reads it as a list. func (s *server) regions() []string { r := s.Regions if s.RegionKeeper != nil { r = s.RegionKeeper.Regions() } if r == nil { return []string{} } return r } type server struct { Config limiter *limiter } // New returns the HTTP handler. func New(cfg Config) http.Handler { if cfg.Clock == nil { cfg.Clock = time.Now } if cfg.PostsPerMinute <= 0 { cfg.PostsPerMinute = defaultPostsPerMinute } s := &server{Config: cfg, limiter: newLimiter(cfg.PostsPerMinute, time.Minute, cfg.Clock)} mux := http.NewServeMux() mux.HandleFunc("GET /api/v1/status", s.status) mux.HandleFunc("GET /api/v1/listings", s.search) mux.HandleFunc("GET /api/v1/listings/{author}/{id}", s.get) mux.HandleFunc("POST /api/v1/listings", s.admin(s.create)) mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update)) mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove)) if cfg.RegionKeeper != nil { mux.HandleFunc("PUT /api/v1/regions", s.admin(s.putRegions)) } if cfg.CertKeeper != nil { mux.HandleFunc("PUT /api/v1/certificate", s.admin(s.putCertificate)) } // Messaging: public relay endpoints for buyers' browsers... mux.HandleFunc("POST /api/v1/messages", s.postMessage) mux.HandleFunc("GET /api/v1/messages", s.getMailbox) mux.HandleFunc("GET /api/v1/messages/required", s.getRequiredWork) // ...and the owner's inbox and private address, behind the admin token. if cfg.Inbox != nil { mux.HandleFunc("GET /api/v1/mine", s.admin(s.mine)) mux.HandleFunc("GET /api/v1/inbox", s.admin(s.listThreads)) mux.HandleFunc("GET /api/v1/inbox/{id}/{thread}", s.admin(s.getThread)) mux.HandleFunc("POST /api/v1/inbox/{id}/{thread}", s.admin(s.reply)) mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}", s.admin(s.deleteThread)) mux.HandleFunc("PUT /api/v1/inbox/{id}/{thread}/block", s.admin(s.blockThread)) mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}/block", s.admin(s.unblockThread)) mux.HandleFunc("GET /api/v1/blocked", s.admin(s.listBlocked)) mux.HandleFunc("PUT /api/v1/listings/{id}/address", s.admin(s.putAddress)) mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress)) mux.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress)) } // Abuse reports: anyone can read what this node makes of a listing's // reports and tip the operator off (proof-of-work, no account); the // operator reads the tips and signs reports. mux.HandleFunc("GET /api/v1/reports", s.getReports) mux.HandleFunc("POST /api/v1/signals", s.postSignal) mux.HandleFunc("GET /api/v1/signals", s.admin(s.listSignals)) mux.HandleFunc("DELETE /api/v1/signals/{author}/{id}", s.admin(s.dismissSignals)) mux.HandleFunc("POST /api/v1/reports", s.admin(s.postReport)) mux.Handle("GET /", s.ui()) return secure(mux) } // contentSecurityPolicy lets the UI load only its own script and styles and // talk only to its own node. Listing text comes from strangers; the UI never // inserts it as HTML, and this policy is the second line of defence. const contentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; " + "img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" // ui serves the embedded browser UI. func (s *server) ui() http.Handler { files := http.FileServerFS(web.Files()) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("Content-Security-Policy", contentSecurityPolicy) h.Set("Referrer-Policy", "no-referrer") h.Set("Cross-Origin-Opener-Policy", "same-origin") h.Set("Cache-Control", "no-cache") // revalidate, so upgrades reach users files.ServeHTTP(w, r) }) } // secure adds headers every response should carry. func secure(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") next.ServeHTTP(w, r) }) } // --- reading -------------------------------------------------------------- func (s *server) status(w http.ResponseWriter, r *http.Request) { n, err := s.Store.Count(r.Context()) if err != nil { fail(w, http.StatusInternalServerError, "internal error") return } writeJSON(w, http.StatusOK, map[string]any{ "peer_id": s.Node.ID().String(), "addrs": s.Node.Addrs(), "author": s.Device.Cert.Author, "device": s.Device.Cert.Device, "regions": s.regions(), "peers": s.Node.PeerCount(), "listings": n, // When this node's device certificate runs out (it is public: it // travels with every listing) and whether the owner can renew it here. "cert_expires_at": s.Device.Current().ExpiresAt, "can_renew": s.CertKeeper != nil && s.CertKeeper.CanRenew(), // Lets the browser report how much anti-spam work a listing carries. "difficulty": s.Difficulty, "message_difficulty": s.MessageDifficulty, }) } func (s *server) search(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() query := store.Query{Kind: q.Get("kind"), Category: q.Get("category"), IncludeHidden: q.Get("hidden") == "1"} if g := q.Get("geohash"); g != "" { for _, p := range strings.Split(g, ",") { if !listing.ValidGeohashPrefix(p) { fail(w, http.StatusBadRequest, fmt.Sprintf("invalid geohash prefix %q", p)) return } query.Geohashes = append(query.Geohashes, p) } } ints := []struct { name string dst any }{ {"min_price", &query.MinPriceCents}, {"max_price", &query.MaxPriceCents}, {"min_area", &query.MinAreaM2}, {"min_rooms", &query.MinRoomsX2}, {"limit", &query.Limit}, {"offset", &query.Offset}, } for _, f := range ints { v := q.Get(f.name) if v == "" { continue } n, err := strconv.ParseInt(v, 10, 64) if err != nil || n < 0 { fail(w, http.StatusBadRequest, fmt.Sprintf("%s must be a non-negative integer", f.name)) return } switch d := f.dst.(type) { case *int64: *d = n case *int: *d = int(n) } } items, err := s.Store.Search(r.Context(), query) if err != nil { fail(w, http.StatusInternalServerError, "internal error") return } writeListings(w, items) } func (s *server) get(w http.ResponseWriter, r *http.Request) { l, err := s.Store.Get(r.Context(), r.PathValue("author"), r.PathValue("id")) if errors.Is(err, store.ErrNotFound) { fail(w, http.StatusNotFound, "not found") return } if err != nil { fail(w, http.StatusInternalServerError, "internal error") return } b, err := l.Bytes() if err != nil { fail(w, http.StatusInternalServerError, "internal error") return } setPublic(w) w.Header().Set("Content-Type", "application/json") w.Write(b) } // writeListings sends the records in their canonical encoding so clients can // verify signatures over the exact bytes. func writeListings(w http.ResponseWriter, items []*listing.Listing) { setPublic(w) w.Header().Set("Content-Type", "application/json") w.Write([]byte("[")) for i, l := range items { b, err := l.Bytes() if err != nil { continue } if i > 0 { w.Write([]byte(",")) } w.Write(b) } w.Write([]byte("]")) } // setPublic marks a response as public data that any website may read. func setPublic(w http.ResponseWriter) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Cache-Control", "public, max-age=15") } // --- writing -------------------------------------------------------------- // draft is what the owner provides; the node adds identity, time, proof of // work and signature. Images are not supported yet. type draft struct { Kind string `json:"kind"` Category string `json:"category"` Geohash string `json:"geohash"` Price *listing.Price `json:"price"` AreaM2 int `json:"area_m2"` RoomsX2 int `json:"rooms_x2"` Features []string `json:"features"` Title string `json:"title"` Description string `json:"description"` Delegate string `json:"delegate"` ExpiresInDays int `json:"expires_in_days"` } func (s *server) admin(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if s.Token == "" { fail(w, http.StatusForbidden, "writing is disabled on this node") return } got := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") if subtle.ConstantTimeCompare([]byte(got), []byte(s.Token)) != 1 { w.Header().Set("WWW-Authenticate", "Bearer") fail(w, http.StatusUnauthorized, "missing or wrong admin token") return } next(w, r) } } // putCertificate renews the device certificate from the recovery phrase. The // phrase is used for this one request and not kept; it never leaves the node // the owner is signed in to, but it does cross the connection to it, so over // anything but localhost the node must sit behind TLS (as for the admin token). func (s *server) putCertificate(w http.ResponseWriter, r *http.Request) { var body struct { Phrase string `json:"phrase"` } if !decodeBody(w, r, &body) { return } if !s.CertKeeper.CanRenew() { fail(w, http.StatusConflict, "this identity has no recovery phrase, so its certificate cannot be renewed") return } root, err := identity.FromPhrase(body.Phrase) if err != nil { fail(w, http.StatusBadRequest, "that is not a valid recovery phrase: check the twelve words") return } cert, err := s.CertKeeper.Renew(root) switch { case errors.Is(err, identity.ErrWrongIdentity): fail(w, http.StatusConflict, "these words belong to a different identity than this node") return case err != nil: fail(w, http.StatusInternalServerError, err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"cert_expires_at": cert.ExpiresAt}) } // putRegions changes the regions the node follows, at once and for good. func (s *server) putRegions(w http.ResponseWriter, r *http.Request) { var body struct { Regions []string `json:"regions"` } if !decodeBody(w, r, &body) { return } var regions []string for _, raw := range body.Regions { region := strings.ToLower(strings.TrimSpace(raw)) if !listing.ValidRegion(region) { fail(w, http.StatusBadRequest, fmt.Sprintf( "%q is not a region: use %d geohash characters, e.g. u1j for Bonn", raw, listing.RegionPrecision)) return } if !slices.Contains(regions, region) { regions = append(regions, region) } } switch { case len(regions) == 0: fail(w, http.StatusBadRequest, "choose at least one region") return case len(regions) > MaxRegions: fail(w, http.StatusBadRequest, fmt.Sprintf("that is too many regions (at most %d)", MaxRegions)) return } if err := s.RegionKeeper.SetRegions(regions); err != nil { fail(w, http.StatusInternalServerError, "could not change the regions: "+err.Error()) return } writeJSON(w, http.StatusOK, map[string]any{"regions": s.RegionKeeper.Regions()}) } func (s *server) readDraft(w http.ResponseWriter, r *http.Request) (*draft, bool) { dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody)) dec.DisallowUnknownFields() var d draft if err := dec.Decode(&d); err != nil { fail(w, http.StatusBadRequest, "invalid JSON body: "+err.Error()) return nil, false } if _, err := dec.Token(); err != io.EOF { fail(w, http.StatusBadRequest, "unexpected data after JSON body") return nil, false } if d.ExpiresInDays < 0 || d.ExpiresInDays > defaultLifetime { fail(w, http.StatusBadRequest, fmt.Sprintf("expires_in_days must be 1-%d", defaultLifetime)) return nil, false } return &d, true } func (d *draft) build(id string, seq uint64, now time.Time) *listing.Listing { days := d.ExpiresInDays if days == 0 { days = defaultLifetime } return &listing.Listing{ Version: listing.Version, ID: id, Seq: seq, CreatedAt: now.Unix(), ExpiresAt: now.Add(time.Duration(days) * 24 * time.Hour).Unix(), Kind: d.Kind, Category: d.Category, Geohash: d.Geohash, Price: d.Price, AreaM2: d.AreaM2, RoomsX2: d.RoomsX2, Features: d.Features, Title: d.Title, Description: d.Description, Delegate: d.Delegate, } } func (s *server) create(w http.ResponseWriter, r *http.Request) { d, ok := s.readDraft(w, r) if !ok { return } id, err := listing.NewID() if err != nil { fail(w, http.StatusInternalServerError, "internal error") return } s.seal(w, r, d.build(id, 1, s.Clock())) } func (s *server) update(w http.ResponseWriter, r *http.Request) { d, ok := s.readDraft(w, r) if !ok { return } old, ok := s.own(w, r) if !ok { return } if listing.Region(d.Geohash) != listing.Region(old.Geohash) { fail(w, http.StatusBadRequest, "the region cannot change; delete this listing and create a new one") return } s.seal(w, r, d.build(old.ID, old.Seq+1, s.Clock())) } func (s *server) remove(w http.ResponseWriter, r *http.Request) { old, ok := s.own(w, r) if !ok { return } now := s.Clock() s.seal(w, r, &listing.Listing{ Version: listing.Version, ID: old.ID, Seq: old.Seq + 1, CreatedAt: now.Unix(), // Outlives every earlier version (<= 30 days), so old copies cannot return. ExpiresAt: now.Add(listing.MaxLifetime).Unix(), Tombstone: true, Geohash: old.Geohash, }) } // own loads the caller's live listing named in the URL. func (s *server) own(w http.ResponseWriter, r *http.Request) (*listing.Listing, bool) { l, err := s.Store.Get(r.Context(), s.Device.Cert.Author, r.PathValue("id")) if errors.Is(err, store.ErrNotFound) { fail(w, http.StatusNotFound, "no such listing of yours") return nil, false } if err != nil { fail(w, http.StatusInternalServerError, "internal error") return nil, false } return l, true } // seal signs l with the node's device, stores and gossips it, and replies // with the signed record. func (s *server) seal(w http.ResponseWriter, r *http.Request, l *listing.Listing) { if err := l.Seal(s.Device, s.Difficulty); err != nil { fail(w, http.StatusInternalServerError, "internal error") return } if err := s.Node.Publish(r.Context(), l); 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'") case errors.Is(err, context.Canceled): fail(w, http.StatusRequestTimeout, "request cancelled") default: fail(w, http.StatusInternalServerError, "internal error") } return } b, err := l.Bytes() if err != nil { fail(w, http.StatusInternalServerError, "internal error") return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(b) } // --- helpers -------------------------------------------------------------- func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) json.NewEncoder(w).Encode(v) } func fail(w http.ResponseWriter, code int, msg string) { writeJSON(w, code, map[string]string{"error": msg}) }