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>
This commit is contained in:
@@ -17,6 +17,12 @@ signature itself, so you don't have to trust the node it talks to. The UI is
|
||||
pre-built and embedded; Node.js is only needed to change it
|
||||
(`cd web && npm ci && npm run build && npm test`).
|
||||
|
||||
Buyers can write to an owner straight from a listing, without an account.
|
||||
Messages are end-to-end encrypted in the browser and relayed through the
|
||||
network, so a node only ever sees ciphertext. The owner reads and answers
|
||||
through the token-protected API (`GET /api/v1/inbox`, see the protocol doc) and
|
||||
can release the exact address as a signed message; an owner UI is not built yet.
|
||||
|
||||
A second node on the same network finds this one automatically (mDNS); across
|
||||
networks, pass `--bootstrap /ip4/<addr>/tcp/<port>/p2p/<peer id>`.
|
||||
|
||||
|
||||
+17
-2
@@ -16,7 +16,9 @@ import (
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/api"
|
||||
"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/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
@@ -37,7 +39,11 @@ func cmdRun(args []string) error {
|
||||
httpAddr := fs.String("http", "127.0.0.1:8080", "address for the HTTP API")
|
||||
noMDNS := fs.Bool("no-mdns", false, "do not look for peers on the local network")
|
||||
difficulty := fs.Int("difficulty", listing.DefaultDifficulty,
|
||||
"proof-of-work bits; must match the rest of the network")
|
||||
"proof-of-work bits for listings; must match the rest of the network")
|
||||
msgDifficulty := fs.Int("message-difficulty", message.DefaultDifficulty,
|
||||
"proof-of-work bits for messages; must match the rest of the network")
|
||||
maxNewThreads := fs.Int("max-new-threads", inbox.DefaultMaxNewThreads,
|
||||
"how many new conversations each of your listings can start per day")
|
||||
fs.Parse(args)
|
||||
|
||||
if len(regions) == 0 {
|
||||
@@ -61,7 +67,9 @@ func cmdRun(args []string) error {
|
||||
"expires", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02"))
|
||||
}
|
||||
|
||||
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{Difficulty: *difficulty})
|
||||
st, err := store.Open(filepath.Join(*data, dbFile), store.Options{
|
||||
Difficulty: *difficulty, MessageDifficulty: *msgDifficulty,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -79,6 +87,8 @@ func cmdRun(args []string) error {
|
||||
MDNS: !*noMDNS,
|
||||
Difficulty: *difficulty,
|
||||
Logger: log,
|
||||
|
||||
MessageDifficulty: *msgDifficulty,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -91,6 +101,11 @@ func cmdRun(args []string) error {
|
||||
}
|
||||
handler := api.New(api.Config{
|
||||
Store: st, Node: node, Device: dev, Regions: regions, Token: token, Difficulty: *difficulty,
|
||||
MessageDifficulty: *msgDifficulty,
|
||||
Inbox: &inbox.Inbox{
|
||||
Store: st, Device: dev, Publisher: node,
|
||||
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
|
||||
},
|
||||
})
|
||||
|
||||
ln, err := net.Listen("tcp", *httpAddr)
|
||||
|
||||
+53
-22
@@ -131,7 +131,13 @@ within 30 days.
|
||||
revocations every 30 minutes, so newcomers hear about them without waiting
|
||||
for a sync.
|
||||
|
||||
## Messaging (wire format, draft, not implemented yet)
|
||||
## Messaging
|
||||
|
||||
Implemented in `internal/message` (wire format), `internal/inbox` (owner side)
|
||||
and `web/src/message.ts` (buyer side). Both crypto implementations are tested
|
||||
against a fixture written by the Go code
|
||||
(`internal/message/testdata/fixture.json`, refresh with
|
||||
`UPDATE_FIXTURES=1 go test ./internal/message -run TestGoldenFixture`).
|
||||
|
||||
A browser-only buyer contacts a listing's owner, and the owner can answer and
|
||||
release the exact address. Messages are **end-to-end encrypted**, short,
|
||||
@@ -194,8 +200,10 @@ different contexts; no separate encryption key is added to certificates.
|
||||
|
||||
**Padding:** plaintext = canonical JSON, then `0x80`, then zero bytes up to the
|
||||
next size of 512, 1024, 2048 or 4096 bytes, so length reveals little.
|
||||
Plaintext before padding is at most 4096 bytes. Relay and owner/buyer limits
|
||||
are in UTF-8 bytes.
|
||||
Plaintext before padding is at most 4095 bytes (one byte is the marker). Relay
|
||||
and owner/buyer limits are in UTF-8 bytes. The plaintext must be *canonical*:
|
||||
a receiver re-encodes what it decoded and rejects any difference (unknown
|
||||
fields, odd escapes, reordering).
|
||||
|
||||
### Plaintext (inside `ct`)
|
||||
|
||||
@@ -236,12 +244,15 @@ the browser had the data and cannot be forced to forget it.
|
||||
3. proof-of-work at the node's message difficulty;
|
||||
4. `to = owner`: the listing must be known, live (not expired or deleted) and
|
||||
in this region, and `rcpt` must equal its current `device`;
|
||||
5. `to = buyer`: no listing check (the owner may have deleted the listing since,
|
||||
and replies must still arrive), only the checks above;
|
||||
6. per-queue caps: at most 200 live envelopes per listing (`owner`) and 50 per
|
||||
mailbox (`buyer`). When full, the envelope with the **least work** is
|
||||
evicted (oldest first on ties), so filling a queue costs more than the
|
||||
proof-of-work of the messages it displaces.
|
||||
5. `to = buyer`: the listing need not exist (the owner may have deleted it
|
||||
since, and replies must still arrive). If the listing *is* known, the
|
||||
envelope's region must still match it;
|
||||
6. per-queue caps: at most 200 live envelopes per listing (`owner`), 50 per
|
||||
mailbox (`buyer`) and 20000 per node (all configurable in the store). When
|
||||
full, the envelope with the **least work** is evicted (oldest first on
|
||||
ties); a newcomer with less work than everything queued is rejected. So
|
||||
filling a queue costs more than the proof-of-work of the messages it
|
||||
displaces.
|
||||
|
||||
Invalid envelopes are rejected and the relaying peer loses score. Unknown
|
||||
listing, wrong `rcpt` after a device change, and clock failures are **ignored
|
||||
@@ -256,28 +267,48 @@ text rules below are enforced by endpoints.
|
||||
clickable links.
|
||||
- **First-message restriction:** until the owner has sent a message in a
|
||||
thread, the buyer's messages must be short text with **no links**: no
|
||||
`://`, no `www.`, no hostname-like `label.tld` token. The owner's node hides
|
||||
violating messages (marked "contains a link") and the buyer's browser
|
||||
refuses to send them. This is a heuristic against scams, not a guarantee.
|
||||
`://`, no `www.`, no hostname-like `label.tld` token (a regexp over letters,
|
||||
digits and `-`, after lowercasing; it also flags "Hallo.Ich", which the UI
|
||||
says). The owner's node stores such messages but marks them **hidden**: the
|
||||
API withholds their text. The buyer's browser refuses to send them. The
|
||||
rule is shared by Go and TypeScript and checked against common test vectors.
|
||||
This is a heuristic against scams, not a guarantee.
|
||||
- **Owner-side rate limit:** a node accepts at most N new threads per listing
|
||||
per day (default 20). Surplus first messages stay queued and unread until
|
||||
they expire; highest work first, then oldest.
|
||||
per 24 hours (`--max-new-threads`, default 20). Surplus first messages stay
|
||||
unseen until room frees up (or they expire); highest work first, then oldest.
|
||||
Envelopes that fail to decrypt are remembered (`inbox_seen`) and not tried
|
||||
again.
|
||||
- Messages carry **no attachments and no images**.
|
||||
- The decrypted inbox is stored only on the owner's node, in its database. The
|
||||
exact address is a private per-listing field there, never signed or
|
||||
gossiped; "release address" pre-fills a `grant` that the owner can edit.
|
||||
|
||||
### Transport (planned)
|
||||
### Transport
|
||||
|
||||
- **Gossip** on `/allmende/1/messages/<region>`; **sync** extends
|
||||
`/allmende/1/sync` with a message stream paged by `(created_at, hash)`.
|
||||
- **HTTP**: `POST /api/v1/messages` (no token; the node validates, stores and
|
||||
gossips the envelope; rate limited per client) and
|
||||
`GET /api/v1/messages?mailbox=<tag>&after=<created_at>` for the buyer's
|
||||
browser to poll. The owner's decrypted inbox and replies use the existing
|
||||
admin token.
|
||||
`/allmende/1/sync` with kind `messages`, paged by `(created_at, hash)`.
|
||||
- **HTTP**, public: `POST /api/v1/messages` (the canonical envelope as the
|
||||
body, at most 10 KB; the node validates, stores and gossips it; answers 202
|
||||
`{"hash"}`; 400 invalid, 404 unknown listing, 413 too large, 429 rate
|
||||
limited per client IP) and
|
||||
`GET /api/v1/messages?mailbox=<tag>&since=<created_at>&limit=<n ≤ 100>` for
|
||||
the buyer's browser to poll (`since` is inclusive; the browser re-reads the
|
||||
last hour each time and dedupes by hash). Responses are `no-store`.
|
||||
- **HTTP**, owner (admin token): `GET /api/v1/inbox` (threads),
|
||||
`GET|POST|DELETE /api/v1/inbox/{listing}/{thread}` (read, reply, erase) and
|
||||
`PUT|GET|DELETE /api/v1/listings/{id}/address` (the private address). A
|
||||
reply body is `{type: "text"|"grant", text, address, phone, email, note,
|
||||
valid_days}`; a grant without `address` uses the stored one.
|
||||
- `GET /api/v1/status` reports `message_difficulty`, which the browser mines to.
|
||||
- **Flags:** `--message-difficulty` (default 14) and `--max-new-threads`.
|
||||
- A gateway sees the buyer's IP address and mailbox tag. Buyers can use any
|
||||
gateway; nothing else about the conversation is exposed.
|
||||
- **Buyer UI:** a contact form on every verified listing; a private link
|
||||
`#/c/<author>/<id>/<thread secret>` (the secret stays in the URL fragment,
|
||||
which is never sent to a server) that polls every 20 s, shows only verified
|
||||
owner replies and counts the rest as rejected; `#/messages` lists the
|
||||
conversations stored in this browser. There is **no owner UI yet**; the owner
|
||||
uses the admin API.
|
||||
|
||||
### Limits of this design
|
||||
|
||||
@@ -348,7 +379,7 @@ Proof-of-work per listing and per revocation, plus subscribable blocklists
|
||||
|
||||
## Open
|
||||
|
||||
Messaging implementation and abuse reporting for messages, reciprocity rules, anti-
|
||||
An owner UI for the inbox, abuse reporting for messages, reciprocity rules, anti-
|
||||
discrimination (AGG) content rules, blocklists, peer scoring and rate limits,
|
||||
incremental sync and anti-entropy, DHT discovery, UI publishing, image hosting,
|
||||
recovering listings onto a fresh machine with an empty database, a helper to
|
||||
|
||||
@@ -3,9 +3,11 @@ module git.stinnesbeck.com/nils/allmende
|
||||
go 1.27.3
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.2.0
|
||||
github.com/libp2p/go-libp2p v0.52.0
|
||||
github.com/libp2p/go-libp2p-pubsub v0.19.0
|
||||
github.com/tyler-smith/go-bip39 v1.1.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/term v0.48.0
|
||||
modernc.org/sqlite v1.62.0
|
||||
)
|
||||
@@ -92,7 +94,6 @@ require (
|
||||
go.uber.org/mock v0.6.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
golang.org/x/crypto v0.59.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20261113113407-e3970619a1a4 // indirect
|
||||
golang.org/x/mod v0.43.0 // indirect
|
||||
golang.org/x/net v0.62.0 // indirect
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5 h1:JA0fFr+kxpqTdxR9LOBiTWpGNchqmkcsgmdeJZRclZ0=
|
||||
filippo.io/bigmod v0.1.1-0.20260103110540-f8a47775ebe5/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
|
||||
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
|
||||
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
|
||||
filippo.io/keygen v1.0.0 h1:u0/Fhxlgz3uPv+XxhfgTq3BJt5VesIPM5ue/OuG7qjQ=
|
||||
filippo.io/keygen v1.0.0/go.mod h1:9nnw1SlYHYuPSo/3wjQzNjSbeHlq2NsKo5iEtfJPWP0=
|
||||
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
|
||||
|
||||
+30
-1
@@ -19,6 +19,7 @@ import (
|
||||
"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"
|
||||
@@ -39,10 +40,20 @@ type Config struct {
|
||||
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
|
||||
}
|
||||
|
||||
type server struct {
|
||||
Config
|
||||
limiter *limiter
|
||||
}
|
||||
|
||||
// New returns the HTTP handler.
|
||||
@@ -50,7 +61,10 @@ func New(cfg Config) http.Handler {
|
||||
if cfg.Clock == nil {
|
||||
cfg.Clock = time.Now
|
||||
}
|
||||
s := &server{cfg}
|
||||
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)
|
||||
@@ -58,6 +72,20 @@ func New(cfg Config) http.Handler {
|
||||
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))
|
||||
|
||||
// Messaging: public relay endpoints for buyers' browsers...
|
||||
mux.HandleFunc("POST /api/v1/messages", s.postMessage)
|
||||
mux.HandleFunc("GET /api/v1/messages", s.getMailbox)
|
||||
// ...and the owner's inbox and private address, behind the admin token.
|
||||
if cfg.Inbox != nil {
|
||||
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/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))
|
||||
}
|
||||
mux.Handle("GET /", s.ui())
|
||||
return secure(mux)
|
||||
}
|
||||
@@ -107,6 +135,7 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
||||
"listings": n,
|
||||
// Lets the browser report how much anti-spam work a listing carries.
|
||||
"difficulty": s.Difficulty,
|
||||
"message_difficulty": s.MessageDifficulty,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"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"
|
||||
@@ -29,28 +30,37 @@ type fixture struct {
|
||||
dev *identity.Device
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, tok string) *fixture {
|
||||
const msgDifficulty = 4
|
||||
|
||||
func newFixture(t *testing.T, tok string, tweak ...func(*Config)) *fixture {
|
||||
t.Helper()
|
||||
root, _, _ := identity.NewRoot()
|
||||
dev, err := identity.Enroll(root, time.Now().Add(-time.Hour), 90*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node, err := p2p.New(context.Background(), p2p.Config{
|
||||
Device: dev, Store: s, Regions: []string{"u1x"}, Difficulty: difficulty,
|
||||
MessageDifficulty: msgDifficulty,
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(New(Config{
|
||||
cfg := Config{
|
||||
Store: s, Node: node, Device: dev, Regions: []string{"u1x"}, Token: tok, Difficulty: difficulty,
|
||||
}))
|
||||
MessageDifficulty: msgDifficulty,
|
||||
Inbox: &inbox.Inbox{Store: s, Device: dev, Publisher: node, Difficulty: msgDifficulty},
|
||||
}
|
||||
for _, f := range tweak {
|
||||
f(&cfg)
|
||||
}
|
||||
srv := httptest.NewServer(New(cfg))
|
||||
t.Cleanup(func() { srv.Close(); node.Close(); s.Close() })
|
||||
return &fixture{srv: srv, s: s, dev: dev}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
func (f *fixture) publish(t *testing.T) *listing.Listing {
|
||||
t.Helper()
|
||||
code, body := f.do(t, "POST", "/api/v1/listings", draftJSON, true)
|
||||
if code != 200 {
|
||||
t.Fatalf("create: %d %s", code, body)
|
||||
}
|
||||
var l listing.Listing
|
||||
if err := json.Unmarshal(body, &l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &l
|
||||
}
|
||||
|
||||
// send posts an envelope the way a buyer's browser does (no token).
|
||||
func (f *fixture) send(t *testing.T, e *message.Envelope) (int, []byte) {
|
||||
t.Helper()
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return f.sendRaw(t, b)
|
||||
}
|
||||
|
||||
func (f *fixture) sendRaw(t *testing.T, b []byte) (int, []byte) {
|
||||
t.Helper()
|
||||
resp, err := http.Post(f.srv.URL+"/api/v1/messages", "application/json", bytes.NewReader(b))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var buf bytes.Buffer
|
||||
buf.ReadFrom(resp.Body)
|
||||
return resp.StatusCode, buf.Bytes()
|
||||
}
|
||||
|
||||
func buyerHello(t *testing.T, l *listing.Listing, tk *message.ThreadKey, text string) *message.Envelope {
|
||||
t.Helper()
|
||||
p := &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: text}
|
||||
e, err := message.SealToOwner(l, tk, p, time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
func newThread(t *testing.T) *message.ThreadKey {
|
||||
t.Helper()
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return tk
|
||||
}
|
||||
|
||||
func TestMessagingOverHTTP(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
tk := newThread(t)
|
||||
thread := tk.PublicHex()
|
||||
|
||||
// 1. The buyer's browser posts an encrypted envelope. No token.
|
||||
code, body := f.send(t, buyerHello(t, l, tk, "Ist die Wohnung noch frei?"))
|
||||
if code != http.StatusAccepted || !bytes.Contains(body, []byte(`"hash"`)) {
|
||||
t.Fatalf("post: %d %s", code, body)
|
||||
}
|
||||
|
||||
// 2. The owner sees one conversation, with the decrypted text.
|
||||
code, body = f.do(t, "GET", "/api/v1/inbox", "", true)
|
||||
var threads []threadView
|
||||
if code != 200 || json.Unmarshal([]byte(body), &threads) != nil || len(threads) != 1 {
|
||||
t.Fatalf("inbox: %d %s", code, body)
|
||||
}
|
||||
if threads[0].Listing != l.ID || threads[0].Thread != thread || threads[0].Replied || threads[0].Messages != 1 {
|
||||
t.Fatalf("thread summary: %+v", threads[0])
|
||||
}
|
||||
path := "/api/v1/inbox/" + l.ID + "/" + thread
|
||||
code, body = f.do(t, "GET", path, "", true)
|
||||
var msgs []messageView
|
||||
if code != 200 || json.Unmarshal([]byte(body), &msgs) != nil || len(msgs) != 1 || msgs[0].Text != "Ist die Wohnung noch frei?" || msgs[0].Dir != "in" {
|
||||
t.Fatalf("thread: %d %s", code, body)
|
||||
}
|
||||
|
||||
// 3. The owner answers with text, then saves the address and grants it.
|
||||
if code, body = f.do(t, "POST", path, `{"type":"text","text":"Ja, noch frei."}`, true); code != 200 {
|
||||
t.Fatalf("reply: %d %s", code, body)
|
||||
}
|
||||
if code, body = f.do(t, "PUT", "/api/v1/listings/"+l.ID+"/address",
|
||||
`{"address":"Musterstraße 12, 20255 Hamburg","phone":"+49 40 1"}`, true); code != 204 {
|
||||
t.Fatalf("put address: %d %s", code, body)
|
||||
}
|
||||
if code, body = f.do(t, "POST", path,
|
||||
`{"type":"grant","note":"Samstag 10 Uhr, bitte zweimal klingeln","valid_days":3}`, true); code != 200 {
|
||||
t.Fatalf("grant: %d %s", code, body)
|
||||
}
|
||||
|
||||
// 4. The buyer polls its mailbox and decrypts both, verified as the owner's.
|
||||
mb, _ := tk.Mailbox()
|
||||
resp, err := http.Get(f.srv.URL + "/api/v1/messages?mailbox=" + mb)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 || resp.Header.Get("Cache-Control") != "no-store" || resp.Header.Get("Access-Control-Allow-Origin") != "*" {
|
||||
t.Fatalf("mailbox headers: %d %v", resp.StatusCode, resp.Header)
|
||||
}
|
||||
var box []message.Envelope
|
||||
if err := json.NewDecoder(resp.Body).Decode(&box); err != nil || len(box) != 2 {
|
||||
t.Fatalf("mailbox: %d envelopes, %v", len(box), err)
|
||||
}
|
||||
var sawText, sawGrant bool
|
||||
for i := range box {
|
||||
p, err := box[i].OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatalf("buyer cannot open a reply: %v", err)
|
||||
}
|
||||
switch p.Type {
|
||||
case message.TypeText:
|
||||
sawText = p.Text == "Ja, noch frei."
|
||||
case message.TypeGrant:
|
||||
sawGrant = p.Address == "Musterstraße 12, 20255 Hamburg" && p.Phone == "+49 40 1" &&
|
||||
p.Note == "Samstag 10 Uhr, bitte zweimal klingeln"
|
||||
}
|
||||
}
|
||||
if !sawText || !sawGrant {
|
||||
t.Fatalf("text=%v grant=%v", sawText, sawGrant)
|
||||
}
|
||||
|
||||
// The owner's view now shows the replies too and marks the thread answered.
|
||||
_, body = f.do(t, "GET", "/api/v1/inbox", "", true)
|
||||
_ = json.Unmarshal([]byte(body), &threads)
|
||||
if !threads[0].Replied || threads[0].Messages != 3 {
|
||||
t.Fatalf("after replying: %+v", threads[0])
|
||||
}
|
||||
|
||||
// 5. Erasing the conversation removes it from the node.
|
||||
if code, _ = f.do(t, "DELETE", path, "", true); code != 204 {
|
||||
t.Fatalf("delete: %d", code)
|
||||
}
|
||||
if code, _ = f.do(t, "GET", path, "", true); code != 404 {
|
||||
t.Fatalf("deleted thread still served: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHiddenFirstMessageTextIsWithheld(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
tk := newThread(t)
|
||||
if code, body := f.send(t, buyerHello(t, l, tk, "Hier: https://example.com/kaution")); code != 202 {
|
||||
t.Fatalf("post: %d %s", code, body)
|
||||
}
|
||||
code, body := f.do(t, "GET", "/api/v1/inbox/"+l.ID+"/"+tk.PublicHex(), "", true)
|
||||
if code != 200 || bytes.Contains(body, []byte("example.com")) {
|
||||
t.Fatalf("the link text must not be served: %d %s", code, body)
|
||||
}
|
||||
var msgs []messageView
|
||||
_ = json.Unmarshal([]byte(body), &msgs)
|
||||
if len(msgs) != 1 || !msgs[0].Hidden || msgs[0].Reason == "" {
|
||||
t.Fatalf("message should be marked hidden: %+v", msgs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostingRules(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
good := buyerHello(t, l, newThread(t), "hallo")
|
||||
goodBytes, _ := good.Bytes()
|
||||
|
||||
// Not canonical: same content, different spelling.
|
||||
var pretty bytes.Buffer
|
||||
_ = json.Indent(&pretty, goodBytes, "", " ")
|
||||
for name, tc := range map[string]struct {
|
||||
body []byte
|
||||
want int
|
||||
}{
|
||||
"not JSON": {[]byte("hello"), 400},
|
||||
"not canonical": {pretty.Bytes(), 400},
|
||||
"unknown field": {bytes.Replace(goodBytes, []byte(`{"created_at"`), []byte(`{"extra":1,"created_at"`), 1), 400},
|
||||
"too large": {bytes.Repeat([]byte("a"), message.MaxSize+100), 413},
|
||||
"empty": {nil, 400},
|
||||
"unknown listing": {func() []byte {
|
||||
other := *l
|
||||
other.ID = strings.Repeat("ab", 16)
|
||||
e := buyerHello(t, &other, newThread(t), "x")
|
||||
b, _ := e.Bytes()
|
||||
return b
|
||||
}(), 404},
|
||||
"weak work": {func() []byte {
|
||||
for {
|
||||
e, err := message.SealToOwner(l, newThread(t), &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: "x"}, time.Now(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w < msgDifficulty {
|
||||
b, _ := e.Bytes()
|
||||
return b
|
||||
}
|
||||
}
|
||||
}(), 400},
|
||||
} {
|
||||
if code, body := f.sendRaw(t, tc.body); code != tc.want {
|
||||
t.Errorf("%s: %d %s, want %d", name, code, body, tc.want)
|
||||
}
|
||||
}
|
||||
if code, body := f.sendRaw(t, goodBytes); code != 202 {
|
||||
t.Fatalf("the valid one: %d %s", code, body)
|
||||
}
|
||||
// Posting it again is harmless.
|
||||
if code, _ := f.sendRaw(t, goodBytes); code != 202 {
|
||||
t.Fatalf("duplicate: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostingIsRateLimited(t *testing.T) {
|
||||
f := newFixture(t, token, func(c *Config) { c.PostsPerMinute = 3 })
|
||||
l := f.publish(t)
|
||||
for i := 0; i < 3; i++ {
|
||||
if code, body := f.send(t, buyerHello(t, l, newThread(t), "hallo")); code != 202 {
|
||||
t.Fatalf("post %d: %d %s", i, code, body)
|
||||
}
|
||||
}
|
||||
resp, err := http.Post(f.srv.URL+"/api/v1/messages", "application/json", strings.NewReader("{}"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 429 || resp.Header.Get("Retry-After") == "" {
|
||||
t.Fatalf("fourth post: %d retry-after=%q", resp.StatusCode, resp.Header.Get("Retry-After"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailboxQueryIsValidated(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
for _, q := range []string{
|
||||
"", "?mailbox=zz", "?mailbox=" + strings.Repeat("A", 32), "?mailbox=" + strings.Repeat("0", 31),
|
||||
"?mailbox=" + strings.Repeat("0", 32) + "&since=-1", "?mailbox=" + strings.Repeat("0", 32) + "&limit=0",
|
||||
"?mailbox=" + strings.Repeat("0", 32) + "&limit=1000", "?mailbox=" + strings.Repeat("0", 32) + "&since=abc",
|
||||
} {
|
||||
if code, _ := f.do(t, "GET", "/api/v1/messages"+q, "", false); code != 400 {
|
||||
t.Errorf("%q: %d, want 400", q, code)
|
||||
}
|
||||
}
|
||||
code, body := f.do(t, "GET", "/api/v1/messages?mailbox="+strings.Repeat("0", 32), "", false)
|
||||
if code != 200 || string(body) != "[]" {
|
||||
t.Fatalf("empty mailbox: %d %s", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerEndpointsNeedTheToken(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
thread := strings.Repeat("ab", 32)
|
||||
for _, c := range []struct{ method, path string }{
|
||||
{"GET", "/api/v1/inbox"},
|
||||
{"GET", "/api/v1/inbox/" + l.ID + "/" + thread},
|
||||
{"POST", "/api/v1/inbox/" + l.ID + "/" + thread},
|
||||
{"DELETE", "/api/v1/inbox/" + l.ID + "/" + thread},
|
||||
{"PUT", "/api/v1/listings/" + l.ID + "/address"},
|
||||
{"GET", "/api/v1/listings/" + l.ID + "/address"},
|
||||
{"DELETE", "/api/v1/listings/" + l.ID + "/address"},
|
||||
} {
|
||||
if code, _ := f.do(t, c.method, c.path, "{}", false); code != 401 {
|
||||
t.Errorf("%s %s without token: %d, want 401", c.method, c.path, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplyErrors(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
tk := newThread(t)
|
||||
f.send(t, buyerHello(t, l, tk, "hallo"))
|
||||
path := "/api/v1/inbox/" + l.ID + "/" + tk.PublicHex()
|
||||
f.do(t, "GET", "/api/v1/inbox", "", true) // collect
|
||||
|
||||
for name, c := range map[string]struct {
|
||||
path, body string
|
||||
want int
|
||||
}{
|
||||
"unknown thread": {"/api/v1/inbox/" + l.ID + "/" + strings.Repeat("ab", 32), `{"type":"text","text":"x"}`, 404},
|
||||
"malformed thread": {"/api/v1/inbox/" + l.ID + "/xyz", `{"type":"text","text":"x"}`, 400},
|
||||
"unknown field": {path, `{"type":"text","text":"x","bogus":1}`, 400},
|
||||
"grant with no address": {path, `{"type":"grant"}`, 400},
|
||||
"grant for 31 days": {path, `{"type":"grant","address":"Weg 1","valid_days":31}`, 400},
|
||||
"empty text": {path, `{"type":"text","text":""}`, 400},
|
||||
"unknown type": {path, `{"type":"image"}`, 400},
|
||||
"text over the limit": {path, `{"type":"text","text":"` + strings.Repeat("a", message.MaxText+1) + `"}`, 400},
|
||||
"trailing data": {path, `{"type":"text","text":"x"} {}`, 400},
|
||||
"someone else's listing": {"/api/v1/inbox/" + strings.Repeat("cd", 16) + "/" + tk.PublicHex(), `{"type":"text","text":"x"}`, 404},
|
||||
} {
|
||||
if code, body := f.do(t, "POST", c.path, c.body, true); code != c.want {
|
||||
t.Errorf("%s: %d %s, want %d", name, code, body, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddressEndpoints(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
l := f.publish(t)
|
||||
path := "/api/v1/listings/" + l.ID + "/address"
|
||||
|
||||
if code, _ := f.do(t, "GET", path, "", true); code != 404 {
|
||||
t.Fatalf("before saving: %d", code)
|
||||
}
|
||||
if code, body := f.do(t, "PUT", path, `{"address":"Weg 1, 20095 Hamburg","email":"a@example.com"}`, true); code != 204 {
|
||||
t.Fatalf("put: %d %s", code, body)
|
||||
}
|
||||
code, body := f.do(t, "GET", path, "", true)
|
||||
if code != 200 || !strings.Contains(string(body), "Weg 1") || !strings.Contains(string(body), "a@example.com") {
|
||||
t.Fatalf("get: %d %s", code, body)
|
||||
}
|
||||
// The exact address is nowhere on the public side.
|
||||
if _, pub := f.do(t, "GET", "/api/v1/listings/"+l.Author+"/"+l.ID, "", false); strings.Contains(string(pub), "Weg 1") {
|
||||
t.Fatal("the address leaked into the public listing")
|
||||
}
|
||||
if code, _ := f.do(t, "PUT", path, `{"address":""}`, true); code != 400 {
|
||||
t.Errorf("empty address: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "PUT", path, `{"address":"`+strings.Repeat("a", message.MaxAddress+1)+`"}`, true); code != 400 {
|
||||
t.Errorf("long address: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "PUT", "/api/v1/listings/"+strings.Repeat("cd", 16)+"/address", `{"address":"x"}`, true); code != 404 {
|
||||
t.Errorf("someone else's listing: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "DELETE", path, "", true); code != 204 {
|
||||
t.Fatalf("delete: %d", code)
|
||||
}
|
||||
if code, _ := f.do(t, "GET", path, "", true); code != 404 {
|
||||
t.Fatalf("address survived deletion: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusReportsMessageDifficulty(t *testing.T) {
|
||||
f := newFixture(t, token)
|
||||
_, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||
var st map[string]any
|
||||
_ = json.Unmarshal(body, &st)
|
||||
if st["message_difficulty"] != float64(msgDifficulty) {
|
||||
t.Fatalf("message_difficulty = %v", st["message_difficulty"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// Package inbox is the owner's side of messaging: it collects the encrypted
|
||||
// envelopes the network holds for the owner's listings, decrypts them with the
|
||||
// device key, keeps the conversations, and sends replies and address grants.
|
||||
//
|
||||
// Everything here stays on the owner's node. Relays only ever see ciphertext.
|
||||
package inbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxNewThreads is how many conversations a listing can start per
|
||||
// day before further first messages wait.
|
||||
DefaultMaxNewThreads = 20
|
||||
// DefaultGrantDays is how long an address grant is shown to the buyer.
|
||||
DefaultGrantDays = 7
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoThread means no such conversation exists.
|
||||
ErrNoThread = errors.New("inbox: no such conversation")
|
||||
// ErrNotOwner means the listing belongs to another author.
|
||||
ErrNotOwner = errors.New("inbox: not this node's listing")
|
||||
// ErrInvalid wraps a reply that cannot be sent as given (the caller's
|
||||
// mistake, as opposed to a failure of the node).
|
||||
ErrInvalid = errors.New("inbox: invalid reply")
|
||||
)
|
||||
|
||||
// Publisher sends an envelope into the network (p2p.Node implements it).
|
||||
type Publisher interface {
|
||||
PublishMessage(ctx context.Context, region string, e *message.Envelope) error
|
||||
}
|
||||
|
||||
// Inbox belongs to one device.
|
||||
type Inbox struct {
|
||||
Store *store.Store
|
||||
Device *identity.Device
|
||||
Publisher Publisher
|
||||
|
||||
// Difficulty is the proof-of-work of the replies this node sends.
|
||||
Difficulty int
|
||||
// MaxNewThreads is the per-listing, per-24-hours limit on new
|
||||
// conversations; 0 means DefaultMaxNewThreads.
|
||||
MaxNewThreads int
|
||||
Clock func() time.Time
|
||||
}
|
||||
|
||||
func (i *Inbox) now() time.Time {
|
||||
if i.Clock != nil {
|
||||
return i.Clock()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (i *Inbox) maxNewThreads() int {
|
||||
if i.MaxNewThreads > 0 {
|
||||
return i.MaxNewThreads
|
||||
}
|
||||
return DefaultMaxNewThreads
|
||||
}
|
||||
|
||||
type candidate struct {
|
||||
hash string
|
||||
env *message.Envelope
|
||||
plain *message.Plain
|
||||
work int
|
||||
}
|
||||
|
||||
type threadKey struct {
|
||||
ref message.Ref
|
||||
thread string
|
||||
}
|
||||
|
||||
// Collect reads the envelopes the node holds for the owner's listings,
|
||||
// decrypts the ones it has not seen and files them into conversations. It
|
||||
// returns how many messages were added.
|
||||
//
|
||||
// Two owner-side rules are applied here, because relays cannot see content:
|
||||
// - until the owner has replied, a buyer's message must be short and free of
|
||||
// links; a violating message is kept but hidden;
|
||||
// - at most MaxNewThreads new conversations per listing start every 24
|
||||
// hours. Surplus first messages stay queued, unread, until there is room
|
||||
// (strongest proof-of-work first, then oldest) or they expire.
|
||||
func (i *Inbox) Collect(ctx context.Context) (int, error) {
|
||||
envs, err := i.Store.OwnerMessages(ctx, i.Device.Cert.Author)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
hashes := make([]string, len(envs))
|
||||
for k, e := range envs {
|
||||
if hashes[k], err = e.Hash(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
seen, err := i.Store.SeenEnvelopes(ctx, hashes)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var known []candidate
|
||||
fresh := map[threadKey][]candidate{}
|
||||
for k, e := range envs {
|
||||
h := hashes[k]
|
||||
if seen[h] {
|
||||
continue
|
||||
}
|
||||
p, err := e.OpenAsOwner(i.Device)
|
||||
if err != nil {
|
||||
// Not for this device, damaged, or malformed: never look again.
|
||||
if err := i.Store.MarkSeen(ctx, h, e.ExpiresAt); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
work, _ := e.Work()
|
||||
c := candidate{hash: h, env: e, plain: p, work: work}
|
||||
key := threadKey{e.Listing, p.Thread}
|
||||
exists, err := i.Store.HasThread(ctx, e.Listing, p.Thread)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if exists {
|
||||
known = append(known, c)
|
||||
} else {
|
||||
fresh[key] = append(fresh[key], c)
|
||||
}
|
||||
}
|
||||
|
||||
added := 0
|
||||
admit := func(cs []candidate) error {
|
||||
sort.Slice(cs, func(a, b int) bool {
|
||||
if cs[a].plain.SentAt != cs[b].plain.SentAt {
|
||||
return cs[a].plain.SentAt < cs[b].plain.SentAt
|
||||
}
|
||||
return cs[a].plain.N < cs[b].plain.N
|
||||
})
|
||||
for _, c := range cs {
|
||||
if err := i.file(ctx, c); err != nil {
|
||||
return err
|
||||
}
|
||||
added++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := admit(known); err != nil {
|
||||
return added, err
|
||||
}
|
||||
|
||||
// New conversations, strongest first, within each listing's daily budget.
|
||||
byListing := map[message.Ref][]threadKey{}
|
||||
for key := range fresh {
|
||||
byListing[key.ref] = append(byListing[key.ref], key)
|
||||
}
|
||||
since := i.now().Add(-24 * time.Hour).Unix()
|
||||
for ref, keys := range byListing {
|
||||
used, err := i.Store.NewThreadsSince(ctx, ref, since)
|
||||
if err != nil {
|
||||
return added, err
|
||||
}
|
||||
room := i.maxNewThreads() - used
|
||||
strength := func(k threadKey) (work int, oldest int64) {
|
||||
oldest = 1<<62 - 1
|
||||
for _, c := range fresh[k] {
|
||||
if c.work > work {
|
||||
work = c.work
|
||||
}
|
||||
if c.env.CreatedAt < oldest {
|
||||
oldest = c.env.CreatedAt
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
sort.Slice(keys, func(a, b int) bool {
|
||||
wa, oa := strength(keys[a])
|
||||
wb, ob := strength(keys[b])
|
||||
if wa != wb {
|
||||
return wa > wb
|
||||
}
|
||||
if oa != ob {
|
||||
return oa < ob
|
||||
}
|
||||
return keys[a].thread < keys[b].thread
|
||||
})
|
||||
for k := 0; k < len(keys) && k < room; k++ {
|
||||
if err := admit(fresh[keys[k]]); err != nil {
|
||||
return added, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return added, nil
|
||||
}
|
||||
|
||||
func (i *Inbox) file(ctx context.Context, c candidate) error {
|
||||
replied, err := i.Store.Replied(ctx, c.env.Listing, c.plain.Thread)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
hidden := !replied && c.plain.CheckBuyerFirst() != nil
|
||||
return i.Store.AddInbox(ctx, store.InboxMessage{
|
||||
Hash: c.hash, Listing: c.env.Listing, Thread: c.plain.Thread, Dir: store.InboxIn,
|
||||
Plain: c.plain, Hidden: hidden, ReceivedAt: i.now().Unix(),
|
||||
}, c.env.ExpiresAt)
|
||||
}
|
||||
|
||||
// Reply is what the owner sends back.
|
||||
type Reply struct {
|
||||
Type string // message.TypeText or message.TypeGrant
|
||||
|
||||
Text string // text
|
||||
|
||||
// Grant fields. Address, Phone and Email default to the values saved for
|
||||
// the listing when left empty.
|
||||
Address, Phone, Email, Note string
|
||||
ValidDays int // 0 means DefaultGrantDays
|
||||
}
|
||||
|
||||
// Send signs a reply, publishes it to the buyer's mailbox and records it in
|
||||
// the conversation.
|
||||
func (i *Inbox) Send(ctx context.Context, ref message.Ref, thread string, r Reply) (*message.Envelope, error) {
|
||||
if ref.Author != i.Device.Cert.Author {
|
||||
return nil, ErrNotOwner
|
||||
}
|
||||
ok, err := i.Store.HasThread(ctx, ref, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrNoThread
|
||||
}
|
||||
region, err := i.Store.Region(ctx, ref.Author, ref.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inbox: the listing is gone, so the reply cannot be routed: %w", err)
|
||||
}
|
||||
n, err := i.Store.NextOut(ctx, ref, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := i.now()
|
||||
p := &message.Plain{Type: r.Type, Thread: thread, N: n, SentAt: now.Unix()}
|
||||
|
||||
switch r.Type {
|
||||
case message.TypeText:
|
||||
p.Text = r.Text
|
||||
case message.TypeGrant:
|
||||
p.Address, p.Phone, p.Email, p.Note = r.Address, r.Phone, r.Email, r.Note
|
||||
if p.Address == "" {
|
||||
saved, err := i.Store.GetAddress(ctx, ref)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, fmt.Errorf("%w: no address given and none saved for this listing", ErrInvalid)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Address = saved.Address
|
||||
if p.Phone == "" {
|
||||
p.Phone = saved.Phone
|
||||
}
|
||||
if p.Email == "" {
|
||||
p.Email = saved.Email
|
||||
}
|
||||
}
|
||||
days := r.ValidDays
|
||||
if days == 0 {
|
||||
days = DefaultGrantDays
|
||||
}
|
||||
if days < 0 || time.Duration(days)*24*time.Hour > message.MaxGrantValidity {
|
||||
return nil, fmt.Errorf("%w: valid_days must be between 1 and 30", ErrInvalid)
|
||||
}
|
||||
p.ValidUntil = now.Add(time.Duration(days) * 24 * time.Hour).Unix()
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: unknown reply type %q", ErrInvalid, r.Type)
|
||||
}
|
||||
|
||||
env, err := message.SealToBuyer(i.Device, ref, p, now, i.Difficulty)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrInvalid, err)
|
||||
}
|
||||
if err := i.Publisher.PublishMessage(ctx, region, env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h, err := env.Hash()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = i.Store.AddInbox(ctx, store.InboxMessage{
|
||||
Hash: h, Listing: ref, Thread: thread, Dir: store.InboxOut, Plain: p, ReceivedAt: now.Unix(),
|
||||
}, env.ExpiresAt)
|
||||
return env, err
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package inbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
listingDifficulty = 6
|
||||
msgDifficulty = 4
|
||||
region = "u1x"
|
||||
)
|
||||
|
||||
var (
|
||||
ctx = context.Background()
|
||||
t0 = time.Unix(1_800_000_000, 0)
|
||||
)
|
||||
|
||||
// relay stands in for the network: it stores what the owner publishes, like
|
||||
// a gateway would.
|
||||
type relay struct {
|
||||
st *store.Store
|
||||
sent []*message.Envelope
|
||||
fail error
|
||||
}
|
||||
|
||||
func (r *relay) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
if r.fail != nil {
|
||||
return r.fail
|
||||
}
|
||||
if _, err := r.st.PutMessage(ctx, region, e); err != nil {
|
||||
return err
|
||||
}
|
||||
r.sent = append(r.sent, e)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fixture struct {
|
||||
t *testing.T
|
||||
now time.Time
|
||||
st *store.Store
|
||||
dev *identity.Device
|
||||
relay *relay
|
||||
in *Inbox
|
||||
}
|
||||
|
||||
func newFixture(t *testing.T, maxNew int) *fixture {
|
||||
t.Helper()
|
||||
f := &fixture{t: t, now: t0}
|
||||
root, _, _ := identity.NewRoot()
|
||||
dev, err := identity.Enroll(root, t0.Add(-time.Hour), 90*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.dev = dev
|
||||
f.st, err = store.Open(":memory:", store.Options{
|
||||
Difficulty: listingDifficulty, MessageDifficulty: msgDifficulty,
|
||||
Clock: func() time.Time { return f.now },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { f.st.Close() })
|
||||
f.relay = &relay{st: f.st}
|
||||
f.in = &Inbox{Store: f.st, Device: dev, Publisher: f.relay, Difficulty: msgDifficulty,
|
||||
MaxNewThreads: maxNew, Clock: func() time.Time { return f.now }}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fixture) listing() *listing.Listing {
|
||||
f.t.Helper()
|
||||
id, _ := listing.NewID()
|
||||
l := &listing.Listing{
|
||||
Version: listing.Version, ID: id, Seq: 1, CreatedAt: f.now.Unix(),
|
||||
ExpiresAt: f.now.Add(7 * 24 * time.Hour).Unix(), Kind: "rent", Category: "apartment",
|
||||
Geohash: "u1xjhx", Price: &listing.Price{AmountCents: 100000, Currency: "EUR", Period: "month"},
|
||||
Title: "Wohnung",
|
||||
}
|
||||
if err := l.Seal(f.dev, listingDifficulty); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
if _, err := f.st.Put(ctx, l); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// buyer sends a message with exactly `work` bits of proof-of-work.
|
||||
func (f *fixture) buyer(l *listing.Listing, tk *message.ThreadKey, n int64, text string, work int) {
|
||||
f.t.Helper()
|
||||
for {
|
||||
p := &message.Plain{Type: message.TypeText, N: n, SentAt: f.now.Unix() + n, Text: text}
|
||||
e, err := message.SealToOwner(l, tk, p, f.now, work)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w != work {
|
||||
continue
|
||||
}
|
||||
if _, err := f.st.PutMessage(ctx, region, e); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fixture) newThread() *message.ThreadKey {
|
||||
f.t.Helper()
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return tk
|
||||
}
|
||||
|
||||
func (f *fixture) collect() int {
|
||||
f.t.Helper()
|
||||
n, err := f.in.Collect(ctx)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestCollectFilesConversationsOnce(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l, l2 := f.listing(), f.listing()
|
||||
a, b := f.newThread(), f.newThread()
|
||||
f.buyer(l, a, 1, "Ist die Wohnung noch frei?", msgDifficulty)
|
||||
f.buyer(l, a, 2, "Ich könnte morgen vorbeikommen.", msgDifficulty)
|
||||
f.buyer(l2, b, 1, "Guten Tag", msgDifficulty)
|
||||
|
||||
if n := f.collect(); n != 3 {
|
||||
t.Fatalf("collected %d, want 3", n)
|
||||
}
|
||||
if n := f.collect(); n != 0 {
|
||||
t.Fatalf("a second collection added %d", n)
|
||||
}
|
||||
threads, err := f.st.Threads(ctx, l.Author)
|
||||
if err != nil || len(threads) != 2 {
|
||||
t.Fatalf("threads = %d, %v", len(threads), err)
|
||||
}
|
||||
msgs, _ := f.st.ThreadMessages(ctx, message.Ref{Author: l.Author, ID: l.ID}, a.PublicHex())
|
||||
if len(msgs) != 2 || msgs[0].Plain.Text != "Ist die Wohnung noch frei?" || msgs[1].Plain.N != 2 {
|
||||
t.Fatalf("conversation is wrong: %+v", msgs)
|
||||
}
|
||||
for _, m := range msgs {
|
||||
if m.Dir != store.InboxIn || m.Hidden {
|
||||
t.Fatalf("unexpected %+v", m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinksInFirstMessagesAreHiddenUntilTheOwnerReplies(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
|
||||
f.buyer(l, tk, 1, "Schaut euch https://example.com/kaution an", msgDifficulty)
|
||||
f.buyer(l, tk, 2, strings.Repeat("x", message.MaxFirstText+1), msgDifficulty)
|
||||
f.collect()
|
||||
msgs, _ := f.st.ThreadMessages(ctx, ref, tk.PublicHex())
|
||||
if len(msgs) != 2 || !msgs[0].Hidden || !msgs[1].Hidden {
|
||||
t.Fatalf("violating first messages must be hidden: %+v", msgs)
|
||||
}
|
||||
|
||||
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{Type: message.TypeText, Text: "Hallo!"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.buyer(l, tk, 3, "Hier ist mein Profil: https://example.com/me", msgDifficulty)
|
||||
f.collect()
|
||||
msgs, _ = f.st.ThreadMessages(ctx, ref, tk.PublicHex())
|
||||
for _, m := range msgs {
|
||||
if m.Dir != store.InboxIn {
|
||||
continue
|
||||
}
|
||||
wantHidden := m.Plain.N < 3 // the first two broke the rules before any reply
|
||||
if m.Hidden != wantHidden {
|
||||
t.Errorf("message %d: hidden = %v, want %v", m.Plain.N, m.Hidden, wantHidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewConversationsAreLimitedPerDay(t *testing.T) {
|
||||
f := newFixture(t, 2)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
|
||||
weakest := f.newThread()
|
||||
f.buyer(l, weakest, 1, "schwach", 4)
|
||||
strong := f.newThread()
|
||||
f.buyer(l, strong, 1, "stark", 10)
|
||||
mid := f.newThread()
|
||||
f.buyer(l, mid, 1, "mittel", 7)
|
||||
mid2 := f.newThread()
|
||||
f.buyer(l, mid2, 1, "mittel2", 7)
|
||||
|
||||
f.collect()
|
||||
has := func(tk *message.ThreadKey) bool {
|
||||
ok, _ := f.st.HasThread(ctx, ref, tk.PublicHex())
|
||||
return ok
|
||||
}
|
||||
if !has(strong) || !(has(mid) != has(mid2)) || has(weakest) {
|
||||
t.Fatalf("room for 2 goes to the strongest: strong=%v mid=%v mid2=%v weakest=%v",
|
||||
has(strong), has(mid), has(mid2), has(weakest))
|
||||
}
|
||||
|
||||
// Follow-ups to an existing conversation are never held back.
|
||||
f.buyer(l, strong, 2, "noch eine Frage", 4)
|
||||
if n := f.collect(); n != 1 {
|
||||
t.Fatalf("follow-up not filed (%d)", n)
|
||||
}
|
||||
// The waiting ones stay queued and are not marked as seen...
|
||||
if has(weakest) {
|
||||
t.Fatal("limit exceeded")
|
||||
}
|
||||
// ...so they get in once a day has passed and the window has moved on.
|
||||
f.now = f.now.Add(25 * time.Hour)
|
||||
f.collect()
|
||||
if !has(weakest) || !has(mid) || !has(mid2) {
|
||||
t.Fatalf("queued conversations should be admitted the next day: weakest=%v mid=%v mid2=%v",
|
||||
has(weakest), has(mid), has(mid2))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepliesReachTheBuyerAndAreSigned(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
|
||||
f.collect()
|
||||
|
||||
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{Type: message.TypeText, Text: "Ja, noch frei."}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.st.SetAddress(ctx, ref, store.Address{Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A grant prefilled from the saved address, with the owner's own words.
|
||||
if _, err := f.in.Send(ctx, ref, tk.PublicHex(), Reply{
|
||||
Type: message.TypeGrant, Note: "Samstag 10 Uhr, bitte zweimal klingeln", ValidDays: 3,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mb, _ := tk.Mailbox()
|
||||
box, err := f.st.Mailbox(ctx, mb, 0, 10)
|
||||
if err != nil || len(box) != 2 {
|
||||
t.Fatalf("mailbox = %d, %v", len(box), err)
|
||||
}
|
||||
var text, grant *message.Plain
|
||||
for _, e := range box {
|
||||
p, err := e.OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatalf("buyer cannot open a reply: %v", err)
|
||||
}
|
||||
if p.Type == message.TypeGrant {
|
||||
grant = p
|
||||
} else {
|
||||
text = p
|
||||
}
|
||||
}
|
||||
if text == nil || text.Text != "Ja, noch frei." || text.N != 1 {
|
||||
t.Fatalf("text reply: %+v", text)
|
||||
}
|
||||
if grant == nil || grant.Address != "Musterstraße 12, 20255 Hamburg" || grant.Phone != "+49 40 1" ||
|
||||
grant.Note != "Samstag 10 Uhr, bitte zweimal klingeln" || grant.N != 2 ||
|
||||
grant.ValidUntil != f.now.Add(3*24*time.Hour).Unix() {
|
||||
t.Fatalf("grant: %+v", grant)
|
||||
}
|
||||
|
||||
// The conversation keeps both our replies, in order.
|
||||
msgs, _ := f.st.ThreadMessages(ctx, ref, tk.PublicHex())
|
||||
var outs int
|
||||
for _, m := range msgs {
|
||||
if m.Dir == store.InboxOut {
|
||||
outs++
|
||||
}
|
||||
}
|
||||
if outs != 2 {
|
||||
t.Fatalf("recorded %d outgoing messages, want 2", outs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendRefusals(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
|
||||
f.collect()
|
||||
th := tk.PublicHex()
|
||||
|
||||
if _, err := f.in.Send(ctx, ref, strings.Repeat("ab", 32), Reply{Type: message.TypeText, Text: "x"}); !errors.Is(err, ErrNoThread) {
|
||||
t.Errorf("unknown thread: %v", err)
|
||||
}
|
||||
if _, err := f.in.Send(ctx, message.Ref{Author: strings.Repeat("cd", 32), ID: l.ID}, th, Reply{Type: message.TypeText, Text: "x"}); !errors.Is(err, ErrNotOwner) {
|
||||
t.Errorf("foreign listing: %v", err)
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeGrant}); err == nil || !strings.Contains(err.Error(), "no address") {
|
||||
t.Errorf("grant without any address: %v", err)
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeGrant, Address: "Weg 1", ValidDays: 31}); err == nil {
|
||||
t.Error("a grant valid for 31 days was accepted")
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: "image"}); err == nil {
|
||||
t.Error("unknown reply type accepted")
|
||||
}
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeText, Text: ""}); err == nil {
|
||||
t.Error("empty reply accepted")
|
||||
}
|
||||
|
||||
// A failed publish leaves nothing behind.
|
||||
f.relay.fail = errors.New("network down")
|
||||
if _, err := f.in.Send(ctx, ref, th, Reply{Type: message.TypeText, Text: "x"}); err == nil {
|
||||
t.Error("publish failure was swallowed")
|
||||
}
|
||||
msgs, _ := f.st.ThreadMessages(ctx, ref, th)
|
||||
if len(msgs) != 1 {
|
||||
t.Fatalf("a failed send was recorded: %d messages", len(msgs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddressesAndThreadsCanBeErased(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
tk := f.newThread()
|
||||
f.buyer(l, tk, 1, "Hallo", msgDifficulty)
|
||||
f.collect()
|
||||
|
||||
if _, err := f.st.GetAddress(ctx, ref); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("address before saving: %v", err)
|
||||
}
|
||||
f.st.SetAddress(ctx, ref, store.Address{Address: "A"})
|
||||
f.st.SetAddress(ctx, ref, store.Address{Address: "B", Email: "x@example.com"})
|
||||
if a, _ := f.st.GetAddress(ctx, ref); a.Address != "B" || a.Email != "x@example.com" {
|
||||
t.Fatalf("address was not replaced: %+v", a)
|
||||
}
|
||||
f.st.DeleteAddress(ctx, ref)
|
||||
if _, err := f.st.GetAddress(ctx, ref); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatal("address survived deletion")
|
||||
}
|
||||
|
||||
if ok, _ := f.st.DeleteThread(ctx, ref, tk.PublicHex()); !ok {
|
||||
t.Fatal("thread not deleted")
|
||||
}
|
||||
if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 {
|
||||
t.Fatal("thread survived deletion")
|
||||
}
|
||||
// The envelope was marked seen, so deleting a thread does not resurrect it.
|
||||
if n := f.collect(); n != 0 {
|
||||
t.Fatalf("an erased conversation came back (%d)", n)
|
||||
}
|
||||
}
|
||||
@@ -368,6 +368,13 @@ func validPeerID(s string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// ValidText applies the text rules shared by listings and messages: valid
|
||||
// UTF-8, a length of min to max characters and no control characters
|
||||
// (newlines only if allowNewlines).
|
||||
func ValidText(s string, min, max int, allowNewlines bool) error {
|
||||
return validText(s, min, max, allowNewlines)
|
||||
}
|
||||
|
||||
func validText(s string, min, max int, allowNewlines bool) error {
|
||||
if !utf8.ValidString(s) {
|
||||
return errors.New("invalid UTF-8")
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdh"
|
||||
"crypto/ed25519"
|
||||
"crypto/hkdf"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"filippo.io/edwards25519"
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
const sealInfo = "allmende-seal-v1"
|
||||
|
||||
var x25519 = ecdh.X25519()
|
||||
|
||||
// entropy is where ephemeral keys come from. Tests replace it to produce the
|
||||
// deterministic golden fixture the browser implementation is checked against.
|
||||
var entropy io.Reader = rand.Reader
|
||||
|
||||
// paddingBuckets are the sizes plaintexts are padded to, so the ciphertext
|
||||
// length reveals little about a message.
|
||||
var paddingBuckets = []int{512, 1024, 2048, 4096}
|
||||
|
||||
// MaxPlain is the largest plaintext before padding. One byte is reserved for
|
||||
// the padding marker so the largest padded plaintext is 4096 bytes.
|
||||
const MaxPlain = 4095
|
||||
|
||||
// ed25519PublicToX25519 converts a device's signing key to the X25519 key
|
||||
// used to seal messages to it (the birational map libsodium uses for
|
||||
// crypto_sign_ed25519_pk_to_curve25519).
|
||||
func ed25519PublicToX25519(pub ed25519.PublicKey) (*ecdh.PublicKey, error) {
|
||||
p, err := new(edwards25519.Point).SetBytes(pub)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("message: bad device key: %w", err)
|
||||
}
|
||||
return x25519.NewPublicKey(p.BytesMontgomery())
|
||||
}
|
||||
|
||||
// ed25519SecretToX25519 derives the X25519 secret matching
|
||||
// ed25519PublicToX25519 of the corresponding public key.
|
||||
func ed25519SecretToX25519(priv ed25519.PrivateKey) (*ecdh.PrivateKey, error) {
|
||||
h := sha512.Sum512(priv.Seed())
|
||||
return x25519.NewPrivateKey(h[:32])
|
||||
}
|
||||
|
||||
func newEphemeral() (*ecdh.PrivateKey, error) {
|
||||
var b [32]byte
|
||||
if _, err := io.ReadFull(entropy, b[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x25519.NewPrivateKey(b[:])
|
||||
}
|
||||
|
||||
func sealKey(shared, epk, rpk []byte) ([]byte, error) {
|
||||
salt := append(append([]byte{}, epk...), rpk...)
|
||||
return hkdf.Key(sha256.New, shared, salt, sealInfo, 32)
|
||||
}
|
||||
|
||||
// seal encrypts padded plaintext to rpk. aadFor receives the hex of the fresh
|
||||
// ephemeral public key and returns the header bytes that are authenticated.
|
||||
func seal(rpk *ecdh.PublicKey, aadFor func(epk string) ([]byte, error), plain []byte) (epk string, ct []byte, err error) {
|
||||
esk, err := newEphemeral()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
shared, err := esk.ECDH(rpk) // rejects the all-zero result of low-order points
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
epkBytes := esk.PublicKey().Bytes()
|
||||
key, err := sealKey(shared, epkBytes, rpk.Bytes())
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
epk = hex.EncodeToString(epkBytes)
|
||||
aad, err := aadFor(epk)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
padded, err := pad(plain)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
aead, err := chacha20poly1305.New(key)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
// A zero nonce is safe: the key is unique to this envelope (fresh esk).
|
||||
return epk, aead.Seal(nil, make([]byte, aead.NonceSize()), padded, aad), nil
|
||||
}
|
||||
|
||||
// open decrypts ct with the recipient's secret key.
|
||||
func open(sk *ecdh.PrivateKey, epkHex string, aad, ct []byte) ([]byte, error) {
|
||||
epkBytes, err := hex.DecodeString(epkHex)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
epk, err := x25519.NewPublicKey(epkBytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
shared, err := sk.ECDH(epk)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ephemeral key")
|
||||
}
|
||||
key, err := sealKey(shared, epkBytes, sk.PublicKey().Bytes())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := chacha20poly1305.New(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
padded, err := aead.Open(nil, make([]byte, aead.NonceSize()), ct, aad)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: cannot decrypt")
|
||||
}
|
||||
return unpad(padded)
|
||||
}
|
||||
|
||||
// pad appends 0x80 and zeros up to the next bucket size.
|
||||
func pad(b []byte) ([]byte, error) {
|
||||
if len(b) > MaxPlain {
|
||||
return nil, fmt.Errorf("message: plaintext of %d bytes exceeds %d", len(b), MaxPlain)
|
||||
}
|
||||
size := paddingBuckets[len(paddingBuckets)-1]
|
||||
for _, s := range paddingBuckets {
|
||||
if len(b)+1 <= s {
|
||||
size = s
|
||||
break
|
||||
}
|
||||
}
|
||||
out := make([]byte, size)
|
||||
copy(out, b)
|
||||
out[len(b)] = 0x80
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func unpad(b []byte) ([]byte, error) {
|
||||
b = bytes.TrimRight(b, "\x00")
|
||||
if len(b) == 0 || b[len(b)-1] != 0x80 {
|
||||
return nil, errors.New("message: bad padding")
|
||||
}
|
||||
return b[:len(b)-1], nil
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
// Package message implements the end-to-end encrypted messages between a
|
||||
// buyer and a listing's owner (see "Messaging" in docs/PROTOCOL.md).
|
||||
//
|
||||
// What travels through the network is an Envelope: encrypted, anonymous and
|
||||
// stamped with proof-of-work. Relays can check the stamp, the size and the
|
||||
// listing it refers to, but not the content.
|
||||
package message
|
||||
|
||||
import (
|
||||
"crypto/ecdh"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/pow"
|
||||
)
|
||||
|
||||
const (
|
||||
Version = 1
|
||||
// MaxLifetime is how long a relay keeps an envelope.
|
||||
MaxLifetime = 14 * 24 * time.Hour
|
||||
// MaxSize is the largest canonical envelope.
|
||||
MaxSize = 10 << 10
|
||||
// DefaultDifficulty is lower than for listings: a message should cost a
|
||||
// buyer a moment, not a bot's budget.
|
||||
DefaultDifficulty = 14
|
||||
|
||||
// Directions: who an envelope is for.
|
||||
ToOwner = "owner"
|
||||
ToBuyer = "buyer"
|
||||
|
||||
mailboxContext = "allmende-mailbox-v1\n"
|
||||
maxSafeInt = 1<<53 - 1
|
||||
tagSize = 16 // Poly1305
|
||||
)
|
||||
|
||||
// Ref names the listing a thread is about.
|
||||
type Ref struct {
|
||||
Author string `json:"author"` // identity public key, hex
|
||||
ID string `json:"id"` // listing id, hex
|
||||
}
|
||||
|
||||
// Envelope is the gossiped record.
|
||||
type Envelope struct {
|
||||
Version int `json:"v"`
|
||||
Listing Ref `json:"listing"`
|
||||
To string `json:"to"`
|
||||
Rcpt string `json:"rcpt"` // owner: device key (64 hex); buyer: mailbox tag (32 hex)
|
||||
EPK string `json:"epk"` // sender's ephemeral X25519 key, hex
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
CT string `json:"ct"` // hex
|
||||
PoW uint64 `json:"pow"`
|
||||
}
|
||||
|
||||
// header is the authenticated, unencrypted part: the envelope without the
|
||||
// ciphertext and the proof-of-work nonce.
|
||||
type header struct {
|
||||
Version int `json:"v"`
|
||||
Listing Ref `json:"listing"`
|
||||
To string `json:"to"`
|
||||
Rcpt string `json:"rcpt"`
|
||||
EPK string `json:"epk"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
|
||||
func (e *Envelope) header() header {
|
||||
return header{e.Version, e.Listing, e.To, e.Rcpt, e.EPK, e.CreatedAt, e.ExpiresAt}
|
||||
}
|
||||
|
||||
func (e *Envelope) headerBytes() ([]byte, error) {
|
||||
return jcs.Marshal(e.header())
|
||||
}
|
||||
|
||||
// Bytes is the canonical encoding that is gossiped.
|
||||
func (e *Envelope) Bytes() ([]byte, error) { return jcs.Marshal(e) }
|
||||
|
||||
// Hash identifies the envelope (hex sha256 of its canonical bytes).
|
||||
func (e *Envelope) Hash() (string, error) {
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
func (e *Envelope) powOK(difficulty int) (bool, error) {
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return pow.LeadingZeroBits(b) >= difficulty, nil
|
||||
}
|
||||
|
||||
// Work returns the leading zero bits of the envelope's hash: the proof of
|
||||
// work it carries, used to decide what to evict from a full queue.
|
||||
func (e *Envelope) Work() (int, error) {
|
||||
b, err := e.Bytes()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return pow.LeadingZeroBits(b), nil
|
||||
}
|
||||
|
||||
func (e *Envelope) mine(difficulty int) error {
|
||||
for e.PoW = 0; ; e.PoW++ {
|
||||
if e.PoW > maxSafeInt {
|
||||
return errors.New("message: proof-of-work exhausted")
|
||||
}
|
||||
ok, err := e.powOK(difficulty)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check validates a received envelope as a relay can: structure, size,
|
||||
// lifetime, proof-of-work. It cannot look inside.
|
||||
func (e *Envelope) Check(now time.Time, difficulty int) error {
|
||||
if e.Version != Version {
|
||||
return fmt.Errorf("message: unsupported version %d", e.Version)
|
||||
}
|
||||
if !isHex(e.Listing.Author, 64) || !isHex(e.Listing.ID, 32) {
|
||||
return errors.New("message: malformed listing reference")
|
||||
}
|
||||
switch e.To {
|
||||
case ToOwner:
|
||||
if !isHex(e.Rcpt, 64) {
|
||||
return errors.New("message: owner recipient must be 64 hex characters")
|
||||
}
|
||||
case ToBuyer:
|
||||
if !isHex(e.Rcpt, 32) {
|
||||
return errors.New("message: mailbox tag must be 32 hex characters")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("message: invalid direction %q", e.To)
|
||||
}
|
||||
if !isHex(e.EPK, 64) {
|
||||
return errors.New("message: malformed ephemeral key")
|
||||
}
|
||||
ct, err := hex.DecodeString(e.CT)
|
||||
if err != nil || hex.EncodeToString(ct) != e.CT {
|
||||
return errors.New("message: ciphertext must be lowercase hex")
|
||||
}
|
||||
if len(ct) < tagSize+1 || len(ct) > paddingBuckets[len(paddingBuckets)-1]+tagSize {
|
||||
return errors.New("message: ciphertext size out of range")
|
||||
}
|
||||
if e.CreatedAt <= 0 || e.CreatedAt > maxSafeInt || e.ExpiresAt > maxSafeInt || e.PoW > maxSafeInt {
|
||||
return errors.New("message: number out of range")
|
||||
}
|
||||
if e.ExpiresAt <= e.CreatedAt {
|
||||
return errors.New("message: expires_at must be after created_at")
|
||||
}
|
||||
if time.Duration(e.ExpiresAt-e.CreatedAt)*time.Second > MaxLifetime {
|
||||
return errors.New("message: lifetime exceeds 14 days")
|
||||
}
|
||||
if time.Unix(e.CreatedAt, 0).After(now.Add(listing.MaxClockSkew)) {
|
||||
return fmt.Errorf("message: created_at is in the future: %w", listing.ErrTimeWindow)
|
||||
}
|
||||
if !time.Unix(e.ExpiresAt, 0).After(now) {
|
||||
return fmt.Errorf("message: expired: %w", listing.ErrTimeWindow)
|
||||
}
|
||||
full, err := e.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(full) > MaxSize {
|
||||
return fmt.Errorf("message: %d bytes exceeds limit of %d", len(full), MaxSize)
|
||||
}
|
||||
ok, err := e.powOK(difficulty)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("message: insufficient proof-of-work")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// build seals plain to rpk and mines the proof-of-work.
|
||||
func build(ref Ref, to, rcpt string, rpk *ecdh.PublicKey, plain *Plain, now time.Time, difficulty int) (*Envelope, error) {
|
||||
body, err := jcs.Marshal(plain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e := &Envelope{
|
||||
Version: Version,
|
||||
Listing: ref,
|
||||
To: to,
|
||||
Rcpt: rcpt,
|
||||
CreatedAt: now.Unix(),
|
||||
ExpiresAt: now.Add(MaxLifetime).Unix(),
|
||||
}
|
||||
epk, ct, err := seal(rpk, func(epk string) ([]byte, error) {
|
||||
e.EPK = epk
|
||||
return e.headerBytes()
|
||||
}, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.EPK = epk
|
||||
e.CT = hex.EncodeToString(ct)
|
||||
if err := e.mine(difficulty); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// SealToOwner seals a buyer's message to the listing's current device key.
|
||||
func SealToOwner(l *listing.Listing, thread *ThreadKey, p *Plain, now time.Time, difficulty int) (*Envelope, error) {
|
||||
if l.Tombstone {
|
||||
return nil, errors.New("message: listing is deleted")
|
||||
}
|
||||
devPub, err := hex.DecodeString(l.Device)
|
||||
if err != nil || len(devPub) != 32 {
|
||||
return nil, errors.New("message: bad device key")
|
||||
}
|
||||
rpk, err := ed25519PublicToX25519(devPub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Thread = thread.PublicHex()
|
||||
if err := p.validate(ToOwner); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return build(Ref{Author: l.Author, ID: l.ID}, ToOwner, l.Device, rpk, p, now, difficulty)
|
||||
}
|
||||
|
||||
// SealToBuyer signs the owner's reply with the device key and seals it to the
|
||||
// buyer's thread key; it is addressed to the thread's mailbox.
|
||||
func SealToBuyer(dev *identity.Device, ref Ref, p *Plain, now time.Time, difficulty int) (*Envelope, error) {
|
||||
if ref.Author != dev.Cert.Author {
|
||||
return nil, errors.New("message: device does not belong to the listing's author")
|
||||
}
|
||||
p.signOwner(dev, ref)
|
||||
if err := p.validate(ToBuyer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pub, err := hex.DecodeString(p.Thread)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad thread key")
|
||||
}
|
||||
rpk, err := x25519.NewPublicKey(pub)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad thread key")
|
||||
}
|
||||
mailbox, err := Mailbox(p.Thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return build(ref, ToBuyer, mailbox, rpk, p, now, difficulty)
|
||||
}
|
||||
|
||||
// OpenAsOwner decrypts an envelope addressed to dev and checks the plaintext.
|
||||
func (e *Envelope) OpenAsOwner(dev *identity.Device) (*Plain, error) {
|
||||
if e.To != ToOwner || e.Rcpt != dev.Cert.Device {
|
||||
return nil, errors.New("message: not addressed to this device")
|
||||
}
|
||||
sk, err := ed25519SecretToX25519(dev.Key.PrivateKey())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p, err := e.decrypt(sk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.validate(ToOwner); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// OpenAsBuyer decrypts a reply with the thread key and verifies that it was
|
||||
// signed by a device certified by the listing's author.
|
||||
func (e *Envelope) OpenAsBuyer(t *ThreadKey) (*Plain, error) {
|
||||
mailbox, err := t.Mailbox()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if e.To != ToBuyer || e.Rcpt != mailbox {
|
||||
return nil, errors.New("message: not addressed to this thread")
|
||||
}
|
||||
p, err := e.decrypt(t.k)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := p.validate(ToBuyer); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Thread != t.PublicHex() {
|
||||
return nil, errors.New("message: reply belongs to another thread")
|
||||
}
|
||||
if *p.Listing != e.Listing {
|
||||
return nil, errors.New("message: reply refers to another listing")
|
||||
}
|
||||
if err := p.verifyOwner(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// decrypt opens the envelope and decodes the plaintext strictly: it must be
|
||||
// the canonical encoding of a Plain, so nothing unknown hides in it.
|
||||
func (e *Envelope) decrypt(sk *ecdh.PrivateKey) (*Plain, error) {
|
||||
aad, err := e.headerBytes()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ct, err := hex.DecodeString(e.CT)
|
||||
if err != nil {
|
||||
return nil, errors.New("message: bad ciphertext")
|
||||
}
|
||||
body, err := open(sk, e.EPK, aad, ct)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodePlain(body)
|
||||
}
|
||||
|
||||
// ThreadKey is a buyer's per-thread X25519 key pair.
|
||||
type ThreadKey struct{ k *ecdh.PrivateKey }
|
||||
|
||||
// NewThreadKey creates a fresh thread key.
|
||||
func NewThreadKey() (*ThreadKey, error) {
|
||||
k, err := x25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ThreadKey{k}, nil
|
||||
}
|
||||
|
||||
// ThreadKeyFromBytes restores a thread key from its 32 secret bytes.
|
||||
func ThreadKeyFromBytes(b []byte) (*ThreadKey, error) {
|
||||
k, err := x25519.NewPrivateKey(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ThreadKey{k}, nil
|
||||
}
|
||||
|
||||
// Bytes returns the secret key.
|
||||
func (t *ThreadKey) Bytes() []byte { return t.k.Bytes() }
|
||||
|
||||
// PublicHex is the thread's public key, which identifies the thread.
|
||||
func (t *ThreadKey) PublicHex() string { return hex.EncodeToString(t.k.PublicKey().Bytes()) }
|
||||
|
||||
// Mailbox is the tag replies for this thread are addressed to.
|
||||
func (t *ThreadKey) Mailbox() (string, error) { return Mailbox(t.PublicHex()) }
|
||||
|
||||
// Mailbox derives the mailbox tag from a thread public key (hex): the first
|
||||
// 16 bytes of sha256("allmende-mailbox-v1\n" || key), so the key itself never
|
||||
// appears on the network.
|
||||
func Mailbox(threadPubHex string) (string, error) {
|
||||
pub, err := hex.DecodeString(threadPubHex)
|
||||
if err != nil || len(pub) != 32 {
|
||||
return "", errors.New("message: bad thread key")
|
||||
}
|
||||
sum := sha256.Sum256(append([]byte(mailboxContext), pub...))
|
||||
return hex.EncodeToString(sum[:16]), nil
|
||||
}
|
||||
|
||||
func isHex(s string, n int) bool {
|
||||
if len(s) != n {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(s); i++ {
|
||||
c := s[i]
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
// The browser seals buyer messages and opens owner replies. This golden file
|
||||
// is produced by the Go implementation and consumed by the TypeScript tests
|
||||
// (web/test), which must reproduce every byte: same envelope from the same
|
||||
// ephemeral key, same plaintext from the same thread key.
|
||||
//
|
||||
// Refresh it after an intentional format change with:
|
||||
//
|
||||
// UPDATE_FIXTURES=1 go test ./internal/message -run TestGoldenFixture
|
||||
const fixturePath = "testdata/fixture.json"
|
||||
|
||||
const (
|
||||
fixtureNow = 1_800_000_000
|
||||
fixtureDifficulty = 8
|
||||
)
|
||||
|
||||
type fixtureEnvelope struct {
|
||||
EphemeralSecret string `json:"esk"` // hex; the only randomness in the envelope
|
||||
Plain json.RawMessage `json:"plain"` // what was sealed, as plain JSON
|
||||
PlainCanonical string `json:"plain_canonical"`
|
||||
PaddedLen int `json:"padded_len"`
|
||||
Canonical string `json:"canonical"` // the exact envelope bytes
|
||||
Hash string `json:"hash"`
|
||||
Work int `json:"work"`
|
||||
}
|
||||
|
||||
type linkCase struct {
|
||||
Text string `json:"text"`
|
||||
Link bool `json:"link"`
|
||||
}
|
||||
|
||||
type fixtureFile struct {
|
||||
Now int64 `json:"now"`
|
||||
Difficulty int `json:"difficulty"`
|
||||
Listing Ref `json:"listing"`
|
||||
Device string `json:"device"`
|
||||
DeviceSeed string `json:"device_seed"`
|
||||
ThreadSecret string `json:"thread_secret"`
|
||||
ThreadPublic string `json:"thread_public"`
|
||||
Mailbox string `json:"mailbox"`
|
||||
ToOwner fixtureEnvelope `json:"to_owner"`
|
||||
ToBuyer fixtureEnvelope `json:"to_buyer"`
|
||||
Links []linkCase `json:"links"`
|
||||
}
|
||||
|
||||
func withEntropy(t *testing.T, b []byte) {
|
||||
t.Helper()
|
||||
old := entropy
|
||||
entropy = io.Reader(bytes.NewReader(b))
|
||||
t.Cleanup(func() { entropy = old })
|
||||
}
|
||||
|
||||
func buildFixture(t *testing.T) *fixtureFile {
|
||||
t.Helper()
|
||||
root, err := identity.FromPhrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deviceSeed := bytes.Repeat([]byte{7}, 32)
|
||||
devKey, err := identity.FromSeed(deviceSeed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := time.Unix(fixtureNow, 0)
|
||||
cert, err := identity.IssueCert(root, devKey.PublicKeyHex(), at.Add(-time.Hour), at.Add(90*24*time.Hour))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dev := &identity.Device{Key: devKey, Cert: cert}
|
||||
l := &listing.Listing{ID: "00112233445566778899aabbccddeeff", Author: cert.Author, Device: cert.Device}
|
||||
ref := Ref{Author: l.Author, ID: l.ID}
|
||||
|
||||
threadSecret := bytes.Repeat([]byte{0x11}, 32)
|
||||
tk, err := ThreadKeyFromBytes(threadSecret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailbox, _ := tk.Mailbox()
|
||||
f := &fixtureFile{
|
||||
Now: fixtureNow, Difficulty: fixtureDifficulty, Listing: ref, Device: cert.Device,
|
||||
DeviceSeed: hex.EncodeToString(deviceSeed), ThreadSecret: hex.EncodeToString(threadSecret),
|
||||
ThreadPublic: tk.PublicHex(), Mailbox: mailbox,
|
||||
}
|
||||
|
||||
fill := func(e *Envelope, p *Plain, esk []byte) fixtureEnvelope {
|
||||
canon, _ := e.Bytes()
|
||||
hash, _ := e.Hash()
|
||||
work, _ := e.Work()
|
||||
plain, _ := json.Marshal(p)
|
||||
pc, _ := jcs.Marshal(p) // p was filled in by sealing: thread, and the owner's signature
|
||||
padded, _ := pad(pc)
|
||||
return fixtureEnvelope{
|
||||
EphemeralSecret: hex.EncodeToString(esk), Plain: plain, PlainCanonical: string(pc),
|
||||
PaddedLen: len(padded), Canonical: string(canon), Hash: hash, Work: work,
|
||||
}
|
||||
}
|
||||
|
||||
// Awkward text on purpose: umlauts, an emoji, a newline and U+2028.
|
||||
esk1 := bytes.Repeat([]byte{0x22}, 32)
|
||||
withEntropy(t, esk1)
|
||||
hello := &Plain{Type: TypeText, N: 1, SentAt: fixtureNow,
|
||||
Text: "Guten Tag, ist die Wohnung noch frei? Schöne Grüße \U0001F3E0\nZeile 2
Zeile 3"}
|
||||
e1, err := SealToOwner(l, tk, hello, at, fixtureDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.ToOwner = fill(e1, hello, esk1)
|
||||
|
||||
esk2 := bytes.Repeat([]byte{0x33}, 32)
|
||||
withEntropy(t, esk2)
|
||||
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: fixtureNow,
|
||||
Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 123456",
|
||||
Note: "Samstag 10 Uhr, bitte zweimal klingeln \U0001F514", ValidUntil: fixtureNow + 7*24*3600}
|
||||
e2, err := SealToBuyer(dev, ref, grant, at, fixtureDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The grant now carries the owner's certificate and signature.
|
||||
f.ToBuyer = fill(e2, grant, esk2)
|
||||
|
||||
for _, c := range []struct {
|
||||
text string
|
||||
link bool
|
||||
}{
|
||||
{"Guten Tag, ist die Wohnung noch frei?", false},
|
||||
{"Ich komme z. B. am Samstag, ca. 10 Uhr.", false},
|
||||
{"Preis 1.200 Euro, ok? Ja. Gut.", false},
|
||||
{"Hallo, wir sind 2 Personen (u.a. Nichtraucher).", false},
|
||||
{"schaut mal https://example.com/x", true},
|
||||
{"WWW.example", true},
|
||||
{"auf beispiel.de gibt es mehr", true},
|
||||
{"mail an max@example.com", true},
|
||||
{"Hallo.Ich komme morgen", true},
|
||||
{"Beispiel.DE", true},
|
||||
{"auf straße-1.com", true},
|
||||
{"bit.ly/abc", true},
|
||||
} {
|
||||
if got := ContainsLink(c.text); got != c.link {
|
||||
t.Fatalf("ContainsLink(%q) = %v, want %v", c.text, got, c.link)
|
||||
}
|
||||
f.Links = append(f.Links, linkCase{c.text, c.link})
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func TestGoldenFixture(t *testing.T) {
|
||||
f := buildFixture(t)
|
||||
got, err := json.MarshalIndent(f, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, '\n')
|
||||
|
||||
if os.Getenv("UPDATE_FIXTURES") != "" {
|
||||
if err := os.MkdirAll("testdata", 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(fixturePath, got, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
want, err := os.ReadFile(fixturePath)
|
||||
if err != nil {
|
||||
t.Fatalf("%v (create it with UPDATE_FIXTURES=1)", err)
|
||||
}
|
||||
if !bytes.Equal(got, want) {
|
||||
t.Fatal("fixture is out of date: the wire format changed; if intended, refresh with UPDATE_FIXTURES=1 and update the TypeScript side")
|
||||
}
|
||||
|
||||
// The fixture must be self-consistent: both envelopes pass the relay
|
||||
// checks and open with the keys from the file.
|
||||
for name, c := range map[string]fixtureEnvelope{"to_owner": f.ToOwner, "to_buyer": f.ToBuyer} {
|
||||
var e Envelope
|
||||
if err := json.Unmarshal([]byte(c.Canonical), &e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Check(time.Unix(fixtureNow, 0), fixtureDifficulty); err != nil {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,510 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
const testDifficulty = 6
|
||||
|
||||
var now = time.Unix(1_800_000_000, 0)
|
||||
|
||||
type party struct {
|
||||
dev *identity.Device
|
||||
l *listing.Listing
|
||||
ref Ref
|
||||
}
|
||||
|
||||
func newOwner(t *testing.T) *party {
|
||||
t.Helper()
|
||||
root, err := identity.Generate()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dev, err := identity.Enroll(root, now.Add(-time.Hour), 90*24*time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l := &listing.Listing{ID: strings.Repeat("ab", 16), Author: dev.Cert.Author, Device: dev.Cert.Device}
|
||||
return &party{dev: dev, l: l, ref: Ref{Author: l.Author, ID: l.ID}}
|
||||
}
|
||||
|
||||
func hello(text string) *Plain {
|
||||
return &Plain{Type: TypeText, N: 1, SentAt: now.Unix(), Text: text}
|
||||
}
|
||||
|
||||
func thread(t *testing.T) *ThreadKey {
|
||||
t.Helper()
|
||||
k, err := NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
func TestKeyConversionAgrees(t *testing.T) {
|
||||
for i := 0; i < 20; i++ {
|
||||
id, _ := identity.Generate()
|
||||
priv := id.PrivateKey()
|
||||
sk, err := ed25519SecretToX25519(priv)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pk, err := ed25519PublicToX25519(priv.Public().(ed25519.PublicKey))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(sk.PublicKey().Bytes(), pk.Bytes()) {
|
||||
t.Fatal("converted secret and converted public key do not match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuyerToOwnerRoundTrip(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
e, err := SealToOwner(o.l, tk, hello("Ist die Wohnung noch frei? 🏠"), now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Check(now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := e.Bytes()
|
||||
if bytes.Contains(b, []byte("Wohnung")) {
|
||||
t.Fatal("plaintext visible in the envelope")
|
||||
}
|
||||
if strings.Contains(string(b), tk.PublicHex()) {
|
||||
t.Fatal("thread key must not appear in the envelope")
|
||||
}
|
||||
p, err := e.OpenAsOwner(o.dev)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p.Text != "Ist die Wohnung noch frei? 🏠" || p.Thread != tk.PublicHex() || p.N != 1 {
|
||||
t.Fatalf("unexpected plaintext %+v", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnerReplyAndGrantRoundTrip(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
|
||||
reply := &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "Ja, noch frei."}
|
||||
e, err := SealToBuyer(o.dev, o.ref, reply, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := e.Check(now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mb, _ := tk.Mailbox()
|
||||
if e.Rcpt != mb || e.To != ToBuyer {
|
||||
t.Fatal("reply is not addressed to the thread's mailbox")
|
||||
}
|
||||
got, err := e.OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Text != "Ja, noch frei." || got.Device != o.dev.Cert.Device {
|
||||
t.Fatalf("unexpected reply %+v", got)
|
||||
}
|
||||
|
||||
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 2, SentAt: now.Unix(),
|
||||
Address: "Musterstraße 12, 20255 Hamburg", Phone: "+49 40 123456",
|
||||
Note: "Samstag 10 Uhr, bitte zweimal klingeln", ValidUntil: now.Add(7 * 24 * time.Hour).Unix()}
|
||||
e, err = SealToBuyer(o.dev, o.ref, grant, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = e.OpenAsBuyer(tk)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Address != grant.Address || got.Note != grant.Note || got.ValidUntil != grant.ValidUntil {
|
||||
t.Fatalf("grant changed in transit: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTamperingWithTheHeaderBreaksDecryption(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
e, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty)
|
||||
for name, mutate := range map[string]func(*Envelope){
|
||||
"created_at": func(e *Envelope) { e.CreatedAt++ },
|
||||
"expires_at": func(e *Envelope) { e.ExpiresAt-- },
|
||||
"listing id": func(e *Envelope) { e.Listing.ID = strings.Repeat("cd", 16) },
|
||||
"author": func(e *Envelope) { e.Listing.Author = strings.Repeat("ee", 32) },
|
||||
"ciphertext": func(e *Envelope) {
|
||||
flipped := byte('0')
|
||||
if e.CT[0] == '0' {
|
||||
flipped = '1'
|
||||
}
|
||||
e.CT = string(flipped) + e.CT[1:]
|
||||
},
|
||||
} {
|
||||
c := *e
|
||||
mutate(&c)
|
||||
if _, err := c.OpenAsOwner(o.dev); err == nil {
|
||||
t.Errorf("tampering with %s went unnoticed", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyTheRightKeysOpen(t *testing.T) {
|
||||
o, other := newOwner(t), newOwner(t)
|
||||
tk := thread(t)
|
||||
e, _ := SealToOwner(o.l, tk, hello("hallo"), now, testDifficulty)
|
||||
if _, err := e.OpenAsOwner(other.dev); err == nil {
|
||||
t.Fatal("another device opened the message")
|
||||
}
|
||||
// Same recipient field, wrong secret.
|
||||
c := *e
|
||||
c.Rcpt = other.dev.Cert.Device
|
||||
if _, err := c.OpenAsOwner(other.dev); err == nil {
|
||||
t.Fatal("re-addressed envelope decrypted")
|
||||
}
|
||||
|
||||
r, _ := SealToBuyer(o.dev, o.ref, &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "x"}, now, testDifficulty)
|
||||
if _, err := r.OpenAsBuyer(thread(t)); err == nil {
|
||||
t.Fatal("another thread opened the reply")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImpersonationAndReplayAreRejected(t *testing.T) {
|
||||
o, imp := newOwner(t), newOwner(t)
|
||||
tk := thread(t)
|
||||
|
||||
// A different identity signs a reply that claims to come from o's listing.
|
||||
p := &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "Überweisen Sie die Kaution"}
|
||||
if _, err := SealToBuyer(imp.dev, o.ref, p, now, testDifficulty); err == nil {
|
||||
t.Fatal("SealToBuyer must refuse a device of another author")
|
||||
}
|
||||
p.signOwner(imp.dev, o.ref) // forge it by hand
|
||||
pub, _ := hex.DecodeString(p.Thread)
|
||||
rpk, _ := x25519.NewPublicKey(pub)
|
||||
mb, _ := Mailbox(p.Thread)
|
||||
forged, err := build(o.ref, ToBuyer, mb, rpk, p, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := forged.OpenAsBuyer(tk); err == nil || !strings.Contains(err.Error(), "certificate") {
|
||||
t.Fatalf("forged reply accepted or wrong error: %v", err)
|
||||
}
|
||||
|
||||
// A genuine reply for thread A, moved into thread B, fails its signature.
|
||||
a, b := thread(t), thread(t)
|
||||
genuine := &Plain{Type: TypeText, Thread: a.PublicHex(), N: 1, SentAt: now.Unix(), Text: "für A"}
|
||||
if _, err := SealToBuyer(o.dev, o.ref, genuine, now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
moved := *genuine
|
||||
moved.Thread = b.PublicHex()
|
||||
pubB, _ := hex.DecodeString(moved.Thread)
|
||||
rpkB, _ := x25519.NewPublicKey(pubB)
|
||||
mbB, _ := Mailbox(moved.Thread)
|
||||
e, err := build(o.ref, ToBuyer, mbB, rpkB, &moved, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := e.OpenAsBuyer(b); err == nil || !strings.Contains(err.Error(), "signature") {
|
||||
t.Fatalf("replayed reply accepted or wrong error: %v", err)
|
||||
}
|
||||
|
||||
// A reply for another listing of the same envelope header fails too.
|
||||
g, _ := SealToBuyer(o.dev, o.ref, &Plain{Type: TypeText, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(), Text: "x"}, now, testDifficulty)
|
||||
g.Listing.ID = strings.Repeat("cd", 16)
|
||||
if _, err := g.OpenAsBuyer(tk); err == nil {
|
||||
t.Fatal("reply accepted for a different listing id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayChecks(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
good, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty)
|
||||
if err := good.Check(now, testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
remine := func(e *Envelope) *Envelope {
|
||||
if err := e.mine(testDifficulty); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
mutate func(*Envelope)
|
||||
wantErr string
|
||||
window bool
|
||||
}{
|
||||
{"version", func(e *Envelope) { e.Version = 2 }, "version", false},
|
||||
{"direction", func(e *Envelope) { e.To = "everyone" }, "direction", false},
|
||||
{"owner rcpt too short", func(e *Envelope) { e.Rcpt = e.Rcpt[:32] }, "64 hex", false},
|
||||
{"buyer rcpt too long", func(e *Envelope) { e.To = ToBuyer }, "32 hex", false},
|
||||
{"uppercase ct", func(e *Envelope) { e.CT = strings.ToUpper(e.CT) }, "lowercase", false},
|
||||
{"ct too small", func(e *Envelope) { e.CT = "00" }, "size", false},
|
||||
{"lifetime over 14 days", func(e *Envelope) { e.ExpiresAt = e.CreatedAt + 15*24*3600 }, "14 days", false},
|
||||
{"expiry before creation", func(e *Envelope) { e.ExpiresAt = e.CreatedAt }, "after created_at", false},
|
||||
{"expired", func(e *Envelope) { e.CreatedAt -= 20 * 24 * 3600; e.ExpiresAt -= 20 * 24 * 3600 }, "expired", true},
|
||||
{"from the future", func(e *Envelope) { e.CreatedAt += 3600; e.ExpiresAt += 3600 }, "future", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
e := *good
|
||||
c.mutate(&e)
|
||||
remine(&e)
|
||||
err := e.Check(now, testDifficulty)
|
||||
if err == nil || !strings.Contains(err.Error(), c.wantErr) {
|
||||
t.Errorf("%s: err = %v, want %q", c.name, err, c.wantErr)
|
||||
continue
|
||||
}
|
||||
if errors.Is(err, listing.ErrTimeWindow) != c.window {
|
||||
t.Errorf("%s: ErrTimeWindow = %v, want %v", c.name, !c.window, c.window)
|
||||
}
|
||||
}
|
||||
|
||||
// Proof-of-work is checked against the node's difficulty.
|
||||
if err := good.Check(now, 40); err == nil || !strings.Contains(err.Error(), "proof-of-work") {
|
||||
t.Errorf("weak work accepted: %v", err)
|
||||
}
|
||||
// Any change after mining invalidates the work (with overwhelming probability).
|
||||
c := *good
|
||||
c.CreatedAt++
|
||||
if err := c.Check(now, 24); err == nil {
|
||||
t.Error("altered envelope kept its proof-of-work")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeLimits(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
if _, err := SealToOwner(o.l, tk, hello(strings.Repeat("a", MaxText+1)), now, testDifficulty); err == nil {
|
||||
t.Error("oversized text accepted")
|
||||
}
|
||||
e, err := SealToOwner(o.l, tk, hello(strings.Repeat("ä", MaxText/2)), now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatalf("a full-size message failed: %v", err)
|
||||
}
|
||||
b, _ := e.Bytes()
|
||||
if len(b) > MaxSize {
|
||||
t.Fatalf("a full-size envelope is %d bytes, over the %d limit", len(b), MaxSize)
|
||||
}
|
||||
// The largest owner grant, with certificate and signature, still fits.
|
||||
grant := &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(),
|
||||
Address: strings.Repeat("ä", MaxAddress/2), Phone: strings.Repeat("1", MaxPhone),
|
||||
Email: strings.Repeat("e", MaxEmail), Note: strings.Repeat("ä", MaxNote/2),
|
||||
ValidUntil: now.Add(MaxGrantValidity).Unix()}
|
||||
e, err = SealToBuyer(o.dev, o.ref, grant, now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatalf("a maximal grant does not fit: %v", err)
|
||||
}
|
||||
b, _ = e.Bytes()
|
||||
if len(b) > MaxSize {
|
||||
t.Fatalf("a maximal grant envelope is %d bytes, over the %d limit", len(b), MaxSize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaddingHidesLength(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
size := func(text string) int {
|
||||
e, err := SealToOwner(o.l, thread(t), hello(text), now, testDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return len(e.CT)
|
||||
}
|
||||
if a, b := size("hi"), size(strings.Repeat("x", 250)); a != b {
|
||||
t.Errorf("short messages differ in size: %d vs %d", a, b)
|
||||
}
|
||||
if a, b := size("hi"), size(strings.Repeat("x", 900)); a >= b {
|
||||
t.Errorf("a longer message should land in a larger bucket: %d vs %d", a, b)
|
||||
}
|
||||
for _, n := range []int{0, 1, 511, 512, 1023, 2047, 2048, MaxPlain} {
|
||||
got, err := pad(bytes.Repeat([]byte{'a'}, n))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 512 && len(got) != 1024 && len(got) != 2048 && len(got) != 4096 {
|
||||
t.Errorf("pad(%d) = %d bytes, not a bucket", n, len(got))
|
||||
}
|
||||
back, err := unpad(got)
|
||||
if err != nil || len(back) != n {
|
||||
t.Errorf("unpad(pad(%d)) = %d bytes, %v", n, len(back), err)
|
||||
}
|
||||
}
|
||||
if _, err := pad(make([]byte, MaxPlain+1)); err == nil {
|
||||
t.Error("oversized plaintext padded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLowOrderKeysAreRejected(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
e, _ := SealToOwner(o.l, thread(t), hello("hallo"), now, testDifficulty)
|
||||
c := *e
|
||||
c.EPK = strings.Repeat("00", 32) // a point of low order: shared secret would be all zero
|
||||
if _, err := c.OpenAsOwner(o.dev); err == nil {
|
||||
t.Error("low-order ephemeral key accepted")
|
||||
}
|
||||
p := &Plain{Type: TypeText, Thread: strings.Repeat("00", 32), N: 1, SentAt: now.Unix(), Text: "x"}
|
||||
if _, err := SealToBuyer(o.dev, o.ref, p, now, testDifficulty); err == nil {
|
||||
t.Error("sealing to a low-order thread key succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaintextRules(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
own := func(p *Plain) error {
|
||||
_, err := SealToBuyer(o.dev, o.ref, p, now, testDifficulty)
|
||||
return err
|
||||
}
|
||||
buyer := func(p *Plain) error {
|
||||
_, err := SealToOwner(o.l, tk, p, now, testDifficulty)
|
||||
return err
|
||||
}
|
||||
grant := func() *Plain {
|
||||
return &Plain{Type: TypeGrant, Thread: tk.PublicHex(), N: 1, SentAt: now.Unix(),
|
||||
Address: "Weg 1", ValidUntil: now.Add(time.Hour).Unix()}
|
||||
}
|
||||
if err := own(grant()); err != nil {
|
||||
t.Fatalf("valid grant: %v", err)
|
||||
}
|
||||
|
||||
bad := map[string]func() error{
|
||||
"buyers cannot grant": func() error {
|
||||
g := grant()
|
||||
g.Thread = ""
|
||||
return buyer(g)
|
||||
},
|
||||
"grant without address": func() error { g := grant(); g.Address = ""; return own(g) },
|
||||
"grant with text": func() error { g := grant(); g.Text = "hi"; return own(g) },
|
||||
"valid_until in the past": func() error {
|
||||
g := grant()
|
||||
g.ValidUntil = g.SentAt
|
||||
return own(g)
|
||||
},
|
||||
"valid_until too far": func() error {
|
||||
g := grant()
|
||||
g.ValidUntil = g.SentAt + int64(MaxGrantValidity/time.Second) + 1
|
||||
return own(g)
|
||||
},
|
||||
"text with grant fields": func() error {
|
||||
p := hello("hi")
|
||||
p.Address = "Weg 1"
|
||||
return buyer(p)
|
||||
},
|
||||
"empty text": func() error { return buyer(hello("")) },
|
||||
"control character": func() error { return buyer(hello("a\x07b")) },
|
||||
"unknown type": func() error { p := hello("x"); p.Type = "image"; return buyer(p) },
|
||||
"counter from zero": func() error { p := hello("x"); p.N = 0; return buyer(p) },
|
||||
"invalid utf-8": func() error { return buyer(hello("a\xffb")) },
|
||||
}
|
||||
for name, f := range bad {
|
||||
if err := f(); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
}
|
||||
if err := buyer(hello("Zeile 1\nZeile
2")); err != nil {
|
||||
t.Errorf("newlines and U+2028 should be fine: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaintextMustBeCanonical(t *testing.T) {
|
||||
o := newOwner(t)
|
||||
tk := thread(t)
|
||||
// Valid content plus an unknown field, sealed correctly: the owner must refuse it.
|
||||
body := []byte(`{"n":1,"sent_at":1800000000,"t":"text","text":"hi","thread":"` + tk.PublicHex() + `","x":1}`)
|
||||
rpk, _ := ed25519PublicToX25519(ed25519.PublicKey(mustHex(t, o.l.Device)))
|
||||
e := &Envelope{Version: Version, Listing: o.ref, To: ToOwner, Rcpt: o.l.Device,
|
||||
CreatedAt: now.Unix(), ExpiresAt: now.Add(time.Hour).Unix()}
|
||||
epk, ct, err := seal(rpk, func(epk string) ([]byte, error) { e.EPK = epk; return e.headerBytes() }, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.EPK, e.CT = epk, hex.EncodeToString(ct)
|
||||
if _, err := e.OpenAsOwner(o.dev); err == nil || !strings.Contains(err.Error(), "canonical") {
|
||||
t.Fatalf("non-canonical plaintext accepted: %v", err)
|
||||
}
|
||||
if _, err := decodePlain([]byte(`{"t":"text"`)); err == nil {
|
||||
t.Fatal("broken JSON accepted")
|
||||
}
|
||||
b, _ := jcs.Marshal(hello("x"))
|
||||
if _, err := decodePlain(append([]byte(" "), b...)); err == nil {
|
||||
t.Fatal("whitespace-padded JSON accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailboxIsStableAndOpaque(t *testing.T) {
|
||||
k := thread(t)
|
||||
a, _ := k.Mailbox()
|
||||
b, _ := Mailbox(k.PublicHex())
|
||||
if a != b || len(a) != 32 || strings.Contains(a, k.PublicHex()[:8]) {
|
||||
t.Fatalf("mailbox %q", a)
|
||||
}
|
||||
if _, err := Mailbox("zz"); err == nil {
|
||||
t.Fatal("bad key accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestThreadKeyRoundTrip(t *testing.T) {
|
||||
k := thread(t)
|
||||
again, err := ThreadKeyFromBytes(k.Bytes())
|
||||
if err != nil || again.PublicHex() != k.PublicHex() {
|
||||
t.Fatalf("restoring a thread key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFirstMessageRules(t *testing.T) {
|
||||
ok := []string{
|
||||
"Guten Tag, ist die Wohnung noch frei?",
|
||||
"Ich komme z. B. am Samstag, ca. 10 Uhr.",
|
||||
"Preis 1.200 Euro, ok? Ja. Gut.",
|
||||
"Hallo, wir sind 2 Personen (u.a. Nichtraucher).",
|
||||
}
|
||||
links := []string{
|
||||
"schaut mal https://example.com/x",
|
||||
"http://evil",
|
||||
"ftp://x",
|
||||
"WWW.example",
|
||||
"auf beispiel.de gibt es mehr",
|
||||
"mail an max@example.com",
|
||||
"Hallo.Ich komme morgen",
|
||||
"Beispiel.DE",
|
||||
"bit.ly/abc",
|
||||
"auf straße-1.com",
|
||||
}
|
||||
for _, s := range ok {
|
||||
if ContainsLink(s) {
|
||||
t.Errorf("%q wrongly flagged as a link", s)
|
||||
}
|
||||
}
|
||||
for _, s := range links {
|
||||
if !ContainsLink(s) {
|
||||
t.Errorf("%q not flagged as a link", s)
|
||||
}
|
||||
}
|
||||
long := &Plain{Type: TypeText, Text: strings.Repeat("a", MaxFirstText+1)}
|
||||
if long.CheckBuyerFirst() == nil {
|
||||
t.Error("overlong first message accepted")
|
||||
}
|
||||
if (&Plain{Type: TypeText, Text: "gerne!"}).CheckBuyerFirst() != nil {
|
||||
t.Error("harmless first message rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func mustHex(t *testing.T, s string) []byte {
|
||||
t.Helper()
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
)
|
||||
|
||||
const (
|
||||
TypeText = "text"
|
||||
TypeGrant = "grant"
|
||||
|
||||
// Limits are in UTF-8 bytes.
|
||||
MaxFirstText = 1000
|
||||
MaxText = 2000
|
||||
MaxAddress = 300
|
||||
MaxPhone = 40
|
||||
MaxEmail = 120
|
||||
MaxNote = 1000
|
||||
// MaxGrantValidity bounds valid_until.
|
||||
MaxGrantValidity = 30 * 24 * time.Hour
|
||||
|
||||
replyContext = "allmende-reply-v1\n"
|
||||
)
|
||||
|
||||
// Plain is what an envelope carries inside its ciphertext.
|
||||
type Plain struct {
|
||||
Type string `json:"t"` // "text" or "grant"
|
||||
Thread string `json:"thread"` // thread public key, hex
|
||||
N int64 `json:"n"` // sender's counter in this thread, from 1
|
||||
SentAt int64 `json:"sent_at"`
|
||||
Text string `json:"text,omitempty"`
|
||||
Address string `json:"address,omitempty"` // grant only
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Note string `json:"note,omitempty"`
|
||||
// ValidUntil is when a grant stops being shown (advisory).
|
||||
ValidUntil int64 `json:"valid_until,omitempty"`
|
||||
|
||||
// Owner replies are signed; buyer messages carry none of these.
|
||||
Listing *Ref `json:"listing,omitempty"`
|
||||
Device string `json:"device,omitempty"`
|
||||
Cert *identity.Cert `json:"cert,omitempty"`
|
||||
Sig string `json:"sig,omitempty"`
|
||||
}
|
||||
|
||||
func decodePlain(body []byte) (*Plain, error) {
|
||||
var p Plain
|
||||
if err := json.Unmarshal(body, &p); err != nil {
|
||||
return nil, errors.New("message: malformed plaintext")
|
||||
}
|
||||
// Re-encoding must reproduce the input exactly, so unknown fields,
|
||||
// non-canonical spelling and duplicates are all rejected.
|
||||
again, err := jcs.Marshal(&p)
|
||||
if err != nil || !bytes.Equal(again, body) {
|
||||
return nil, errors.New("message: plaintext is not canonical")
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (p *Plain) unsignedBytes() ([]byte, error) {
|
||||
c := *p
|
||||
c.Sig = ""
|
||||
return jcs.Marshal(&c)
|
||||
}
|
||||
|
||||
func (p *Plain) signOwner(dev *identity.Device, ref Ref) {
|
||||
p.Listing = &Ref{Author: ref.Author, ID: ref.ID}
|
||||
p.Device = dev.Cert.Device
|
||||
p.Cert = dev.Cert
|
||||
p.Sig = ""
|
||||
b, _ := p.unsignedBytes() // cannot fail for the types in Plain
|
||||
p.Sig = hex.EncodeToString(dev.Key.Sign(append([]byte(replyContext), b...)))
|
||||
}
|
||||
|
||||
// verifyOwner checks that the reply was signed by a device certified by the
|
||||
// author of the listing it names. It cannot know about later revocations.
|
||||
func (p *Plain) verifyOwner() error {
|
||||
if p.Cert == nil || p.Listing == nil {
|
||||
return errors.New("message: reply is not signed")
|
||||
}
|
||||
if err := p.Cert.Check(); err != nil {
|
||||
return fmt.Errorf("message: %w", err)
|
||||
}
|
||||
if p.Cert.Author != p.Listing.Author || p.Cert.Device != p.Device {
|
||||
return errors.New("message: certificate does not match the listing's author and the device")
|
||||
}
|
||||
if !p.Cert.Covers(p.SentAt) {
|
||||
return errors.New("message: sent outside the certificate's validity")
|
||||
}
|
||||
b, err := p.unsignedBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sig, err := hex.DecodeString(p.Sig)
|
||||
if err != nil || len(sig) != 64 {
|
||||
return errors.New("message: malformed signature")
|
||||
}
|
||||
if !identity.Verify(p.Device, append([]byte(replyContext), b...), sig) {
|
||||
return errors.New("message: bad signature")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validate checks structure for a plaintext travelling in direction to.
|
||||
func (p *Plain) validate(to string) error {
|
||||
if !isHex(p.Thread, 64) {
|
||||
return errors.New("message: thread must be 64 hex characters")
|
||||
}
|
||||
if p.N < 1 || p.N > maxSafeInt || p.SentAt <= 0 || p.SentAt > maxSafeInt {
|
||||
return errors.New("message: n or sent_at out of range")
|
||||
}
|
||||
owner := to == ToBuyer
|
||||
if owner {
|
||||
if p.Listing == nil || !isHex(p.Listing.Author, 64) || !isHex(p.Listing.ID, 32) ||
|
||||
!isHex(p.Device, 64) || p.Cert == nil || !isHex(p.Sig, 128) {
|
||||
return errors.New("message: owner reply must be signed")
|
||||
}
|
||||
} else if p.Listing != nil || p.Device != "" || p.Cert != nil || p.Sig != "" {
|
||||
return errors.New("message: buyer messages are not signed")
|
||||
}
|
||||
switch p.Type {
|
||||
case TypeText:
|
||||
if p.Address != "" || p.Phone != "" || p.Email != "" || p.Note != "" || p.ValidUntil != 0 {
|
||||
return errors.New("message: text must not carry grant fields")
|
||||
}
|
||||
return checkText(p.Text, 1, MaxText, true)
|
||||
case TypeGrant:
|
||||
if !owner {
|
||||
return errors.New("message: only the owner can release an address")
|
||||
}
|
||||
if p.Text != "" {
|
||||
return errors.New("message: a grant carries its words in note")
|
||||
}
|
||||
if err := checkText(p.Address, 1, MaxAddress, true); err != nil {
|
||||
return fmt.Errorf("address: %w", err)
|
||||
}
|
||||
if err := checkText(p.Phone, 0, MaxPhone, false); err != nil {
|
||||
return fmt.Errorf("phone: %w", err)
|
||||
}
|
||||
if err := checkText(p.Email, 0, MaxEmail, false); err != nil {
|
||||
return fmt.Errorf("email: %w", err)
|
||||
}
|
||||
if err := checkText(p.Note, 0, MaxNote, true); err != nil {
|
||||
return fmt.Errorf("note: %w", err)
|
||||
}
|
||||
if p.ValidUntil <= p.SentAt || time.Duration(p.ValidUntil-p.SentAt)*time.Second > MaxGrantValidity {
|
||||
return errors.New("message: valid_until must be within 30 days after sent_at")
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("message: unknown type %q", p.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// checkText limits s to maxBytes of UTF-8 and applies the listing text rules.
|
||||
// The rune limit passed on is maxBytes too: runes never outnumber bytes.
|
||||
func checkText(s string, min, maxBytes int, newlines bool) error {
|
||||
if len(s) > maxBytes {
|
||||
return fmt.Errorf("longer than %d bytes", maxBytes)
|
||||
}
|
||||
return listing.ValidText(s, min, maxBytes, newlines)
|
||||
}
|
||||
|
||||
// CheckBuyerFirst applies the extra rules for a buyer's messages before the
|
||||
// owner has replied: shorter, and no links. Relays cannot enforce this (the
|
||||
// text is encrypted), so the owner's node and the buyer's browser do.
|
||||
func (p *Plain) CheckBuyerFirst() error {
|
||||
if len(p.Text) > MaxFirstText {
|
||||
return fmt.Errorf("a first message may have at most %d bytes", MaxFirstText)
|
||||
}
|
||||
if ContainsLink(p.Text) {
|
||||
return errors.New("a first message must not contain links")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hostname matches label.tld, in any script, so "example.com" and
|
||||
// "Beispiel.de" are caught but "z. B." and "etc." are not.
|
||||
var hostname = regexp.MustCompile(`[\p{L}\p{N}-]+\.\p{L}{2,}`)
|
||||
|
||||
// ContainsLink is a heuristic for URLs and addresses: a scheme separator,
|
||||
// "www.", or a hostname-like word. It also flags "Hallo.Ich" typed without a
|
||||
// space; the message is then hidden, not lost, and the browser asks the buyer
|
||||
// to fix it. It is a speed bump against scams, not a guarantee.
|
||||
func ContainsLink(s string) bool {
|
||||
l := strings.ToLower(s)
|
||||
return strings.Contains(l, "://") || strings.Contains(l, "www.") || hostname.MatchString(l)
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"now": 1800000000,
|
||||
"difficulty": 8,
|
||||
"listing": {
|
||||
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||
"id": "00112233445566778899aabbccddeeff"
|
||||
},
|
||||
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||
"device_seed": "0707070707070707070707070707070707070707070707070707070707070707",
|
||||
"thread_secret": "1111111111111111111111111111111111111111111111111111111111111111",
|
||||
"thread_public": "7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13",
|
||||
"mailbox": "1c5080388031861646a688822711548c",
|
||||
"to_owner": {
|
||||
"esk": "2222222222222222222222222222222222222222222222222222222222222222",
|
||||
"plain": {
|
||||
"t": "text",
|
||||
"thread": "7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13",
|
||||
"n": 1,
|
||||
"sent_at": 1800000000,
|
||||
"text": "Guten Tag, ist die Wohnung noch frei? Schöne Grüße 🏠\nZeile 2\u2028Zeile 3"
|
||||
},
|
||||
"plain_canonical": "{\"n\":1,\"sent_at\":1800000000,\"t\":\"text\",\"text\":\"Guten Tag, ist die Wohnung noch frei? Schöne Grüße 🏠\\nZeile 2\u2028Zeile 3\",\"thread\":\"7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13\"}",
|
||||
"padded_len": 512,
|
||||
"canonical": "{\"created_at\":1800000000,\"ct\":\"49dcc562f0a7ca98687ec373eb9b4528cafae1ccb46e9f9e8e746dd1c652124d5eb9ee8e63335a63c41148e59fa5cf8cd773309221668cda3d9d144e51285e99fe427ffe8ec65660c28eae5b10f61060864f5730d792859ce6a5baa3b9109b9398fb1e22dc4761b2c00af6f05b1ff386507bf1e407dfdcb81a467f9fe604dbbaf005db50387ad3fd1364e8f817d25d66e7a1c231c18460306c02bc5cc16725c9beb0ac9b1334a5f27be9b2f9d006524fd620f22b106a3a8dd4b82a5ee5a7a6f845b698c19d3035cfbf73f11346aa98b108aef1696e95637494b350993b71c981a13b192cb805f47917e8c073876a0116033cfa63a877bcd0604c0011f5c2197ba2fe384134c2cd2b55cac1b7cbe6997e11d9ceec3f71b1787a5721b3ccc082ef225f721c81884e89d37d0b7bbd48681d7e42d62cd5ca9dfab692d7f3a736a7f2d7db36f60c2b1aa5a4fb5fe39eb92cb01c24071eee6f515ff494f82ab303413275c4404e1d7775f7429306c948bfae6e659fea1be2b6948d00f4c8a022033f9ad040665e54ec9aeacd11d973dc6d32eb1535677cff8a9b248f688695b42e1608ff60c9ad0badce345a5828c21f4da49914ad4055b7df8dc06ea8976f24abc38b6fd7746ebecbcbde1ca9becce4dae99501819ffe4896319ee69151a4416ffc18aa56a0d481b4171789649cec9668c830fede417fe7b87fd09dcc441aff4eacc643c0e0fe21a773459e74e85b0ea592d3\",\"epk\":\"0faa684ed28867b97f4a6a2dee5df8ce974e76b7018e3f22a1c4cf2678570f20\",\"expires_at\":1801209600,\"listing\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"id\":\"00112233445566778899aabbccddeeff\"},\"pow\":527,\"rcpt\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"to\":\"owner\",\"v\":1}",
|
||||
"hash": "0034399737231f0ad0aef3caf03a682fdcc31fd79055e73f206f4a35da23334c",
|
||||
"work": 10
|
||||
},
|
||||
"to_buyer": {
|
||||
"esk": "3333333333333333333333333333333333333333333333333333333333333333",
|
||||
"plain": {
|
||||
"t": "grant",
|
||||
"thread": "7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13",
|
||||
"n": 1,
|
||||
"sent_at": 1800000000,
|
||||
"address": "Musterstraße 12, 20255 Hamburg",
|
||||
"phone": "+49 40 123456",
|
||||
"note": "Samstag 10 Uhr, bitte zweimal klingeln 🔔",
|
||||
"valid_until": 1800604800,
|
||||
"listing": {
|
||||
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||
"id": "00112233445566778899aabbccddeeff"
|
||||
},
|
||||
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||
"cert": {
|
||||
"v": 1,
|
||||
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||
"issued_at": 1799996400,
|
||||
"expires_at": 1807776000,
|
||||
"sig": "dab8cef621f829c47eaf5bfea7fcaa3dad144b718d322b4c4989ecc33931c925afcfb50f642ce0c692bc53ceb57f67ddd3c347ff95a496e4f6413ecb5b32ac0e"
|
||||
},
|
||||
"sig": "4908dc2443f4436bca032583504b06e932c9acbf256814033e8b1982c7cb1e02a6a10999c3077e01606358c89461a711e27418d15dad53059f3ee347d960f408"
|
||||
},
|
||||
"plain_canonical": "{\"address\":\"Musterstraße 12, 20255 Hamburg\",\"cert\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"device\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"expires_at\":1807776000,\"issued_at\":1799996400,\"sig\":\"dab8cef621f829c47eaf5bfea7fcaa3dad144b718d322b4c4989ecc33931c925afcfb50f642ce0c692bc53ceb57f67ddd3c347ff95a496e4f6413ecb5b32ac0e\",\"v\":1},\"device\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"listing\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"id\":\"00112233445566778899aabbccddeeff\"},\"n\":1,\"note\":\"Samstag 10 Uhr, bitte zweimal klingeln 🔔\",\"phone\":\"+49 40 123456\",\"sent_at\":1800000000,\"sig\":\"4908dc2443f4436bca032583504b06e932c9acbf256814033e8b1982c7cb1e02a6a10999c3077e01606358c89461a711e27418d15dad53059f3ee347d960f408\",\"t\":\"grant\",\"thread\":\"7b4e909bbe7ffe44c465a220037d608ee35897d31ef972f07f74892cb0f73f13\",\"valid_until\":1800604800}",
|
||||
"padded_len": 1024,
|
||||
"canonical": "{\"created_at\":1800000000,\"ct\":\"8ab2fc4f4fadaa3c8dc5f439bf14bfb7a7bcbd87d4c86d55db264b14f4ff754e617444acbf11421d83bdb0d8b826cb2f1afde4898bb8b53ba9a3ece8cb3972fab5f777b9fbf3217588c802fc0d96abc0bd0e8367ad16ac7b81205b00e8e7885703228d813495208f42deeb0b7a3f104d605e77d83f191394156745b227a7dfd753243d768d49c37cd0e53e19c801fc6b45a7f1fd4cc0d5af37ca87a9e600ccbadec048ee71f482f526cec43ba5941210b4c28bc633b3f8373587f9be728bd90944ee4c81703fcd27eaa8d86a41a41d37e499d33e5d1024c1723d0d77d7a5a53012363446d80ca590b7bc34a9930cf1d2b1c6335e56c1eb22534875729e4f8de020bd2cd2993593550b384ff9601fd8d0a072b32e6a7a2e36c71f9259b78030170e9dfa74fe09ed774e08feca66b2b791545b592fa4b7502d5031456f5e55b1ecc6f928216f591f1c57ac0222a66ff7c5af2eeb1a30672a9be846ac9da682a4bb97cad9562f62b1928d9db8b7d27ef494b0372fc0279d6430ca8443f9e40bf2dd082bc79613696e36f81e6600d567f0580bf42713658f6bd92c3c6c18e63ead7e070da60f5470fbfc179e0e623f7cfaa6b82ed9f89495cacdfc86cc0c2ed119efd99a986af689b4ef62384f801da777d5fce0a7260ae00001d70a98a3cb8a6f93a7286f1f7915b4d2da0a7b6af304903061aa96657922a33d5048c2253a3524533f4ed14cae2e0f4cc65a110cf681176ab31510d3316b858af6caee2538e164a6e51095ad4b31aab8c14706f031ed0c8fff2d30110e224dfc3ab5ec07a01e9a5b5e754bb2b5060cad3b30361a80c08e136e59cc02ddf50444a8f67ee0f8d1704a1ee7f73e5a03774d28bf71393313cdad43a6e11d56f7b1125af733c7095fd4dca009ffd951d13b74bf286e0ca6c0ed11268d07b57d98ec27093fcaa08bf41929639edd8afe4b7bc6a8a0e0f22e70e7a72cfa1fa0888b52423447003732c38e667aa3a1616c84eee78066c73234c5550ea3a32cbd46c9a2ad99e02b94cf48abb6155cebc5d0f344150e4d439b468f02ab82fc5ec8c90c9cecb838fe86d1bbff101239c5ccf33b0d1298332f7150e6e46e49dd5c06212fd78ddc077b75368002b54c2098ae9e3ca33b239134c406c8adc4c3af9b96095293c8f852ff012d3a6c31cb3f6c7feac339cf4bb27eb2841849001c9c499f472d16ee7fe8184bb2dbe9fa93dbcf76dcc6c6b3c7827bf62090d59b77b5432e974d74fe8a2e7c5aee68b7a7fe96a530e03e62f694b0abd035f22f40d64da500a09d71d3488261b3cbff6d6a3fd422084602a3672b89490fd9c0932017f366223ae4fa132df2111b218e711020218f4378432ef97045de9be216124051b68f0a7fd0601a9b0da6fa22118ae2d6eae2c28106bc803b8732251219eb5891812c5b0ebfab504dc60d3f60993c0484b7813a40f5595969e8f40cb51b1167\",\"epk\":\"7b0d47d93427f8311160781c7c733fd89f88970aef490d8aa0ee19a4cb8a1b14\",\"expires_at\":1801209600,\"listing\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"id\":\"00112233445566778899aabbccddeeff\"},\"pow\":79,\"rcpt\":\"1c5080388031861646a688822711548c\",\"to\":\"buyer\",\"v\":1}",
|
||||
"hash": "00453c5f05142dd4176db4381d30cf00079b847189aa60902d7bf9d9e4a5a3ee",
|
||||
"work": 9
|
||||
},
|
||||
"links": [
|
||||
{
|
||||
"text": "Guten Tag, ist die Wohnung noch frei?",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "Ich komme z. B. am Samstag, ca. 10 Uhr.",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "Preis 1.200 Euro, ok? Ja. Gut.",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "Hallo, wir sind 2 Personen (u.a. Nichtraucher).",
|
||||
"link": false
|
||||
},
|
||||
{
|
||||
"text": "schaut mal https://example.com/x",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "WWW.example",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "auf beispiel.de gibt es mehr",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "mail an max@example.com",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "Hallo.Ich komme morgen",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "Beispiel.DE",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "auf straße-1.com",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"text": "bit.ly/abc",
|
||||
"link": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const msgRegion = "u1x"
|
||||
|
||||
func hello(t *testing.T, text string) *message.Plain {
|
||||
t.Helper()
|
||||
return &message.Plain{Type: message.TypeText, N: 1, SentAt: time.Now().Unix(), Text: text}
|
||||
}
|
||||
|
||||
func TestMessagesTravelBetweenBuyerGatewayAndOwner(t *testing.T) {
|
||||
owner := startNode(t, nil, msgRegion)
|
||||
gateway := startNode(t, nil, msgRegion)
|
||||
connect(t, gateway, owner)
|
||||
|
||||
l := owner.listing(t, "u1xjhx")
|
||||
if err := owner.Publish(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
eventually(t, "gateway learns the listing", func() bool {
|
||||
_, err := gateway.s.Get(context.Background(), l.Author, l.ID)
|
||||
return err == nil
|
||||
})
|
||||
|
||||
// The buyer's browser sends through the gateway.
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env, err := message.SealToOwner(l, tk, hello(t, "Ist die Wohnung noch frei?"), time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gateway.PublishMessage(context.Background(), msgRegion, env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var got []*message.Envelope
|
||||
eventually(t, "owner receives the message", func() bool {
|
||||
got, _ = owner.s.OwnerMessages(context.Background(), l.Author)
|
||||
return len(got) == 1
|
||||
})
|
||||
plain, err := got[0].OpenAsOwner(owner.dev)
|
||||
if err != nil || plain.Text != "Ist die Wohnung noch frei?" {
|
||||
t.Fatalf("owner could not read it: %v %+v", err, plain)
|
||||
}
|
||||
|
||||
// The owner answers; the reply waits in the gateway's mailbox.
|
||||
reply := &message.Plain{Type: message.TypeText, Thread: plain.Thread, N: 1, SentAt: time.Now().Unix(), Text: "Ja!"}
|
||||
renv, err := message.SealToBuyer(owner.dev, message.Ref{Author: l.Author, ID: l.ID}, reply, time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := owner.PublishMessage(context.Background(), msgRegion, renv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailbox, _ := tk.Mailbox()
|
||||
var box []*message.Envelope
|
||||
eventually(t, "reply reaches the gateway's mailbox", func() bool {
|
||||
box, _ = gateway.s.Mailbox(context.Background(), mailbox, 0, 10)
|
||||
return len(box) == 1
|
||||
})
|
||||
back, err := box[0].OpenAsBuyer(tk)
|
||||
if err != nil || back.Text != "Ja!" {
|
||||
t.Fatalf("buyer could not read the reply: %v %+v", err, back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLateJoinersSyncMessagesAfterListings(t *testing.T) {
|
||||
owner := startNode(t, nil, msgRegion)
|
||||
l := owner.listing(t, "u1xjhx")
|
||||
if err := owner.Publish(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tk, _ := message.NewThreadKey()
|
||||
env, err := message.SealToOwner(l, tk, hello(t, "hallo"), time.Now(), msgDifficulty)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := owner.PublishMessage(context.Background(), msgRegion, env); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reply := &message.Plain{Type: message.TypeText, Thread: tk.PublicHex(), N: 1, SentAt: time.Now().Unix(), Text: "ok"}
|
||||
renv, _ := message.SealToBuyer(owner.dev, message.Ref{Author: l.Author, ID: l.ID}, reply, time.Now(), msgDifficulty)
|
||||
if err := owner.PublishMessage(context.Background(), msgRegion, renv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Joins later, and in another region as well, which must stay empty.
|
||||
late := startNode(t, nil, msgRegion)
|
||||
other := startNode(t, nil, "u1y")
|
||||
connect(t, late, owner)
|
||||
connect(t, other, owner)
|
||||
|
||||
eventually(t, "late joiner has the owner-bound message", func() bool {
|
||||
got, _ := late.s.OwnerMessages(context.Background(), l.Author)
|
||||
return len(got) == 1
|
||||
})
|
||||
mailbox, _ := tk.Mailbox()
|
||||
eventually(t, "late joiner has the reply", func() bool {
|
||||
box, _ := late.s.Mailbox(context.Background(), mailbox, 0, 10)
|
||||
return len(box) == 1
|
||||
})
|
||||
if n, _ := other.s.MessageCount(context.Background()); n != 0 {
|
||||
t.Fatalf("a node in another region holds %d envelopes", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidMessagesAreNotAccepted(t *testing.T) {
|
||||
a := startNode(t, nil, msgRegion)
|
||||
l := a.listing(t, "u1xjhx")
|
||||
if err := a.Publish(context.Background(), l); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tk, _ := message.NewThreadKey()
|
||||
|
||||
// No proof-of-work at this node's difficulty.
|
||||
var weak *message.Envelope
|
||||
for {
|
||||
e, err := message.SealToOwner(l, tk, hello(t, "x"), time.Now(), 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w < msgDifficulty {
|
||||
weak = e
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := a.PublishMessage(context.Background(), msgRegion, weak); !errors.Is(err, store.ErrInvalid) {
|
||||
t.Fatalf("weak message: %v, want ErrInvalid", err)
|
||||
}
|
||||
|
||||
// A listing this node does not hold.
|
||||
b := startNode(t, nil, msgRegion)
|
||||
foreign := b.listing(t, "u1xjhx")
|
||||
env, _ := message.SealToOwner(foreign, tk, hello(t, "x"), time.Now(), msgDifficulty)
|
||||
if err := a.PublishMessage(context.Background(), msgRegion, env); !errors.Is(err, store.ErrNoListing) {
|
||||
t.Fatalf("unknown listing: %v, want ErrNoListing", err)
|
||||
}
|
||||
if n, _ := a.s.MessageCount(context.Background()); n != 0 {
|
||||
t.Fatalf("rejected messages were stored (%d)", n)
|
||||
}
|
||||
}
|
||||
@@ -30,11 +30,15 @@ import (
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
listingTopicPrefix = "/allmende/1/listings/"
|
||||
// messageTopicPrefix carries encrypted message envelopes, one topic per
|
||||
// region next to the listing topic.
|
||||
messageTopicPrefix = "/allmende/1/messages/"
|
||||
// RevocationTopic carries identity revocations for the whole network.
|
||||
RevocationTopic = "/allmende/1/revocations"
|
||||
|
||||
@@ -53,6 +57,9 @@ type Config struct {
|
||||
MDNS bool // discover peers on the local network
|
||||
|
||||
Difficulty int // required proof-of-work bits
|
||||
// MessageDifficulty is the proof-of-work bits required of message
|
||||
// envelopes; it must match the store's.
|
||||
MessageDifficulty int
|
||||
SyncPageSize int // records per sync page (default 500)
|
||||
RedialInterval time.Duration // how often lost bootstrap peers are redialed (default 20s)
|
||||
Clock func() time.Time // default time.Now
|
||||
@@ -74,6 +81,7 @@ type Node struct {
|
||||
|
||||
mu sync.Mutex
|
||||
topics map[string]*pubsub.Topic
|
||||
msgTopics map[string]*pubsub.Topic
|
||||
subscribed []string
|
||||
bootstrap []peer.AddrInfo
|
||||
syncing map[peer.ID]bool
|
||||
@@ -126,6 +134,7 @@ func New(ctx context.Context, cfg Config) (*Node, error) {
|
||||
ctx: nctx,
|
||||
cancel: cancel,
|
||||
topics: map[string]*pubsub.Topic{},
|
||||
msgTopics: map[string]*pubsub.Topic{},
|
||||
syncing: map[peer.ID]bool{},
|
||||
bootstrap: bootstrap,
|
||||
}
|
||||
@@ -226,6 +235,24 @@ func (n *Node) Publish(ctx context.Context, l *listing.Listing) error {
|
||||
return t.Publish(ctx, data)
|
||||
}
|
||||
|
||||
// PublishMessage stores an envelope locally (which verifies it) and gossips it
|
||||
// on the message topic of region. The node must replicate the region: owner-
|
||||
// bound envelopes are only accepted for listings it holds.
|
||||
func (n *Node) PublishMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
if _, err := n.cfg.Store.PutMessage(ctx, region, e); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := e.Bytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t, err := n.messageTopic(region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.Publish(ctx, data)
|
||||
}
|
||||
|
||||
// PublishRevocation stores r locally and gossips it to the whole network.
|
||||
func (n *Node) PublishRevocation(ctx context.Context, r *identity.Revocation) error {
|
||||
if _, err := n.cfg.Store.PutRevocation(ctx, r); err != nil {
|
||||
@@ -307,9 +334,56 @@ func (n *Node) subscribeRegion(region string) error {
|
||||
}
|
||||
})
|
||||
}()
|
||||
|
||||
mt, err := n.messageTopic(region)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
msub, err := mt.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n.wg.Add(1)
|
||||
go func() {
|
||||
defer n.wg.Done()
|
||||
n.consume(msub, func(msg *pubsub.Message) {
|
||||
e, ok := msg.ValidatorData.(*message.Envelope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
switch _, err := n.cfg.Store.PutMessage(n.ctx, region, e); {
|
||||
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
|
||||
default:
|
||||
n.log.Warn("store message", "err", err)
|
||||
}
|
||||
})
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// messageTopic joins (once) the message topic for region.
|
||||
func (n *Node) messageTopic(region string) (*pubsub.Topic, error) {
|
||||
if !listing.ValidRegion(region) {
|
||||
return nil, fmt.Errorf("p2p: invalid region %q", region)
|
||||
}
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
if t, ok := n.msgTopics[region]; ok {
|
||||
return t, nil
|
||||
}
|
||||
name := messageTopicPrefix + region
|
||||
if err := n.ps.RegisterTopicValidator(name, n.messageValidator(region),
|
||||
pubsub.WithValidatorTimeout(5*time.Second)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t, err := n.ps.Join(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.msgTopics[region] = t
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// regionTopic joins (once) the topic for region and installs its validator.
|
||||
func (n *Node) regionTopic(region string) (*pubsub.Topic, error) {
|
||||
if !listing.ValidRegion(region) {
|
||||
@@ -360,6 +434,39 @@ func (n *Node) listingValidator(region string) pubsub.ValidatorEx {
|
||||
}
|
||||
}
|
||||
|
||||
// messageValidator checks what a relay can see: the envelope's structure,
|
||||
// size and proof-of-work, and the listing it points to. It cannot read the
|
||||
// content. Invalid envelopes cost the relaying peer score; ones this node
|
||||
// cannot place (unknown listing, a device that changed) or whose clocks
|
||||
// disagree are ignored without penalty.
|
||||
func (n *Node) messageValidator(region string) pubsub.ValidatorEx {
|
||||
return func(ctx context.Context, _ peer.ID, msg *pubsub.Message) pubsub.ValidationResult {
|
||||
if len(msg.Data) > message.MaxSize {
|
||||
return pubsub.ValidationReject
|
||||
}
|
||||
var e message.Envelope
|
||||
if err := json.Unmarshal(msg.Data, &e); err != nil {
|
||||
return pubsub.ValidationReject
|
||||
}
|
||||
// Only the canonical encoding, so every node derives the same ID.
|
||||
if canon, err := e.Bytes(); err != nil || !bytes.Equal(canon, msg.Data) {
|
||||
return pubsub.ValidationReject
|
||||
}
|
||||
err := n.cfg.Store.CheckMessage(ctx, region, &e)
|
||||
switch {
|
||||
case err == nil:
|
||||
msg.ValidatorData = &e
|
||||
return pubsub.ValidationAccept
|
||||
case errors.Is(err, listing.ErrTimeWindow), errors.Is(err, store.ErrNoListing):
|
||||
return pubsub.ValidationIgnore
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
return pubsub.ValidationReject
|
||||
default:
|
||||
return pubsub.ValidationIgnore // a local failure is not the peer's fault
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (n *Node) validateListing(ctx context.Context, data []byte) (*listing.Listing, pubsub.ValidationResult) {
|
||||
if len(data) > listing.MaxSize {
|
||||
return nil, pubsub.ValidationReject
|
||||
|
||||
@@ -18,7 +18,10 @@ import (
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const difficulty = 6
|
||||
const (
|
||||
difficulty = 6
|
||||
msgDifficulty = 4
|
||||
)
|
||||
|
||||
// testLogger is silent unless P2P_DEBUG is set.
|
||||
func testLogger() *slog.Logger {
|
||||
@@ -49,7 +52,7 @@ func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), r
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty})
|
||||
s, err := store.Open(":memory:", store.Options{Difficulty: difficulty, MessageDifficulty: msgDifficulty})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -59,6 +62,7 @@ func startNodeWith(t *testing.T, root *identity.Identity, tweak func(*Config), r
|
||||
ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},
|
||||
Regions: regions,
|
||||
Difficulty: difficulty,
|
||||
MessageDifficulty: msgDifficulty,
|
||||
SyncPageSize: 3,
|
||||
RedialInterval: 200 * time.Millisecond,
|
||||
Logger: testLogger(),
|
||||
|
||||
+68
-3
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
@@ -30,11 +32,12 @@ const (
|
||||
)
|
||||
|
||||
type syncRequest struct {
|
||||
Kind string `json:"kind"` // "listings" or "revocations"
|
||||
Kind string `json:"kind"` // "listings", "messages" or "revocations"
|
||||
Region string `json:"region,omitempty"`
|
||||
AfterCreated int64 `json:"after_created,omitempty"`
|
||||
AfterAuthor string `json:"after_author,omitempty"`
|
||||
AfterID string `json:"after_id,omitempty"`
|
||||
AfterAuthor string `json:"after_author,omitempty"` // listings
|
||||
AfterID string `json:"after_id,omitempty"` // listings
|
||||
AfterHash string `json:"after_hash,omitempty"` // messages
|
||||
Limit int `json:"limit,omitempty"`
|
||||
}
|
||||
|
||||
@@ -81,6 +84,27 @@ func (n *Node) handleSync(s network.Stream) {
|
||||
return
|
||||
}
|
||||
}
|
||||
case "messages":
|
||||
if !listing.ValidRegion(req.Region) {
|
||||
_ = s.Reset()
|
||||
return
|
||||
}
|
||||
limit := req.Limit
|
||||
if limit <= 0 || limit > n.cfg.SyncPageSize {
|
||||
limit = n.cfg.SyncPageSize
|
||||
}
|
||||
items, err := n.cfg.Store.MessagesSince(n.ctx, req.Region,
|
||||
store.MessageCursor{CreatedAt: req.AfterCreated, Hash: req.AfterHash}, limit)
|
||||
if err != nil {
|
||||
_ = s.Reset()
|
||||
return
|
||||
}
|
||||
for _, e := range items {
|
||||
if !write(e.Bytes()) {
|
||||
_ = s.Reset()
|
||||
return
|
||||
}
|
||||
}
|
||||
case "revocations":
|
||||
revs, err := n.cfg.Store.Revocations(n.ctx)
|
||||
if err != nil {
|
||||
@@ -147,6 +171,47 @@ func (n *Node) SyncFrom(ctx context.Context, p peer.ID) error {
|
||||
if err := n.syncRegion(ctx, p, region); err != nil {
|
||||
return err
|
||||
}
|
||||
// After the listings: owner-bound messages are only accepted for
|
||||
// listings we already hold.
|
||||
if err := n.syncMessages(ctx, p, region); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (n *Node) syncMessages(ctx context.Context, p peer.ID, region string) error {
|
||||
var cur store.MessageCursor
|
||||
for page := 0; page < maxSyncPages; page++ {
|
||||
var count int
|
||||
var last *message.Envelope
|
||||
err := n.request(ctx, p, syncRequest{
|
||||
Kind: "messages", Region: region, Limit: n.cfg.SyncPageSize,
|
||||
AfterCreated: cur.CreatedAt, AfterHash: cur.Hash,
|
||||
}, func(line []byte) {
|
||||
var e message.Envelope
|
||||
if json.Unmarshal(line, &e) != nil {
|
||||
return
|
||||
}
|
||||
count++
|
||||
last = &e
|
||||
switch _, err := n.cfg.Store.PutMessage(ctx, region, &e); {
|
||||
case err == nil, errors.Is(err, store.ErrNoListing), errors.Is(err, store.ErrQueueFull):
|
||||
default:
|
||||
n.log.Debug("sync: message rejected", "peer", p, "err", err)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count < n.cfg.SyncPageSize || last == nil {
|
||||
return nil
|
||||
}
|
||||
c, err := store.MessageCursorOf(last)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cur = c
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/jcs"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
// Directions of an InboxMessage.
|
||||
const (
|
||||
InboxIn = "in" // from a buyer
|
||||
InboxOut = "out" // our reply
|
||||
)
|
||||
|
||||
// InboxMessage is one decrypted message in the owner's conversations.
|
||||
type InboxMessage struct {
|
||||
Hash string // hash of the envelope that carried it
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
Dir string
|
||||
Plain *message.Plain
|
||||
Hidden bool // a buyer message that broke the first-message rules
|
||||
ReceivedAt int64
|
||||
}
|
||||
|
||||
// ThreadSummary describes one conversation.
|
||||
type ThreadSummary struct {
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
Messages int
|
||||
Hidden int
|
||||
Replied bool // we have answered at least once
|
||||
FirstAt int64
|
||||
LastAt int64
|
||||
}
|
||||
|
||||
// Address is the exact location and contact data of a listing. It is stored
|
||||
// only here and used only to prefill an address grant.
|
||||
type Address struct {
|
||||
Address string `json:"address"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
// Region returns the gossip region of a listing, even if it is deleted or
|
||||
// expired but not yet purged, so replies can still be routed.
|
||||
func (s *Store) Region(ctx context.Context, author, id string) (string, error) {
|
||||
var geohash string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT geohash FROM listings WHERE author = ? AND id = ?`, author, id).Scan(&geohash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return listing.Region(geohash), nil
|
||||
}
|
||||
|
||||
// SeenEnvelopes returns which of the given envelope hashes the owner's node
|
||||
// has already processed.
|
||||
func (s *Store) SeenEnvelopes(ctx context.Context, hashes []string) (map[string]bool, error) {
|
||||
seen := map[string]bool{}
|
||||
for _, h := range hashes {
|
||||
var n int
|
||||
if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM inbox_seen WHERE hash = ?`, h).Scan(&n); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen[h] = n > 0
|
||||
}
|
||||
return seen, nil
|
||||
}
|
||||
|
||||
// MarkSeen records an envelope as processed until expiresAt.
|
||||
func (s *Store) MarkSeen(ctx context.Context, hash string, expiresAt int64) error {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`, hash, expiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddInbox stores a decrypted message and marks its envelope as seen, in one
|
||||
// transaction. Adding the same hash twice is a no-op.
|
||||
func (s *Store) AddInbox(ctx context.Context, m InboxMessage, seenUntil int64) error {
|
||||
data, err := jcs.Marshal(m.Plain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT OR IGNORE INTO inbox (hash, author, listing_id, thread, dir, n, sent_at, received_at, hidden, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
m.Hash, m.Listing.Author, m.Listing.ID, m.Thread, m.Dir, m.Plain.N, m.Plain.SentAt, m.ReceivedAt,
|
||||
boolInt(m.Hidden), data); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO inbox_seen (hash, expires_at) VALUES (?, ?)`,
|
||||
m.Hash, seenUntil); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// HasThread reports whether a conversation exists.
|
||||
func (s *Store) HasThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`,
|
||||
ref.Author, ref.ID, thread).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// Replied reports whether we have sent anything in the conversation.
|
||||
func (s *Store) Replied(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT COUNT(*) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
|
||||
ref.Author, ref.ID, thread).Scan(&n)
|
||||
return n > 0, err
|
||||
}
|
||||
|
||||
// NewThreadsSince counts conversations of a listing that began (were first
|
||||
// received) at or after since.
|
||||
func (s *Store) NewThreadsSince(ctx context.Context, ref message.Ref, since int64) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `
|
||||
SELECT COUNT(*) FROM (
|
||||
SELECT MIN(received_at) AS first FROM inbox
|
||||
WHERE author = ? AND listing_id = ? GROUP BY thread
|
||||
) WHERE first >= ?`, ref.Author, ref.ID, since).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// NextOut returns the counter for our next message in a conversation.
|
||||
func (s *Store) NextOut(ctx context.Context, ref message.Ref, thread string) (int64, error) {
|
||||
var max sql.NullInt64
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT MAX(n) FROM inbox WHERE author = ? AND listing_id = ? AND thread = ? AND dir = 'out'`,
|
||||
ref.Author, ref.ID, thread).Scan(&max)
|
||||
return max.Int64 + 1, err
|
||||
}
|
||||
|
||||
// Threads lists the author's conversations, most recently active first.
|
||||
func (s *Store) Threads(ctx context.Context, author string) ([]ThreadSummary, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT listing_id, thread, COUNT(*), SUM(hidden), SUM(dir = 'out'), MIN(received_at), MAX(sent_at)
|
||||
FROM inbox WHERE author = ?
|
||||
GROUP BY listing_id, thread
|
||||
ORDER BY MAX(sent_at) DESC, thread`, author)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []ThreadSummary
|
||||
for rows.Next() {
|
||||
t := ThreadSummary{Listing: message.Ref{Author: author}}
|
||||
var replies int
|
||||
if err := rows.Scan(&t.Listing.ID, &t.Thread, &t.Messages, &t.Hidden, &replies, &t.FirstAt, &t.LastAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.Replied = replies > 0
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ThreadMessages returns a conversation in order.
|
||||
func (s *Store) ThreadMessages(ctx context.Context, ref message.Ref, thread string) ([]InboxMessage, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT hash, dir, hidden, received_at, data FROM inbox
|
||||
WHERE author = ? AND listing_id = ? AND thread = ?
|
||||
ORDER BY sent_at, dir, n, hash`, ref.Author, ref.ID, thread)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []InboxMessage
|
||||
for rows.Next() {
|
||||
m := InboxMessage{Listing: ref, Thread: thread}
|
||||
var hidden int
|
||||
var data []byte
|
||||
if err := rows.Scan(&m.Hash, &m.Dir, &hidden, &m.ReceivedAt, &data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m.Hidden = hidden != 0
|
||||
m.Plain = &message.Plain{}
|
||||
if err := json.Unmarshal(data, m.Plain); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt inbox row: %w", err)
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DeleteThread erases a conversation from this node.
|
||||
func (s *Store) DeleteThread(ctx context.Context, ref message.Ref, thread string) (bool, error) {
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM inbox WHERE author = ? AND listing_id = ? AND thread = ?`, ref.Author, ref.ID, thread)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return n > 0, nil
|
||||
}
|
||||
|
||||
// SetAddress stores the exact address of one of the author's listings.
|
||||
func (s *Store) SetAddress(ctx context.Context, ref message.Ref, a Address) error {
|
||||
_, err := s.db.ExecContext(ctx, `
|
||||
INSERT OR REPLACE INTO addresses (author, listing_id, address, phone, email) VALUES (?, ?, ?, ?, ?)`,
|
||||
ref.Author, ref.ID, a.Address, a.Phone, a.Email)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetAddress returns the stored address, or ErrNotFound.
|
||||
func (s *Store) GetAddress(ctx context.Context, ref message.Ref) (Address, error) {
|
||||
var a Address
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT address, phone, email FROM addresses WHERE author = ? AND listing_id = ?`,
|
||||
ref.Author, ref.ID).Scan(&a.Address, &a.Phone, &a.Email)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return a, ErrNotFound
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
// DeleteAddress erases the stored address.
|
||||
func (s *Store) DeleteAddress(ctx context.Context, ref message.Ref) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
const (
|
||||
// MaxOwnerQueue is how many live envelopes one listing's owner queue holds.
|
||||
MaxOwnerQueue = 200
|
||||
// MaxMailboxQueue is how many live replies one mailbox holds.
|
||||
MaxMailboxQueue = 50
|
||||
|
||||
defaultMaxMessages = 20000
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoListing means an owner-bound envelope refers to a listing this node
|
||||
// does not hold live, or to a device that no longer signs for it. This
|
||||
// is usually ordering or a device change, not misbehaviour, so the p2p
|
||||
// layer ignores such envelopes without penalizing the sender.
|
||||
ErrNoListing = errors.New("store: no such live listing")
|
||||
// ErrQueueFull means a queue was full of envelopes with at least as much
|
||||
// proof-of-work as the new one.
|
||||
ErrQueueFull = errors.New("store: message queue full")
|
||||
)
|
||||
|
||||
// PutMessage verifies an envelope as a relay can and stores it in region.
|
||||
// Conflict-free: an envelope's identity is its hash, so duplicates are no-ops.
|
||||
//
|
||||
// Queues are bounded (per listing, per mailbox and overall). When one is full
|
||||
// the envelope with the least proof-of-work is evicted, oldest first, so
|
||||
// filling a queue costs more work than the messages it displaces.
|
||||
func (s *Store) PutMessage(ctx context.Context, region string, e *message.Envelope) (Outcome, error) {
|
||||
now := s.clock()
|
||||
if err := e.Check(now, s.msgDifficulty); err != nil {
|
||||
return Ignored, fmt.Errorf("%w: %w", ErrInvalid, err)
|
||||
}
|
||||
if !listing.ValidRegion(region) {
|
||||
return Ignored, fmt.Errorf("%w: bad region %q", ErrInvalid, region)
|
||||
}
|
||||
hash, err := e.Hash()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
work, err := e.Work()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
data, err := e.Bytes()
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM messages WHERE expires_at <= ?`, now.Unix()); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
if err := s.route(ctx, tx, now.Unix(), region, e); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
|
||||
var dup int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE hash = ?`, hash).Scan(&dup); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if dup > 0 {
|
||||
return Ignored, nil
|
||||
}
|
||||
|
||||
// Make room: the queue's own cap first, then the overall cap.
|
||||
var victims []string
|
||||
if e.To == message.ToOwner {
|
||||
v, reject, err := victim(ctx, tx, `to_dir = 'owner' AND author = ? AND listing_id = ?`,
|
||||
[]any{e.Listing.Author, e.Listing.ID}, s.ownerQueue, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
} else {
|
||||
v, reject, err := victim(ctx, tx, `to_dir = 'buyer' AND rcpt = ?`, []any{e.Rcpt}, s.mailboxQueue, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
}
|
||||
// If the queue already frees a slot, count it before checking the total.
|
||||
limit := s.maxMessages + len(victims)
|
||||
v, reject, err := victim(ctx, tx, `1 = 1`, nil, limit, work)
|
||||
if err != nil || reject {
|
||||
return Ignored, orFull(err)
|
||||
}
|
||||
if v != "" {
|
||||
victims = append(victims, v)
|
||||
}
|
||||
for _, h := range victims {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM messages WHERE hash = ?`, h); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
INSERT INTO messages (hash, to_dir, author, listing_id, rcpt, region, created_at, expires_at, work, data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
hash, e.To, e.Listing.Author, e.Listing.ID, e.Rcpt, region, e.CreatedAt, e.ExpiresAt, work, data)
|
||||
if err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return Ignored, err
|
||||
}
|
||||
return Inserted, nil
|
||||
}
|
||||
|
||||
type rowQuerier interface {
|
||||
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
||||
}
|
||||
|
||||
// route checks an envelope against the listing it refers to: the region must
|
||||
// match the listing's, and an owner-bound envelope needs a live listing whose
|
||||
// current device is the recipient. Replies to buyers need no listing (the
|
||||
// owner may have deleted it since), but if it is known the region still has
|
||||
// to match.
|
||||
func (s *Store) route(ctx context.Context, q rowQuerier, now int64, region string, e *message.Envelope) error {
|
||||
var geohash, device string
|
||||
var tombstone, expires int64
|
||||
err := q.QueryRowContext(ctx,
|
||||
`SELECT geohash, device, tombstone, expires_at FROM listings WHERE author = ? AND id = ?`,
|
||||
e.Listing.Author, e.Listing.ID).Scan(&geohash, &device, &tombstone, &expires)
|
||||
known := err == nil
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if known && listing.Region(geohash) != region {
|
||||
return fmt.Errorf("%w: wrong region for this listing", ErrInvalid)
|
||||
}
|
||||
if e.To == message.ToOwner && (!known || tombstone != 0 || expires <= now || device != e.Rcpt) {
|
||||
return ErrNoListing
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckMessage is the read-only part of PutMessage: what a relay verifies
|
||||
// before forwarding an envelope. It returns an error wrapping ErrInvalid for
|
||||
// envelopes that are wrong, and ErrNoListing for ones this node cannot place.
|
||||
func (s *Store) CheckMessage(ctx context.Context, region string, e *message.Envelope) error {
|
||||
now := s.clock()
|
||||
if err := e.Check(now, s.msgDifficulty); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrInvalid, err)
|
||||
}
|
||||
if !listing.ValidRegion(region) {
|
||||
return fmt.Errorf("%w: bad region %q", ErrInvalid, region)
|
||||
}
|
||||
return s.route(ctx, s.db, now.Unix(), region, e)
|
||||
}
|
||||
|
||||
// orFull turns "rejected, no error" into ErrQueueFull.
|
||||
func orFull(err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrQueueFull
|
||||
}
|
||||
|
||||
// victim looks at the rows matching where. If there are fewer than limit it
|
||||
// returns nothing. Otherwise it picks the row with the least work (oldest on
|
||||
// ties) to evict, or reject = true if the new envelope has even less work.
|
||||
// where is always a constant fragment from this file, never caller input.
|
||||
func victim(ctx context.Context, tx *sql.Tx, where string, args []any, limit, work int) (hash string, reject bool, err error) {
|
||||
var n int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE `+where, args...).Scan(&n); err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if n < limit {
|
||||
return "", false, nil
|
||||
}
|
||||
var least int
|
||||
err = tx.QueryRowContext(ctx,
|
||||
`SELECT hash, work FROM messages WHERE `+where+` ORDER BY work, created_at LIMIT 1`, args...).
|
||||
Scan(&hash, &least)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
if work < least {
|
||||
return "", true, nil
|
||||
}
|
||||
return hash, false, nil
|
||||
}
|
||||
|
||||
// OwnerMessages returns the live envelopes addressed to author's listings,
|
||||
// oldest first. The owner's node decrypts them with its device key.
|
||||
func (s *Store) OwnerMessages(ctx context.Context, author string) ([]*message.Envelope, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE to_dir = 'owner' AND author = ? AND expires_at > ?
|
||||
ORDER BY created_at, hash`, author, s.clock().Unix())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// Mailbox returns up to limit live replies in a mailbox created at or after
|
||||
// since, oldest first. A browser polls it; it dedupes by hash.
|
||||
func (s *Store) Mailbox(ctx context.Context, tag string, since int64, limit int) ([]*message.Envelope, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE to_dir = 'buyer' AND rcpt = ? AND created_at >= ? AND expires_at > ?
|
||||
ORDER BY created_at, hash LIMIT ?`, tag, since, s.clock().Unix(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// MessageCursor is a keyset position in the (created_at, hash) order used to
|
||||
// page through envelopes during sync. The zero value is the beginning.
|
||||
type MessageCursor struct {
|
||||
CreatedAt int64
|
||||
Hash string
|
||||
}
|
||||
|
||||
// MessageCursorOf returns the cursor positioned at e.
|
||||
func MessageCursorOf(e *message.Envelope) (MessageCursor, error) {
|
||||
h, err := e.Hash()
|
||||
return MessageCursor{CreatedAt: e.CreatedAt, Hash: h}, err
|
||||
}
|
||||
|
||||
// MessagesSince returns up to limit live envelopes of a region after cur,
|
||||
// oldest first, for peers that are catching up.
|
||||
func (s *Store) MessagesSince(ctx context.Context, region string, cur MessageCursor, limit int) ([]*message.Envelope, error) {
|
||||
if !listing.ValidRegion(region) {
|
||||
return nil, fmt.Errorf("store: invalid region %q", region)
|
||||
}
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT data FROM messages
|
||||
WHERE region = ? AND expires_at > ? AND (created_at, hash) > (?, ?)
|
||||
ORDER BY created_at, hash LIMIT ?`, region, s.clock().Unix(), cur.CreatedAt, cur.Hash, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return collectMessages(rows)
|
||||
}
|
||||
|
||||
// MessageCount returns the number of live envelopes held.
|
||||
func (s *Store) MessageCount(ctx context.Context) (int, error) {
|
||||
var n int
|
||||
err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM messages WHERE expires_at > ?`,
|
||||
s.clock().Unix()).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func collectMessages(rows *sql.Rows) ([]*message.Envelope, error) {
|
||||
defer rows.Close()
|
||||
var out []*message.Envelope
|
||||
for rows.Next() {
|
||||
var data []byte
|
||||
if err := rows.Scan(&data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var e message.Envelope
|
||||
if err := json.Unmarshal(data, &e); err != nil {
|
||||
return nil, fmt.Errorf("store: corrupt message row: %w", err)
|
||||
}
|
||||
out = append(out, &e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
)
|
||||
|
||||
const msgDifficulty = 4
|
||||
|
||||
const region = "u1x"
|
||||
|
||||
func newMsgEnv(t *testing.T, opt Options) *env {
|
||||
t.Helper()
|
||||
e := &env{now: t0}
|
||||
e.root, _, _ = identity.NewRoot()
|
||||
e.dev = newDevice(t, e.root)
|
||||
opt.Difficulty = difficulty
|
||||
opt.MessageDifficulty = msgDifficulty
|
||||
opt.Clock = func() time.Time { return e.now }
|
||||
s, err := Open(":memory:", opt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
e.s = s
|
||||
return e
|
||||
}
|
||||
|
||||
// toOwner makes a buyer's envelope whose work is exactly `work` bits, so
|
||||
// eviction order can be tested precisely.
|
||||
func toOwner(t *testing.T, l *listing.Listing, at time.Time, work int) *message.Envelope {
|
||||
t.Helper()
|
||||
for {
|
||||
tk, err := message.NewThreadKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := &message.Plain{Type: message.TypeText, N: 1, SentAt: at.Unix(), Text: "hi"}
|
||||
e, err := message.SealToOwner(l, tk, p, at, work)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := e.Work(); w == work {
|
||||
return e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// toBuyer makes an owner reply to the given thread (a fresh one if tk is nil).
|
||||
func toBuyer(t *testing.T, e *env, l *listing.Listing, tk *message.ThreadKey, at time.Time, work int) *message.Envelope {
|
||||
t.Helper()
|
||||
for {
|
||||
k := tk
|
||||
if k == nil {
|
||||
var err error
|
||||
if k, err = message.NewThreadKey(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
p := &message.Plain{Type: message.TypeText, Thread: k.PublicHex(), N: 1, SentAt: at.Unix(), Text: "ok"}
|
||||
env, err := message.SealToBuyer(e.dev, message.Ref{Author: l.Author, ID: l.ID}, p, at, work)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, _ := env.Work(); w == work {
|
||||
return env
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (e *env) putMsg(t *testing.T, env *message.Envelope) Outcome {
|
||||
t.Helper()
|
||||
o, err := e.s.PutMessage(ctx, region, env)
|
||||
if err != nil {
|
||||
t.Fatalf("PutMessage: %v", err)
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func TestMessagesRoundTrip(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
tk, _ := message.NewThreadKey()
|
||||
in := toOwner(t, l, e.now, msgDifficulty)
|
||||
if e.putMsg(t, in) != Inserted {
|
||||
t.Fatal("not inserted")
|
||||
}
|
||||
if e.putMsg(t, in) != Ignored {
|
||||
t.Fatal("a duplicate must be a no-op")
|
||||
}
|
||||
out := toBuyer(t, e, l, tk, e.now.Add(time.Second), msgDifficulty)
|
||||
e.putMsg(t, out)
|
||||
|
||||
got, err := e.s.OwnerMessages(ctx, l.Author)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("OwnerMessages = %d, %v", len(got), err)
|
||||
}
|
||||
if h1, _ := got[0].Hash(); h1 != mustHash(t, in) {
|
||||
t.Fatal("stored envelope differs from what was put")
|
||||
}
|
||||
mb, _ := tk.Mailbox()
|
||||
box, err := e.s.Mailbox(ctx, mb, 0, 10)
|
||||
if err != nil || len(box) != 1 {
|
||||
t.Fatalf("Mailbox = %d, %v", len(box), err)
|
||||
}
|
||||
if _, err := box[0].OpenAsBuyer(tk); err != nil {
|
||||
t.Fatalf("a stored reply no longer opens: %v", err)
|
||||
}
|
||||
if other, _ := e.s.Mailbox(ctx, strings.Repeat("0", 32), 0, 10); len(other) != 0 {
|
||||
t.Fatal("another mailbox must be empty")
|
||||
}
|
||||
if later, _ := e.s.Mailbox(ctx, mb, out.CreatedAt+1, 10); len(later) != 0 {
|
||||
t.Fatal("since must exclude older envelopes")
|
||||
}
|
||||
|
||||
all, err := e.s.MessagesSince(ctx, region, MessageCursor{}, 10)
|
||||
if err != nil || len(all) != 2 {
|
||||
t.Fatalf("MessagesSince = %d, %v", len(all), err)
|
||||
}
|
||||
cur, _ := MessageCursorOf(all[0])
|
||||
rest, _ := e.s.MessagesSince(ctx, region, cur, 10)
|
||||
if len(rest) != 1 || mustHash(t, rest[0]) != mustHash(t, all[1]) {
|
||||
t.Fatal("cursor paging is wrong")
|
||||
}
|
||||
if n, _ := e.s.MessageCount(ctx); n != 2 {
|
||||
t.Fatalf("count = %d", n)
|
||||
}
|
||||
if other, _ := e.s.MessagesSince(ctx, "u1y", MessageCursor{}, 10); len(other) != 0 {
|
||||
t.Fatal("another region must be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func mustHash(t *testing.T, e *message.Envelope) string {
|
||||
t.Helper()
|
||||
h, err := e.Hash()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func TestOwnerMessagesNeedALiveListing(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
env := toOwner(t, l, e.now, msgDifficulty)
|
||||
|
||||
if _, err := e.s.PutMessage(ctx, region, env); !errors.Is(err, ErrNoListing) {
|
||||
t.Fatalf("unknown listing: %v, want ErrNoListing", err)
|
||||
}
|
||||
e.put(t, l)
|
||||
if _, err := e.s.PutMessage(ctx, "u1y", env); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("wrong region: %v, want ErrInvalid", err)
|
||||
}
|
||||
e.putMsg(t, env)
|
||||
|
||||
// A message sealed to a device that no longer signs for the listing.
|
||||
old := toOwner(t, l, e.now.Add(time.Second), msgDifficulty)
|
||||
e.dev = newDevice(t, e.root) // the owner recovered onto a new device
|
||||
re := e.listing(t, func(x *listing.Listing) { x.ID = l.ID; x.Seq = 2 })
|
||||
e.put(t, re)
|
||||
if _, err := e.s.PutMessage(ctx, region, old); !errors.Is(err, ErrNoListing) {
|
||||
t.Fatalf("stale device: %v, want ErrNoListing", err)
|
||||
}
|
||||
|
||||
// Deleted listing.
|
||||
ts := e.listing(t, func(x *listing.Listing) {
|
||||
*x = listing.Listing{Version: listing.Version, ID: l.ID, Seq: 3, CreatedAt: e.now.Unix(),
|
||||
ExpiresAt: e.now.Add(24 * time.Hour).Unix(), Tombstone: true, Geohash: "u1xjhx"}
|
||||
})
|
||||
e.put(t, ts)
|
||||
fresh := toOwner(t, re, e.now.Add(2*time.Second), msgDifficulty)
|
||||
if _, err := e.s.PutMessage(ctx, region, fresh); !errors.Is(err, ErrNoListing) {
|
||||
t.Fatalf("deleted listing: %v, want ErrNoListing", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuyerRepliesDoNotNeedTheListing(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil) // never stored: the owner may have deleted it meanwhile
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, e.now, msgDifficulty))
|
||||
|
||||
// If the listing is known, the region must still match.
|
||||
e.put(t, l)
|
||||
if _, err := e.s.PutMessage(ctx, "u1y", toBuyer(t, e, l, nil, e.now, msgDifficulty)); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("wrong region for a known listing: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidEnvelopesAreRejected(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
weak := toOwner(t, l, e.now, msgDifficulty)
|
||||
strict := newMsgEnv(t, Options{})
|
||||
strict.s.msgDifficulty = 30
|
||||
if _, err := strict.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("weak proof-of-work: %v", err)
|
||||
}
|
||||
|
||||
if _, err := e.s.PutMessage(ctx, "nope", weak); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("bad region: %v", err)
|
||||
}
|
||||
|
||||
// Clock failures stay recognisable so the p2p layer can ignore them.
|
||||
late := newMsgEnv(t, Options{})
|
||||
late.now = t0.Add(20 * 24 * time.Hour)
|
||||
_, err := late.s.PutMessage(ctx, region, weak)
|
||||
if !errors.Is(err, ErrInvalid) || !errors.Is(err, listing.ErrTimeWindow) {
|
||||
t.Fatalf("expired: %v, want ErrInvalid wrapping ErrTimeWindow", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagesExpire(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
tk, _ := message.NewThreadKey()
|
||||
e.putMsg(t, toOwner(t, l, e.now, msgDifficulty))
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, e.now, msgDifficulty))
|
||||
|
||||
e.now = e.now.Add(message.MaxLifetime + time.Minute)
|
||||
mb, _ := tk.Mailbox()
|
||||
if box, _ := e.s.Mailbox(ctx, mb, 0, 10); len(box) != 0 {
|
||||
t.Fatal("expired reply still served")
|
||||
}
|
||||
if got, _ := e.s.OwnerMessages(ctx, l.Author); len(got) != 0 {
|
||||
t.Fatal("expired message still served")
|
||||
}
|
||||
if n, _ := e.s.MessageCount(ctx); n != 0 {
|
||||
t.Fatalf("count = %d", n)
|
||||
}
|
||||
if removed, err := e.s.Expire(ctx); err != nil || removed < 2 {
|
||||
t.Fatalf("Expire removed %d, %v", removed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueueEvictsTheLeastWorkOldestFirst(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{OwnerQueue: 3})
|
||||
l := e.listing(t, nil)
|
||||
e.put(t, l)
|
||||
|
||||
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
|
||||
a := toOwner(t, l, at(1), 4)
|
||||
b := toOwner(t, l, at(2), 4)
|
||||
c := toOwner(t, l, at(3), 4)
|
||||
for _, m := range []*message.Envelope{a, b, c} {
|
||||
e.putMsg(t, m)
|
||||
}
|
||||
|
||||
// More work than the least: evicts the oldest of the least-work ones.
|
||||
d := toOwner(t, l, at(4), 9)
|
||||
e.putMsg(t, d)
|
||||
has := func(m *message.Envelope) bool {
|
||||
all, _ := e.s.OwnerMessages(ctx, l.Author)
|
||||
for _, x := range all {
|
||||
if mustHash(t, x) == mustHash(t, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
if has(a) || !has(b) || !has(c) || !has(d) {
|
||||
t.Fatalf("after d: a=%v b=%v c=%v d=%v, want a evicted only", has(a), has(b), has(c), has(d))
|
||||
}
|
||||
|
||||
// Equal work: the newcomer displaces the oldest (spec: oldest first on ties).
|
||||
f := toOwner(t, l, at(5), 4)
|
||||
e.putMsg(t, f)
|
||||
if has(b) || !has(c) || !has(d) || !has(f) {
|
||||
t.Fatalf("after f: b=%v c=%v d=%v f=%v", has(b), has(c), has(d), has(f))
|
||||
}
|
||||
|
||||
// A queue full of strong envelopes refuses weaker ones and keeps them all.
|
||||
for i := 6; i < 9; i++ {
|
||||
e.putMsg(t, toOwner(t, l, at(i), 9))
|
||||
}
|
||||
weak := toOwner(t, l, at(10), 4)
|
||||
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
|
||||
t.Fatalf("weak newcomer: %v, want ErrQueueFull", err)
|
||||
}
|
||||
if all, _ := e.s.OwnerMessages(ctx, l.Author); len(all) != 3 {
|
||||
t.Fatalf("queue holds %d, want 3", len(all))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailboxQueueIsBounded(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{MailboxQueue: 2})
|
||||
l := e.listing(t, nil)
|
||||
tk, _ := message.NewThreadKey()
|
||||
mb, _ := tk.Mailbox()
|
||||
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
|
||||
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, at(1), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, at(2), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, tk, at(3), 9))
|
||||
box, _ := e.s.Mailbox(ctx, mb, 0, 10)
|
||||
if len(box) != 2 {
|
||||
t.Fatalf("mailbox holds %d, want 2", len(box))
|
||||
}
|
||||
// Another mailbox is not affected.
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(4), 4))
|
||||
}
|
||||
|
||||
func TestOverallCapIsEnforced(t *testing.T) {
|
||||
e := newMsgEnv(t, Options{MaxMessages: 2})
|
||||
l := e.listing(t, nil)
|
||||
at := func(i int) time.Time { return e.now.Add(time.Duration(i) * time.Second) }
|
||||
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(1), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(2), 4))
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(3), 9)) // evicts the oldest weak one
|
||||
e.putMsg(t, toBuyer(t, e, l, nil, at(4), 9)) // evicts the other weak one
|
||||
if n, _ := e.s.MessageCount(ctx); n != 2 {
|
||||
t.Fatalf("count = %d, want 2", n)
|
||||
}
|
||||
weak := toBuyer(t, e, l, nil, at(5), 4)
|
||||
if _, err := e.s.PutMessage(ctx, region, weak); !errors.Is(err, ErrQueueFull) {
|
||||
t.Fatalf("weak newcomer at the overall cap: %v", err)
|
||||
}
|
||||
if n, _ := e.s.MessageCount(ctx); n != 2 {
|
||||
t.Fatalf("count = %d after a rejection, want 2", n)
|
||||
}
|
||||
}
|
||||
+86
-3
@@ -43,14 +43,27 @@ func (o Outcome) String() string {
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Difficulty int // required proof-of-work bits
|
||||
Difficulty int // required proof-of-work bits for listings and revocations
|
||||
Clock func() time.Time // defaults to time.Now
|
||||
|
||||
// MessageDifficulty is the proof-of-work bits required of message
|
||||
// envelopes (message.DefaultDifficulty on a real node).
|
||||
MessageDifficulty int
|
||||
// MaxMessages caps the envelopes this node holds; 0 means 20000.
|
||||
MaxMessages int
|
||||
// OwnerQueue and MailboxQueue cap the envelopes per listing and per
|
||||
// mailbox; 0 means MaxOwnerQueue and MaxMailboxQueue.
|
||||
OwnerQueue, MailboxQueue int
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
difficulty int
|
||||
clock func() time.Time
|
||||
msgDifficulty int
|
||||
maxMessages int
|
||||
ownerQueue int
|
||||
mailboxQueue int
|
||||
}
|
||||
|
||||
const schema = `
|
||||
@@ -87,6 +100,56 @@ CREATE TABLE IF NOT EXISTS revocations (
|
||||
data BLOB NOT NULL,
|
||||
PRIMARY KEY (author, device)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
-- Encrypted message envelopes this node relays (see internal/message).
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
hash TEXT PRIMARY KEY,
|
||||
to_dir TEXT NOT NULL, -- 'owner' or 'buyer'
|
||||
author TEXT NOT NULL, -- listing reference
|
||||
listing_id TEXT NOT NULL,
|
||||
rcpt TEXT NOT NULL, -- owner: device key; buyer: mailbox tag
|
||||
region TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
work INTEGER NOT NULL, -- leading zero bits, decides what a full queue evicts
|
||||
data BLOB NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS messages_listing ON messages (to_dir, author, listing_id);
|
||||
CREATE INDEX IF NOT EXISTS messages_mailbox ON messages (to_dir, rcpt, created_at);
|
||||
CREATE INDEX IF NOT EXISTS messages_region ON messages (region, created_at, hash);
|
||||
CREATE INDEX IF NOT EXISTS messages_expires ON messages (expires_at);
|
||||
CREATE INDEX IF NOT EXISTS messages_work ON messages (work, created_at);
|
||||
|
||||
-- The owner's decrypted conversations. These exist only on the owner's node:
|
||||
-- they are never gossiped.
|
||||
CREATE TABLE IF NOT EXISTS inbox (
|
||||
hash TEXT PRIMARY KEY, -- hash of the envelope that carried it
|
||||
author TEXT NOT NULL,
|
||||
listing_id TEXT NOT NULL,
|
||||
thread TEXT NOT NULL,
|
||||
dir TEXT NOT NULL, -- 'in' from a buyer, 'out' our reply
|
||||
n INTEGER NOT NULL,
|
||||
sent_at INTEGER NOT NULL,
|
||||
received_at INTEGER NOT NULL,
|
||||
hidden INTEGER NOT NULL, -- broke the first-message rules
|
||||
data BLOB NOT NULL -- canonical plaintext
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS inbox_thread ON inbox (author, listing_id, thread, sent_at);
|
||||
-- Envelopes the owner's node has already looked at (decrypted or not), so
|
||||
-- garbage is not decrypted again on every collection.
|
||||
CREATE TABLE IF NOT EXISTS inbox_seen (
|
||||
hash TEXT PRIMARY KEY,
|
||||
expires_at INTEGER NOT NULL
|
||||
) WITHOUT ROWID;
|
||||
-- The exact address of a listing, only ever read by its owner's node.
|
||||
CREATE TABLE IF NOT EXISTS addresses (
|
||||
author TEXT NOT NULL,
|
||||
listing_id TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
phone TEXT NOT NULL,
|
||||
email TEXT NOT NULL,
|
||||
PRIMARY KEY (author, listing_id)
|
||||
) WITHOUT ROWID;
|
||||
`
|
||||
|
||||
// Open opens (creating if needed) the database at path. Use ":memory:" for
|
||||
@@ -106,10 +169,21 @@ func Open(path string, opt Options) (*Store, error) {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock}
|
||||
s := &Store{db: db, difficulty: opt.Difficulty, clock: opt.Clock,
|
||||
msgDifficulty: opt.MessageDifficulty, maxMessages: opt.MaxMessages,
|
||||
ownerQueue: opt.OwnerQueue, mailboxQueue: opt.MailboxQueue}
|
||||
if s.ownerQueue <= 0 {
|
||||
s.ownerQueue = MaxOwnerQueue
|
||||
}
|
||||
if s.mailboxQueue <= 0 {
|
||||
s.mailboxQueue = MaxMailboxQueue
|
||||
}
|
||||
if s.clock == nil {
|
||||
s.clock = time.Now
|
||||
}
|
||||
if s.maxMessages <= 0 {
|
||||
s.maxMessages = defaultMaxMessages
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -433,7 +507,16 @@ func (s *Store) Expire(ctx context.Context) (int64, error) {
|
||||
return n, err
|
||||
}
|
||||
m, _ := res.RowsAffected()
|
||||
return n + m, nil
|
||||
res, err = s.db.ExecContext(ctx, `DELETE FROM messages WHERE expires_at <= ?`, now)
|
||||
if err != nil {
|
||||
return n + m, err
|
||||
}
|
||||
k, _ := res.RowsAffected()
|
||||
// Not counted: housekeeping of the owner's "already seen" markers.
|
||||
if _, err := s.db.ExecContext(ctx, `DELETE FROM inbox_seen WHERE expires_at <= ?`, now); err != nil {
|
||||
return n + m + k, err
|
||||
}
|
||||
return n + m + k, nil
|
||||
}
|
||||
|
||||
// Count returns the number of live listings.
|
||||
|
||||
Vendored
+2026
-189
File diff suppressed because it is too large
Load Diff
Vendored
+1
@@ -12,6 +12,7 @@
|
||||
<body>
|
||||
<header class="top">
|
||||
<a class="brand" href="#/">Allmende</a>
|
||||
<nav id="nav" class="nav"></nav>
|
||||
<span id="status" class="status"></span>
|
||||
</header>
|
||||
<main id="app"></main>
|
||||
|
||||
Vendored
+24
@@ -212,3 +212,27 @@ pre {
|
||||
.detail-head { flex-direction: column; }
|
||||
.kv { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* Messages */
|
||||
.nav { margin-left: auto; }
|
||||
textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 8px 10px;
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
resize: vertical;
|
||||
}
|
||||
textarea:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
|
||||
.compose .actions { margin-top: 8px; align-items: center; }
|
||||
.small { font-size: 0.85rem; }
|
||||
.pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; }
|
||||
.thread, .convs { list-style: none; margin: 0 0 16px; padding: 0; display: grid; gap: 10px; }
|
||||
.msg { max-width: 85%; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
|
||||
.msg.out { justify-self: end; border-color: var(--accent); }
|
||||
.msg .who { color: var(--muted); font-size: 0.85rem; margin-bottom: 4px; }
|
||||
.grant { border: 2px solid var(--accent); border-radius: 8px; padding: 10px 12px; margin: 4px 0; }
|
||||
input[readonly] { width: 100%; box-sizing: border-box; }
|
||||
|
||||
Generated
+13
@@ -7,6 +7,7 @@
|
||||
"name": "allmende-web",
|
||||
"license": "AGPL-3.0-only",
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "2.4.0",
|
||||
"@noble/curves": "2.4.0",
|
||||
"@noble/hashes": "2.4.0"
|
||||
},
|
||||
@@ -478,6 +479,18 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/ciphers": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz",
|
||||
"integrity": "sha512-AnjFn0Jv92laAkvMrghlFZq4qQCIN/4DxFV/eooqtC2YTjB7kBeLMS2T9KJX4Dn+ZVXLOwK0lSgqDtx9gvxtiw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 20.19.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://paulmillr.com/funding/"
|
||||
}
|
||||
},
|
||||
"node_modules/@noble/curves": {
|
||||
"version": "2.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"test": "node --test test/*.test.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/ciphers": "2.4.0",
|
||||
"@noble/curves": "2.4.0",
|
||||
"@noble/hashes": "2.4.0"
|
||||
},
|
||||
|
||||
+42
-1
@@ -1,5 +1,8 @@
|
||||
// Talks to the node that served this page. Everything it returns is untrusted
|
||||
// until verify.ts has checked it.
|
||||
// until verify.ts (listings) or message.ts (replies) has checked it.
|
||||
|
||||
import { canonicalize } from "./jcs.ts";
|
||||
import type { Envelope } from "./message.ts";
|
||||
|
||||
export interface Status {
|
||||
peer_id: string;
|
||||
@@ -9,6 +12,8 @@ export interface Status {
|
||||
peers: number;
|
||||
listings: number;
|
||||
difficulty: number;
|
||||
/** Proof-of-work bits a message needs; absent on nodes without messaging. */
|
||||
message_difficulty?: number;
|
||||
}
|
||||
|
||||
async function getJSON(url: string): Promise<unknown> {
|
||||
@@ -32,3 +37,39 @@ export async function search(params: URLSearchParams): Promise<unknown[]> {
|
||||
export async function getListing(author: string, id: string): Promise<unknown | null> {
|
||||
return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`);
|
||||
}
|
||||
|
||||
/** A node refused a request. `detail` is the node's own explanation (English). */
|
||||
export class HttpError extends Error {
|
||||
readonly status: number;
|
||||
readonly detail: string;
|
||||
constructor(status: number, detail: string) {
|
||||
super(`${status} ${detail}`);
|
||||
this.status = status;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
/** Hands an encrypted envelope to the node, which gossips it to the listing's region. */
|
||||
export async function postMessage(envelope: Envelope): Promise<void> {
|
||||
const res = await fetch("/api/v1/messages", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: canonicalize(envelope), // the node only accepts the canonical encoding
|
||||
});
|
||||
if (res.ok) return;
|
||||
let detail = res.statusText;
|
||||
try {
|
||||
const body = (await res.json()) as { error?: unknown };
|
||||
if (typeof body.error === "string") detail = body.error;
|
||||
} catch {
|
||||
// keep the status text
|
||||
}
|
||||
throw new HttpError(res.status, detail);
|
||||
}
|
||||
|
||||
/** Envelopes in a mailbox created at or after `since` (unix seconds). Unverified. */
|
||||
export async function pollMailbox(tag: string, since: number): Promise<unknown[]> {
|
||||
const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`);
|
||||
if (!Array.isArray(data)) throw new Error("unexpected response");
|
||||
return data;
|
||||
}
|
||||
|
||||
+422
@@ -0,0 +1,422 @@
|
||||
// The buyer's side of messaging: the contact form on a listing, a conversation
|
||||
// and the list of conversations. Everything from the network is shown as text
|
||||
// only, and owner messages only after message.ts verified them.
|
||||
|
||||
import { HttpError, getListing, pollMailbox, postMessage } from "./api.ts";
|
||||
import { append, clear, h } from "./dom.ts";
|
||||
import { date } from "./format.ts";
|
||||
import { t, type Key } from "./i18n.ts";
|
||||
import {
|
||||
DEFAULT_MESSAGE_DIFFICULTY,
|
||||
InputError,
|
||||
MAX_FIRST_TEXT,
|
||||
MAX_TEXT,
|
||||
buildToOwner,
|
||||
checkBuyerText,
|
||||
envelopeHash,
|
||||
mailbox,
|
||||
openReply,
|
||||
threadPublic,
|
||||
toHex,
|
||||
type Plain,
|
||||
} from "./message.ts";
|
||||
import { nowSeconds, state, verifyOpts } from "./state.ts";
|
||||
import {
|
||||
conversationHash,
|
||||
deleteConversation,
|
||||
getConversation,
|
||||
isPersistent,
|
||||
listConversations,
|
||||
saveConversation,
|
||||
type Conversation,
|
||||
type StoredMessage,
|
||||
} from "./threads.ts";
|
||||
import { verifyListing, type Listing } from "./verify.ts";
|
||||
|
||||
const POLL_MS = 20_000;
|
||||
/** Re-read this much of the mailbox each time, so a clock that is a little off loses nothing. */
|
||||
const OVERLAP = 3600;
|
||||
const app = () => document.getElementById("app")!;
|
||||
|
||||
const fromHex = (s: string) => Uint8Array.from(s.match(/../g) ?? [], (b) => parseInt(b, 16));
|
||||
const difficulty = () => state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY;
|
||||
const utf8 = (s: string) => new TextEncoder().encode(s).length;
|
||||
|
||||
function describe(e: unknown): string {
|
||||
if (e instanceof InputError) return t(`problem.${e.problem}` as Key);
|
||||
if (e instanceof HttpError) {
|
||||
if (e.status === 404) return t("send.404");
|
||||
if (e.status === 429) return t("send.429");
|
||||
return t("send.other", { detail: e.detail });
|
||||
}
|
||||
return t("send.network");
|
||||
}
|
||||
|
||||
// --- composing ----------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A text box with a send button. `send` does the work; errors are shown under
|
||||
* the box, and the text is kept so nothing the person wrote is lost.
|
||||
*/
|
||||
function composer(opts: {
|
||||
first: () => boolean;
|
||||
button: Key;
|
||||
send: (text: string) => Promise<void>;
|
||||
}): HTMLElement {
|
||||
const area = h("textarea", { name: "message", rows: 5, "aria-label": t("contact.label"), required: true });
|
||||
const counter = h("span", { class: "muted" });
|
||||
const problem = h("p", { class: "error", role: "alert" });
|
||||
const button = h("button", { type: "submit", class: "btn primary" }, t(opts.button));
|
||||
const update = () => {
|
||||
const max = opts.first() ? MAX_FIRST_TEXT : MAX_TEXT;
|
||||
counter.textContent = t("contact.counter", { used: utf8(area.value), max });
|
||||
};
|
||||
area.addEventListener("input", update);
|
||||
update();
|
||||
|
||||
const form = h(
|
||||
"form",
|
||||
{
|
||||
class: "compose",
|
||||
onsubmit: (ev) => {
|
||||
ev.preventDefault();
|
||||
void (async () => {
|
||||
problem.textContent = "";
|
||||
const text = area.value.trim();
|
||||
const bad = checkBuyerText(text, opts.first());
|
||||
if (bad) {
|
||||
problem.textContent = t(`problem.${bad}` as Key);
|
||||
return;
|
||||
}
|
||||
button.disabled = true;
|
||||
area.disabled = true;
|
||||
button.textContent = t("contact.sending");
|
||||
try {
|
||||
await opts.send(text);
|
||||
area.value = "";
|
||||
update();
|
||||
} catch (e) {
|
||||
problem.textContent = describe(e);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
area.disabled = false;
|
||||
button.textContent = t(opts.button);
|
||||
}
|
||||
})();
|
||||
},
|
||||
},
|
||||
area,
|
||||
h("div", { class: "actions" }, button, counter),
|
||||
problem,
|
||||
);
|
||||
return form;
|
||||
}
|
||||
|
||||
/** Sends the next message of a conversation and records it. */
|
||||
async function sendTo(c: Conversation, listing: Listing, text: string, first: boolean): Promise<void> {
|
||||
const n = c.messages.filter((m) => m.dir === "out").length + 1;
|
||||
const now = nowSeconds();
|
||||
const env = await buildToOwner({
|
||||
listing,
|
||||
threadSecret: fromHex(c.secret),
|
||||
text,
|
||||
n,
|
||||
now,
|
||||
difficulty: difficulty(),
|
||||
first,
|
||||
});
|
||||
await postMessage(env);
|
||||
c.messages.push({ dir: "out", n, sent_at: now, t: "text", text });
|
||||
c.updated = now;
|
||||
saveConversation(c);
|
||||
}
|
||||
|
||||
// --- contact form on a listing --------------------------------------------------
|
||||
|
||||
export function contactPanel(l: Listing): HTMLElement {
|
||||
const existing = getConversation(l.author, l.id);
|
||||
if (existing) {
|
||||
return h(
|
||||
"section",
|
||||
{ class: "panel contact" },
|
||||
h("h2", null, t("contact.title")),
|
||||
h("p", null, t("contact.already")),
|
||||
h("a", { class: "btn", href: conversationHash(l.author, l.id, existing.secret) }, t("contact.open")),
|
||||
);
|
||||
}
|
||||
const form = composer({
|
||||
first: () => true,
|
||||
button: "contact.send",
|
||||
send: async (text) => {
|
||||
const secret = toHex(crypto.getRandomValues(new Uint8Array(32)));
|
||||
const c: Conversation = {
|
||||
author: l.author,
|
||||
id: l.id,
|
||||
secret,
|
||||
title: l.title ?? "",
|
||||
created: nowSeconds(),
|
||||
updated: nowSeconds(),
|
||||
messages: [],
|
||||
since: nowSeconds() - OVERLAP,
|
||||
seen: {},
|
||||
};
|
||||
await sendTo(c, l, text, true);
|
||||
location.hash = conversationHash(l.author, l.id, secret);
|
||||
},
|
||||
});
|
||||
return h(
|
||||
"section",
|
||||
{ class: "panel contact" },
|
||||
h("h2", null, t("contact.title")),
|
||||
h("p", null, t("contact.intro")),
|
||||
h("p", { class: "muted" }, t("contact.rules")),
|
||||
form,
|
||||
);
|
||||
}
|
||||
|
||||
// --- one conversation --------------------------------------------------------------
|
||||
|
||||
function grantCard(m: StoredMessage): HTMLElement {
|
||||
const row = (k: Key, v: string | undefined) => (v ? [h("dt", null, t(k)), h("dd", { class: "pre" }, v)] : []);
|
||||
return h(
|
||||
"div",
|
||||
{ class: "grant" },
|
||||
h("strong", null, t("grant.title")),
|
||||
h(
|
||||
"dl",
|
||||
{ class: "kv" },
|
||||
...row("grant.address", m.address),
|
||||
...row("grant.phone", m.phone),
|
||||
...row("grant.email", m.email),
|
||||
...row("grant.note", m.note),
|
||||
),
|
||||
h("p", { class: "muted" }, t("grant.until", { date: date(m.valid_until ?? 0) }), " · ", t("grant.privacy")),
|
||||
);
|
||||
}
|
||||
|
||||
function bubble(m: StoredMessage): HTMLElement {
|
||||
const mine = m.dir === "out";
|
||||
return h(
|
||||
"li",
|
||||
{ class: `msg ${mine ? "out" : "in"}` },
|
||||
h("div", { class: "who" }, mine ? t("chat.you") : t("chat.owner"), " · ", new Date(m.sent_at * 1000).toLocaleString()),
|
||||
m.t === "grant" ? grantCard(m) : h("p", { class: "pre" }, m.text ?? ""),
|
||||
!mine && h("div", { class: "muted small" }, "✓ ", t("chat.verified")),
|
||||
);
|
||||
}
|
||||
|
||||
function stored(p: Plain, hash: string): StoredMessage {
|
||||
const m: StoredMessage = { dir: "in", n: p.n, sent_at: p.sent_at, t: p.t, hash };
|
||||
for (const k of ["text", "address", "phone", "email", "note", "valid_until"] as const) {
|
||||
if (p[k] !== undefined) (m as unknown as Record<string, unknown>)[k] = p[k];
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
/** Fetches the mailbox once. Returns how many envelopes were not genuine. */
|
||||
async function poll(c: Conversation): Promise<number> {
|
||||
const secret = fromHex(c.secret);
|
||||
const envs = await pollMailbox(mailbox(threadPublic(secret)), c.since);
|
||||
const now = nowSeconds();
|
||||
let rejected = 0;
|
||||
let newest = 0;
|
||||
for (const raw of envs) {
|
||||
let hash: string;
|
||||
try {
|
||||
hash = envelopeHash(raw as never);
|
||||
} catch {
|
||||
rejected++;
|
||||
continue;
|
||||
}
|
||||
if (hash in c.seen) continue;
|
||||
const r = openReply(raw, secret, { author: c.author, id: c.id });
|
||||
const env = raw as { created_at?: number; expires_at?: number };
|
||||
c.seen[hash] = typeof env.expires_at === "number" ? env.expires_at : now + 14 * 86_400;
|
||||
if (typeof env.created_at === "number") newest = Math.max(newest, env.created_at);
|
||||
if (!r.ok) {
|
||||
rejected++;
|
||||
continue;
|
||||
}
|
||||
c.messages.push(stored(r.plain, hash));
|
||||
c.updated = now;
|
||||
}
|
||||
for (const [k, exp] of Object.entries(c.seen)) if (exp < now - 86_400) delete c.seen[k];
|
||||
if (newest > 0) c.since = Math.max(c.since, Math.min(newest, now) - OVERLAP);
|
||||
saveConversation(c);
|
||||
return rejected;
|
||||
}
|
||||
|
||||
export async function showConversation(author: string, id: string, secret: string): Promise<void> {
|
||||
const gen = state.generation;
|
||||
const root = app();
|
||||
clear(root);
|
||||
|
||||
let c = getConversation(author, id);
|
||||
if (c && c.secret !== secret) c = undefined; // a link for a different thread of the same listing
|
||||
if (!c) {
|
||||
c = {
|
||||
author, id, secret, title: "", created: nowSeconds(), updated: nowSeconds(),
|
||||
messages: [], since: nowSeconds() - 14 * 86_400, seen: {},
|
||||
};
|
||||
}
|
||||
const conv = c;
|
||||
|
||||
const heading = h("h1", null, conv.title ? t("chat.title", { title: conv.title }) : t("chat.untitled", { id: id.slice(0, 8) }));
|
||||
const list = h("ul", { class: "thread", "aria-live": "polite" });
|
||||
const notes = h("div", null);
|
||||
const composeSlot = h("div", null);
|
||||
const link = location.origin + location.pathname + conversationHash(author, id, secret);
|
||||
|
||||
append(root, [
|
||||
h("a", { class: "back", href: `#/l/${author}/${id}` }, t("chat.back")),
|
||||
" ",
|
||||
h("a", { class: "back", href: "#/messages" }, t("chat.all")),
|
||||
heading,
|
||||
!isPersistent() && h("p", { class: "error" }, t("chat.noStorage")),
|
||||
notes,
|
||||
list,
|
||||
composeSlot,
|
||||
h(
|
||||
"section",
|
||||
{ class: "panel" },
|
||||
h("h2", null, t("chat.link")),
|
||||
h("p", { class: "muted" }, t("chat.linkHelp")),
|
||||
h("input", { class: "mono", readonly: true, value: link, "aria-label": t("chat.link"), onfocus: (e) => (e.target as HTMLInputElement).select() }),
|
||||
),
|
||||
deleteControl(conv),
|
||||
]);
|
||||
|
||||
let listing: Listing | null = null;
|
||||
let listingProblem: Key | null = null;
|
||||
|
||||
const render = (rejected: number, pollFailed: boolean) => {
|
||||
const now = nowSeconds();
|
||||
clear(list);
|
||||
clear(notes);
|
||||
const shown = [...conv.messages]
|
||||
.sort((a, b) => a.sent_at - b.sent_at || (a.dir === "out" ? -1 : 1))
|
||||
.filter((m) => !(m.t === "grant" && (m.valid_until ?? 0) <= now));
|
||||
const expired = conv.messages.filter((m) => m.t === "grant" && (m.valid_until ?? 0) <= now).length;
|
||||
for (const m of shown) list.append(bubble(m));
|
||||
if (!conv.messages.some((m) => m.dir === "in")) list.append(h("li", { class: "muted" }, t("chat.empty")));
|
||||
if (expired) notes.append(h("p", { class: "muted" }, t("grant.expired")));
|
||||
if (rejected) notes.append(h("p", { class: "error" }, t("chat.rejected", { n: rejected })));
|
||||
if (pollFailed) notes.append(h("p", { class: "error" }, t("chat.pollError")));
|
||||
if (listingProblem) notes.append(h("p", { class: "muted" }, t(listingProblem)));
|
||||
if (conv.messages.some((m) => m.dir === "in")) notes.append(h("p", { class: "muted small" }, t("chat.limit")));
|
||||
};
|
||||
|
||||
const renderComposer = () => {
|
||||
clear(composeSlot);
|
||||
if (!listing) return;
|
||||
const repliedTo = () => conv.messages.some((m) => m.dir === "in");
|
||||
composeSlot.append(
|
||||
h(
|
||||
"section",
|
||||
{ class: "panel" },
|
||||
h("h2", null, t("chat.reply")),
|
||||
!repliedTo() && h("p", { class: "muted" }, t("chat.replyRules")),
|
||||
composer({
|
||||
first: () => !repliedTo(),
|
||||
button: "contact.send",
|
||||
send: async (text) => {
|
||||
await sendTo(conv, listing!, text, !repliedTo());
|
||||
if (gen === state.generation) {
|
||||
render(0, false);
|
||||
renderComposer();
|
||||
}
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
render(0, false);
|
||||
|
||||
// The listing gives us the device key to write to and, for a conversation
|
||||
// opened from a bare link, its title. Replies can be read without it.
|
||||
void (async () => {
|
||||
try {
|
||||
const raw = await getListing(author, id);
|
||||
if (gen !== state.generation) return;
|
||||
if (raw === null) {
|
||||
listingProblem = "chat.gone";
|
||||
} else {
|
||||
const l = raw as Listing;
|
||||
const v = verifyListing(raw, verifyOpts());
|
||||
if (v.ok && l.author === author && l.id === id) {
|
||||
listing = l;
|
||||
if (!conv.title && l.title) {
|
||||
conv.title = l.title;
|
||||
heading.textContent = t("chat.title", { title: l.title });
|
||||
if (getConversation(author, id)) saveConversation(conv);
|
||||
}
|
||||
} else {
|
||||
listingProblem = "chat.unverified";
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (gen !== state.generation) return;
|
||||
listingProblem = "chat.unverified";
|
||||
}
|
||||
render(0, false);
|
||||
renderComposer();
|
||||
})();
|
||||
|
||||
const cycle = async () => {
|
||||
if (gen !== state.generation) return;
|
||||
let rejected = 0;
|
||||
let failed = false;
|
||||
try {
|
||||
rejected = await poll(conv);
|
||||
} catch {
|
||||
failed = true;
|
||||
}
|
||||
if (gen !== state.generation) return;
|
||||
render(rejected, failed);
|
||||
setTimeout(() => void cycle(), POLL_MS);
|
||||
};
|
||||
await cycle();
|
||||
}
|
||||
|
||||
function deleteControl(c: Conversation): HTMLElement {
|
||||
const slot = h("p", null);
|
||||
const ask = () => {
|
||||
clear(slot);
|
||||
append(slot, [
|
||||
t("chat.deleteSure"),
|
||||
" ",
|
||||
h("button", { type: "button", class: "btn", onclick: () => { deleteConversation(c.author, c.id); location.hash = "#/messages"; } }, t("chat.deleteYes")),
|
||||
]);
|
||||
};
|
||||
slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("chat.delete")));
|
||||
return slot;
|
||||
}
|
||||
|
||||
// --- all conversations ---------------------------------------------------------------
|
||||
|
||||
export function showInbox(): void {
|
||||
const root = app();
|
||||
clear(root);
|
||||
const convs = listConversations();
|
||||
append(root, [
|
||||
h("a", { class: "back", href: "#/" }, t("detail.back")),
|
||||
h("h1", null, t("inbox.title")),
|
||||
!isPersistent() && h("p", { class: "error" }, t("chat.noStorage")),
|
||||
convs.length === 0
|
||||
? h("p", { class: "muted" }, t("inbox.none"))
|
||||
: h(
|
||||
"ul",
|
||||
{ class: "convs" },
|
||||
...convs.map((c) =>
|
||||
h(
|
||||
"li",
|
||||
{ class: "panel" },
|
||||
h("a", { href: conversationHash(c.author, c.id, c.secret) }, c.title || t("chat.untitled", { id: c.id.slice(0, 8) })),
|
||||
h("div", { class: "muted small" }, t("inbox.last", { date: date(c.updated) })),
|
||||
),
|
||||
),
|
||||
),
|
||||
h("p", { class: "muted" }, t("inbox.note")),
|
||||
]);
|
||||
}
|
||||
+120
-4
@@ -46,8 +46,66 @@ const de = {
|
||||
"detail.location": "Lage (ungefähr, ca. 1 km)",
|
||||
"detail.map": "Auf OpenStreetMap ansehen (externe Seite)",
|
||||
"detail.contact": "Kontakt",
|
||||
"detail.contactSoon":
|
||||
"Der Kontakt zum Anbieter läuft über dessen eigenen Knoten und ist noch nicht verfügbar. Die genaue Adresse wird nie öffentlich verteilt.",
|
||||
"nav.messages": "Meine Nachrichten",
|
||||
"contact.title": "Anbieter kontaktieren",
|
||||
"contact.intro":
|
||||
"Deine Nachricht wird verschlüsselt. Das Netzwerk sieht nur, dass jemand zu dieser Anzeige geschrieben hat, nicht wer und nicht was. Du brauchst kein Konto. Die genaue Adresse gibt der Anbieter selbst frei.",
|
||||
"contact.rules":
|
||||
"Die erste Nachricht muss kurz sein und darf keine Links enthalten. Das schützt vor Betrug; nach der ersten Antwort des Anbieters entfällt es.",
|
||||
"contact.label": "Deine Nachricht",
|
||||
"contact.counter": "{used} / {max} Bytes",
|
||||
"contact.send": "Verschlüsselt senden",
|
||||
"contact.sending": "Wird vorbereitet … (eine kleine Rechenaufgabe gegen Spam)",
|
||||
"contact.already": "Du hast diesem Anbieter schon geschrieben.",
|
||||
"contact.open": "Unterhaltung öffnen",
|
||||
"problem.empty": "Bitte schreibe eine Nachricht.",
|
||||
"problem.long": "Die Nachricht ist zu lang.",
|
||||
"problem.control": "Die Nachricht enthält unerlaubte Sonderzeichen.",
|
||||
"problem.invalid": "Die Nachricht enthält ungültige Zeichen.",
|
||||
"problem.link":
|
||||
"Die erste Nachricht darf keine Links oder Webadressen enthalten (auch kein „Hallo.Ich“ ohne Leerzeichen nach dem Punkt).",
|
||||
"send.404":
|
||||
"Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Gerät gewechselt. Lade die Anzeige neu.",
|
||||
"send.429": "Zu viele Nachrichten. Bitte warte einen Moment.",
|
||||
"send.other": "Senden fehlgeschlagen: {detail}",
|
||||
"send.network": "Der Knoten ist nicht erreichbar.",
|
||||
"chat.back": "← Zur Anzeige",
|
||||
"chat.all": "← Alle Nachrichten",
|
||||
"chat.title": "Unterhaltung zu: {title}",
|
||||
"chat.untitled": "Anzeige {id}",
|
||||
"chat.you": "Du",
|
||||
"chat.owner": "Anbieter",
|
||||
"chat.verified": "Vom Anbieter dieser Anzeige (Signatur geprüft)",
|
||||
"chat.empty":
|
||||
"Noch keine Antwort. Der Anbieter bekommt deine Nachricht, sobald sein Knoten online ist (die Nachricht bleibt bis zu 14 Tage im Netz).",
|
||||
"chat.reply": "Antworten",
|
||||
"chat.replyRules": "Solange der Anbieter nicht geantwortet hat, gelten die Regeln der ersten Nachricht.",
|
||||
"chat.link": "Dein privater Link zu dieser Unterhaltung",
|
||||
"chat.linkHelp":
|
||||
"Setze ein Lesezeichen. Wer diesen Link kennt, kann die Unterhaltung lesen, gib ihn also nicht weiter. Ohne den Link und ohne die Daten dieses Browsers ist die Unterhaltung verloren.",
|
||||
"chat.noStorage":
|
||||
"Dieser Browser speichert hier nichts (privates Fenster?). Die Unterhaltung geht verloren, wenn du die Seite schließt, außer du merkst dir den Link unten.",
|
||||
"chat.gone":
|
||||
"Die Anzeige ist nicht mehr verfügbar. Antworten des Anbieters kannst du weiter empfangen, aber nicht mehr schreiben.",
|
||||
"chat.unverified": "Die Anzeige konnte nicht geprüft werden, daher kannst du gerade nicht schreiben.",
|
||||
"chat.pollError": "Antworten konnten nicht abgerufen werden.",
|
||||
"chat.rejected": "{n} Nachricht(en) im Postfach konnten nicht als echt bestätigt werden und werden ignoriert.",
|
||||
"chat.limit": "Nicht prüfbar: ob der Anbieter sein Gerät inzwischen gesperrt hat.",
|
||||
"chat.delete": "Unterhaltung aus diesem Browser löschen",
|
||||
"chat.deleteSure": "Wirklich löschen? Ohne den Link ist sie dann weg.",
|
||||
"chat.deleteYes": "Ja, löschen",
|
||||
"grant.title": "Adresse vom Anbieter freigegeben",
|
||||
"grant.address": "Adresse",
|
||||
"grant.phone": "Telefon",
|
||||
"grant.email": "E-Mail",
|
||||
"grant.note": "Hinweis des Anbieters",
|
||||
"grant.until": "Angezeigt bis {date}",
|
||||
"grant.expired": "Eine Adressfreigabe des Anbieters ist abgelaufen und wird nicht mehr angezeigt.",
|
||||
"grant.privacy": "Gib diese Angaben nicht weiter.",
|
||||
"inbox.title": "Meine Nachrichten",
|
||||
"inbox.none": "Du hast noch keine Unterhaltungen. Öffne eine Anzeige und schreibe dem Anbieter.",
|
||||
"inbox.last": "Zuletzt: {date}",
|
||||
"inbox.note": "Diese Liste liegt nur in diesem Browser.",
|
||||
"verify.title": "Prüfung in deinem Browser",
|
||||
"verify.intro":
|
||||
"Diese Prüfung läuft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt fälschen.",
|
||||
@@ -112,8 +170,66 @@ const en: Record<keyof typeof de, string> = {
|
||||
"detail.location": "Location (approximate, about 1 km)",
|
||||
"detail.map": "View on OpenStreetMap (external site)",
|
||||
"detail.contact": "Contact",
|
||||
"detail.contactSoon":
|
||||
"Contact goes through the owner's own node and is not available yet. The exact address is never distributed publicly.",
|
||||
"nav.messages": "My messages",
|
||||
"contact.title": "Contact the owner",
|
||||
"contact.intro":
|
||||
"Your message is encrypted. The network only sees that someone wrote about this listing, not who and not what. You need no account. The owner releases the exact address themselves.",
|
||||
"contact.rules":
|
||||
"The first message must be short and must not contain links. This protects against scams; it ends once the owner has replied.",
|
||||
"contact.label": "Your message",
|
||||
"contact.counter": "{used} / {max} bytes",
|
||||
"contact.send": "Send encrypted",
|
||||
"contact.sending": "Preparing … (a small puzzle against spam)",
|
||||
"contact.already": "You have already written to this owner.",
|
||||
"contact.open": "Open conversation",
|
||||
"problem.empty": "Please write a message.",
|
||||
"problem.long": "The message is too long.",
|
||||
"problem.control": "The message contains characters that are not allowed.",
|
||||
"problem.invalid": "The message contains invalid characters.",
|
||||
"problem.link":
|
||||
"The first message must not contain links or web addresses (that includes \"Hello.I\" without a space after the full stop).",
|
||||
"send.404":
|
||||
"This node does not know the listing (anymore), or the owner changed device. Reload the listing.",
|
||||
"send.429": "Too many messages. Please wait a moment.",
|
||||
"send.other": "Sending failed: {detail}",
|
||||
"send.network": "The node is not reachable.",
|
||||
"chat.back": "← Back to the listing",
|
||||
"chat.all": "← All messages",
|
||||
"chat.title": "Conversation about: {title}",
|
||||
"chat.untitled": "Listing {id}",
|
||||
"chat.you": "You",
|
||||
"chat.owner": "Owner",
|
||||
"chat.verified": "From the owner of this listing (signature verified)",
|
||||
"chat.empty":
|
||||
"No reply yet. The owner receives your message once their node is online (it stays in the network for up to 14 days).",
|
||||
"chat.reply": "Reply",
|
||||
"chat.replyRules": "Until the owner has replied, the rules of the first message apply.",
|
||||
"chat.link": "Your private link to this conversation",
|
||||
"chat.linkHelp":
|
||||
"Bookmark it. Anyone who knows this link can read the conversation, so do not share it. Without the link and without this browser's data, the conversation is lost.",
|
||||
"chat.noStorage":
|
||||
"This browser does not store anything here (private window?). The conversation is lost when you close the page unless you keep the link below.",
|
||||
"chat.gone":
|
||||
"The listing is no longer available. You can still receive the owner's replies, but not write any more.",
|
||||
"chat.unverified": "The listing could not be verified, so you cannot write right now.",
|
||||
"chat.pollError": "Replies could not be fetched.",
|
||||
"chat.rejected": "{n} message(s) in the mailbox could not be confirmed as genuine and are ignored.",
|
||||
"chat.limit": "Cannot be checked: whether the owner has since revoked their device.",
|
||||
"chat.delete": "Delete this conversation from this browser",
|
||||
"chat.deleteSure": "Really delete? Without the link it is gone.",
|
||||
"chat.deleteYes": "Yes, delete",
|
||||
"grant.title": "Address released by the owner",
|
||||
"grant.address": "Address",
|
||||
"grant.phone": "Phone",
|
||||
"grant.email": "Email",
|
||||
"grant.note": "Note from the owner",
|
||||
"grant.until": "Shown until {date}",
|
||||
"grant.expired": "An address release from the owner has expired and is no longer shown.",
|
||||
"grant.privacy": "Do not pass these details on.",
|
||||
"inbox.title": "My messages",
|
||||
"inbox.none": "You have no conversations yet. Open a listing and write to the owner.",
|
||||
"inbox.last": "Last activity: {date}",
|
||||
"inbox.note": "This list is kept only in this browser.",
|
||||
"verify.title": "Checked in your browser",
|
||||
"verify.intro":
|
||||
"This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
|
||||
|
||||
+21
-23
@@ -1,8 +1,10 @@
|
||||
import { getListing, getStatus, search, type Status } from "./api.ts";
|
||||
import { getListing, getStatus, search } from "./api.ts";
|
||||
import { append, clear, h } from "./dom.ts";
|
||||
import { date, price, rooms, shortKey } from "./format.ts";
|
||||
import { decodeGeohash } from "./geohash.ts";
|
||||
import { lang, t, type Key } from "./i18n.ts";
|
||||
import { contactPanel, showConversation, showInbox } from "./chat.ts";
|
||||
import { state, verifyOpts } from "./state.ts";
|
||||
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
|
||||
|
||||
const PAGE = 20;
|
||||
@@ -10,17 +12,9 @@ const GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
|
||||
|
||||
const app = document.getElementById("app")!;
|
||||
const statusEl = document.getElementById("status")!;
|
||||
// Not called `status`: that would collide with the built-in window.status.
|
||||
let nodeInfo: Status | null = null;
|
||||
/** Bumped on every navigation so late responses for an old view are dropped. */
|
||||
let generation = 0;
|
||||
|
||||
// --- helpers --------------------------------------------------------------
|
||||
|
||||
function verifyOpts() {
|
||||
return { now: Math.floor(Date.now() / 1000), minPowBits: nodeInfo?.difficulty ?? 0 };
|
||||
}
|
||||
|
||||
/** Translates a value from a listing if it is a known one; unknown values are shown as plain text. */
|
||||
function label(prefix: "kind" | "cat", value: string | undefined): string {
|
||||
if (!value) return "";
|
||||
@@ -78,7 +72,7 @@ function select(name: string, current: string, options: [string, string][]): HTM
|
||||
|
||||
function searchForm(params: URLSearchParams): HTMLFormElement {
|
||||
const get = (k: string) => params.get(k) ?? "";
|
||||
const regions = h("datalist", { id: "regions" }, ...(nodeInfo?.regions ?? []).map((r) => h("option", { value: r })));
|
||||
const regions = h("datalist", { id: "regions" }, ...(state.node?.regions ?? []).map((r) => h("option", { value: r })));
|
||||
const form = h(
|
||||
"form",
|
||||
{ class: "filters" },
|
||||
@@ -95,7 +89,7 @@ function searchForm(params: URLSearchParams): HTMLFormElement {
|
||||
),
|
||||
field(
|
||||
t("filter.region"),
|
||||
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: nodeInfo?.regions[0] ?? "u1x" }),
|
||||
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: state.node?.regions[0] ?? "u1x" }),
|
||||
t("filter.regionHint"),
|
||||
),
|
||||
field(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
|
||||
@@ -160,12 +154,12 @@ async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement):
|
||||
paged.set("offset", String(offset));
|
||||
items = await search(paged);
|
||||
} catch {
|
||||
if (gen !== generation) return;
|
||||
if (gen !== state.generation) return;
|
||||
clear(foot);
|
||||
foot.append(h("p", { class: "error" }, t("results.error")));
|
||||
return;
|
||||
}
|
||||
if (gen !== generation) return;
|
||||
if (gen !== state.generation) return;
|
||||
|
||||
const opts = verifyOpts();
|
||||
for (const raw of items) {
|
||||
@@ -190,7 +184,7 @@ async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement):
|
||||
}
|
||||
|
||||
function showSearch(params: URLSearchParams): void {
|
||||
const gen = generation;
|
||||
const gen = state.generation;
|
||||
clear(app);
|
||||
const results = h("div", { class: "results", "aria-live": "polite" });
|
||||
app.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
|
||||
@@ -288,12 +282,12 @@ function listingBody(l: Listing): HTMLElement[] {
|
||||
l.features?.length
|
||||
? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f))))
|
||||
: h("span"),
|
||||
h("section", { class: "panel contact" }, h("h2", null, t("detail.contact")), h("p", null, t("detail.contactSoon"))),
|
||||
contactPanel(l),
|
||||
];
|
||||
}
|
||||
|
||||
async function showDetail(author: string, id: string): Promise<void> {
|
||||
const gen = generation;
|
||||
const gen = state.generation;
|
||||
clear(app);
|
||||
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
|
||||
app.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
|
||||
@@ -302,12 +296,12 @@ async function showDetail(author: string, id: string): Promise<void> {
|
||||
try {
|
||||
raw = await getListing(author, id);
|
||||
} catch {
|
||||
if (gen !== generation) return;
|
||||
if (gen !== state.generation) return;
|
||||
clear(body);
|
||||
body.append(h("p", { class: "error" }, t("results.error")));
|
||||
return;
|
||||
}
|
||||
if (gen !== generation) return;
|
||||
if (gen !== state.generation) return;
|
||||
clear(body);
|
||||
|
||||
if (raw === null) {
|
||||
@@ -331,13 +325,16 @@ async function showDetail(author: string, id: string): Promise<void> {
|
||||
// --- boot -----------------------------------------------------------------
|
||||
|
||||
function route(): void {
|
||||
generation++;
|
||||
state.generation++;
|
||||
const hash = location.hash.replace(/^#/, "") || "/";
|
||||
const q = hash.indexOf("?");
|
||||
const path = q < 0 ? hash : hash.slice(0, q);
|
||||
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
|
||||
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
|
||||
const c = /^\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(path);
|
||||
if (m) void showDetail(m[1]!, m[2]!);
|
||||
else if (c) void showConversation(c[1]!, c[2]!, c[3]!);
|
||||
else if (path === "/messages") showInbox();
|
||||
else showSearch(params);
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
@@ -345,12 +342,13 @@ function route(): void {
|
||||
async function boot(): Promise<void> {
|
||||
document.documentElement.lang = lang;
|
||||
document.getElementById("foot")!.textContent = t("footer.text");
|
||||
document.getElementById("nav")!.append(h("a", { href: "#/messages" }, t("nav.messages")));
|
||||
try {
|
||||
nodeInfo = await getStatus();
|
||||
state.node = await getStatus();
|
||||
statusEl.textContent = t("status.line", {
|
||||
listings: nodeInfo.listings,
|
||||
peers: nodeInfo.peers,
|
||||
regions: nodeInfo.regions.join(", "),
|
||||
listings: state.node.listings,
|
||||
peers: state.node.peers,
|
||||
regions: state.node.regions.join(", "),
|
||||
});
|
||||
} catch {
|
||||
statusEl.textContent = t("status.unreachable");
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
// End-to-end encrypted messages, the browser's half. This mirrors
|
||||
// internal/message in Go step for step (see "Messaging" in docs/PROTOCOL.md);
|
||||
// test/message.test.ts checks it against a fixture written by the Go code,
|
||||
// down to the byte.
|
||||
//
|
||||
// The buyer only ever *seals to* the listing's device key and *opens replies*
|
||||
// with a per-conversation thread key, so that is all that is implemented here.
|
||||
|
||||
import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
|
||||
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
||||
import { hkdf } from "@noble/hashes/hkdf.js";
|
||||
import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import { canonicalize } from "./jcs.ts";
|
||||
import {
|
||||
CERT_CONTEXT,
|
||||
MAX_CERT_LIFETIME,
|
||||
hexBytes,
|
||||
isObject,
|
||||
safeInt,
|
||||
signedBy,
|
||||
without,
|
||||
type Cert,
|
||||
} from "./verify.ts";
|
||||
|
||||
export const VERSION = 1;
|
||||
export const MAX_LIFETIME = 14 * 86_400;
|
||||
/** Largest plaintext before padding; one byte is kept for the padding marker. */
|
||||
export const MAX_PLAIN = 4095;
|
||||
export const MAX_FIRST_TEXT = 1000;
|
||||
export const MAX_TEXT = 2000;
|
||||
export const MAX_ADDRESS = 300;
|
||||
export const MAX_PHONE = 40;
|
||||
export const MAX_EMAIL = 120;
|
||||
export const MAX_NOTE = 1000;
|
||||
export const MAX_GRANT_VALIDITY = 30 * 86_400;
|
||||
/** What a node requires unless it says otherwise (it reports it in /status). */
|
||||
export const DEFAULT_MESSAGE_DIFFICULTY = 14;
|
||||
|
||||
const BUCKETS = [512, 1024, 2048, 4096];
|
||||
const TAG = 16;
|
||||
|
||||
const enc = new TextEncoder();
|
||||
const SEAL_INFO = enc.encode("allmende-seal-v1");
|
||||
const MAILBOX_CONTEXT = "allmende-mailbox-v1\n";
|
||||
const REPLY_CONTEXT = "allmende-reply-v1\n";
|
||||
|
||||
export interface Ref {
|
||||
author: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export interface Envelope {
|
||||
v: number;
|
||||
listing: Ref;
|
||||
to: "owner" | "buyer";
|
||||
rcpt: string;
|
||||
epk: string;
|
||||
created_at: number;
|
||||
expires_at: number;
|
||||
ct: string;
|
||||
pow: number;
|
||||
}
|
||||
|
||||
export interface Plain {
|
||||
t: "text" | "grant";
|
||||
thread: string;
|
||||
n: number;
|
||||
sent_at: number;
|
||||
text?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
note?: string;
|
||||
valid_until?: number;
|
||||
listing?: Ref;
|
||||
device?: string;
|
||||
cert?: Cert;
|
||||
sig?: string;
|
||||
}
|
||||
|
||||
// --- bytes ------------------------------------------------------------------
|
||||
|
||||
export function toHex(b: Uint8Array): string {
|
||||
let s = "";
|
||||
for (const x of b) s += x.toString(16).padStart(2, "0");
|
||||
return s;
|
||||
}
|
||||
|
||||
function concat(...parts: Uint8Array[]): Uint8Array {
|
||||
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
||||
let at = 0;
|
||||
for (const p of parts) {
|
||||
out.set(p, at);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const byteLength = (s: string): number => enc.encode(s).length;
|
||||
|
||||
// --- text rules (the same as the owner's node applies) -------------------------
|
||||
|
||||
export type InputProblem = "empty" | "long" | "control" | "invalid" | "link";
|
||||
|
||||
/** Thrown when the text of a message breaks the protocol's rules. */
|
||||
export class InputError extends Error {
|
||||
readonly problem: InputProblem;
|
||||
constructor(problem: InputProblem) {
|
||||
super(`message text rejected: ${problem}`);
|
||||
this.problem = problem;
|
||||
}
|
||||
}
|
||||
|
||||
// label.tld in any script; "z. B." and "etc." do not match, "Hallo.Ich" does.
|
||||
const HOSTNAME = /[\p{L}\p{N}-]+\.\p{L}{2,}/u;
|
||||
|
||||
/** A heuristic for URLs and addresses; a speed bump against scams, not a guarantee. */
|
||||
export function containsLink(s: string): boolean {
|
||||
const l = s.toLowerCase();
|
||||
return l.includes("://") || l.includes("www.") || HOSTNAME.test(l);
|
||||
}
|
||||
|
||||
/** Checks a buyer's text. `first` applies while the owner has not replied yet. */
|
||||
export function checkBuyerText(text: string, first: boolean): InputProblem | null {
|
||||
if (text.length === 0) return "empty";
|
||||
if (/\p{Cs}/u.test(text)) return "invalid";
|
||||
if (/[\p{Cc}]/u.test(text.replace(/\n/g, ""))) return "control";
|
||||
if (byteLength(text) > (first ? MAX_FIRST_TEXT : MAX_TEXT)) return "long";
|
||||
if (first && containsLink(text)) return "link";
|
||||
return null;
|
||||
}
|
||||
|
||||
function validField(s: unknown, maxBytes: number, min: number, newlines: boolean): boolean {
|
||||
if (typeof s !== "string") return false;
|
||||
if (s.length < min || byteLength(s) > maxBytes) return false;
|
||||
if (/\p{Cs}/u.test(s)) return false;
|
||||
return !/[\p{Cc}]/u.test(newlines ? s.replace(/\n/g, "") : s);
|
||||
}
|
||||
|
||||
// --- keys -------------------------------------------------------------------
|
||||
|
||||
/** A fresh thread secret (X25519). One per conversation, never reused. */
|
||||
export function newThreadSecret(): Uint8Array {
|
||||
return x25519.utils.randomSecretKey();
|
||||
}
|
||||
|
||||
export function threadPublic(secret: Uint8Array): string {
|
||||
return toHex(x25519.getPublicKey(secret));
|
||||
}
|
||||
|
||||
/** The tag replies are addressed to: the thread key itself never goes on the wire. */
|
||||
export function mailbox(threadPubHex: string): string {
|
||||
const pub = hexBytes(threadPubHex, 32);
|
||||
if (!pub) throw new Error("bad thread key");
|
||||
return toHex(sha256(concat(enc.encode(MAILBOX_CONTEXT), pub)).slice(0, 16));
|
||||
}
|
||||
|
||||
/** The envelope's identity: sha256 of its canonical bytes, hex. */
|
||||
export function envelopeHash(env: Envelope): string {
|
||||
return toHex(sha256(enc.encode(canonicalize(env))));
|
||||
}
|
||||
|
||||
// --- sealing ----------------------------------------------------------------
|
||||
|
||||
function pad(b: Uint8Array): Uint8Array {
|
||||
if (b.length > MAX_PLAIN) throw new InputError("long");
|
||||
const size = BUCKETS.find((s) => b.length + 1 <= s) ?? BUCKETS[BUCKETS.length - 1]!;
|
||||
const out = new Uint8Array(size);
|
||||
out.set(b);
|
||||
out[b.length] = 0x80;
|
||||
return out;
|
||||
}
|
||||
|
||||
function unpad(b: Uint8Array): Uint8Array {
|
||||
let end = b.length;
|
||||
while (end > 0 && b[end - 1] === 0) end--;
|
||||
if (end === 0 || b[end - 1] !== 0x80) throw new Error("bad padding");
|
||||
return b.slice(0, end - 1);
|
||||
}
|
||||
|
||||
function aead(shared: Uint8Array, epk: Uint8Array, rpk: Uint8Array, header: unknown) {
|
||||
const key = hkdf(sha256, shared, concat(epk, rpk), SEAL_INFO, 32);
|
||||
return chacha20poly1305(key, new Uint8Array(12), enc.encode(canonicalize(header)));
|
||||
}
|
||||
|
||||
interface Header {
|
||||
v: number;
|
||||
listing: Ref;
|
||||
to: string;
|
||||
rcpt: string;
|
||||
epk: string;
|
||||
created_at: number;
|
||||
expires_at: number;
|
||||
}
|
||||
|
||||
function headerOf(e: Envelope): Header {
|
||||
return {
|
||||
v: e.v,
|
||||
listing: { author: e.listing.author, id: e.listing.id },
|
||||
to: e.to,
|
||||
rcpt: e.rcpt,
|
||||
epk: e.epk,
|
||||
created_at: e.created_at,
|
||||
expires_at: e.expires_at,
|
||||
};
|
||||
}
|
||||
|
||||
const tick = () => new Promise<void>((r) => setTimeout(r, 0));
|
||||
|
||||
/**
|
||||
* Finds a proof-of-work nonce: sha256 of the canonical envelope has at least
|
||||
* `difficulty` leading zero bits. Only `pow` changes between attempts, so the
|
||||
* canonical text is split once around it and the shared prefix is hashed once.
|
||||
* Yields to the page now and then so it stays responsive.
|
||||
*/
|
||||
async function mine(env: Envelope, difficulty: number): Promise<void> {
|
||||
const canon = canonicalize({ ...env, pow: 0 });
|
||||
const marker = '"pow":0,';
|
||||
const at = canon.indexOf(marker);
|
||||
if (at < 0 || canon.indexOf(marker, at + 1) >= 0) throw new Error("unexpected envelope shape");
|
||||
const prefix = sha256.create().update(enc.encode(canon.slice(0, at + 6)));
|
||||
const suffix = enc.encode(canon.slice(at + 7));
|
||||
for (let n = 0; n <= Number.MAX_SAFE_INTEGER; n++) {
|
||||
const sum = prefix.clone().update(enc.encode(String(n))).update(suffix).digest();
|
||||
if (zeroBits(sum) >= difficulty) {
|
||||
env.pow = n;
|
||||
return;
|
||||
}
|
||||
if (n % 2048 === 2047) await tick();
|
||||
}
|
||||
throw new Error("proof-of-work exhausted");
|
||||
}
|
||||
|
||||
function zeroBits(b: Uint8Array): number {
|
||||
let n = 0;
|
||||
for (const x of b) {
|
||||
if (x === 0) {
|
||||
n += 8;
|
||||
continue;
|
||||
}
|
||||
return n + Math.clz32(x) - 24;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
export interface BuildArgs {
|
||||
/** The listing being written about; only its author, id and device are used. */
|
||||
listing: { author: string; id: string; device: string };
|
||||
threadSecret: Uint8Array;
|
||||
text: string;
|
||||
/** This message's counter in the conversation, from 1. */
|
||||
n: number;
|
||||
/** Unix seconds. */
|
||||
now: number;
|
||||
difficulty: number;
|
||||
/** True until the owner has replied: shorter, and no links. */
|
||||
first: boolean;
|
||||
/** Fixed ephemeral secret; only the golden tests pass this. */
|
||||
esk?: Uint8Array;
|
||||
}
|
||||
|
||||
/** Seals a buyer's message to the listing's device key and mines its proof-of-work. */
|
||||
export async function buildToOwner(a: BuildArgs): Promise<Envelope> {
|
||||
const problem = checkBuyerText(a.text, a.first);
|
||||
if (problem) throw new InputError(problem);
|
||||
|
||||
const devicePub = hexBytes(a.listing.device, 32);
|
||||
if (!devicePub) throw new Error("bad device key");
|
||||
|
||||
const plain: Plain = { t: "text", thread: threadPublic(a.threadSecret), n: a.n, sent_at: a.now, text: a.text };
|
||||
return sealEnvelope({
|
||||
listing: { author: a.listing.author, id: a.listing.id },
|
||||
to: "owner",
|
||||
rcpt: a.listing.device,
|
||||
rpk: ed25519.utils.toMontgomery(devicePub),
|
||||
body: enc.encode(canonicalize(plain)),
|
||||
now: a.now,
|
||||
difficulty: a.difficulty,
|
||||
esk: a.esk,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypts `body` to the X25519 key `rpk`, wraps it in an envelope and mines
|
||||
* its proof-of-work. The browser only sends to owners (see buildToOwner); the
|
||||
* other direction exists so tests can play the owner.
|
||||
*/
|
||||
export async function sealEnvelope(a: {
|
||||
listing: Ref;
|
||||
to: "owner" | "buyer";
|
||||
rcpt: string;
|
||||
rpk: Uint8Array;
|
||||
body: Uint8Array;
|
||||
now: number;
|
||||
difficulty: number;
|
||||
esk?: Uint8Array;
|
||||
}): Promise<Envelope> {
|
||||
const esk = a.esk ?? x25519.utils.randomSecretKey();
|
||||
const epk = x25519.getPublicKey(esk);
|
||||
const env: Envelope = {
|
||||
v: VERSION,
|
||||
listing: { author: a.listing.author, id: a.listing.id },
|
||||
to: a.to,
|
||||
rcpt: a.rcpt,
|
||||
epk: toHex(epk),
|
||||
created_at: a.now,
|
||||
expires_at: a.now + MAX_LIFETIME,
|
||||
ct: "",
|
||||
pow: 0,
|
||||
};
|
||||
const shared = x25519.getSharedSecret(esk, a.rpk); // throws for a low-order key
|
||||
env.ct = toHex(aead(shared, epk, a.rpk, headerOf(env)).encrypt(pad(a.body)));
|
||||
await mine(env, a.difficulty);
|
||||
return env;
|
||||
}
|
||||
|
||||
// --- opening replies -----------------------------------------------------------
|
||||
|
||||
export type Opened = { ok: true; plain: Plain } | { ok: false; error: string };
|
||||
|
||||
const fail = (error: string): Opened => ({ ok: false, error });
|
||||
|
||||
/**
|
||||
* Decrypts an envelope from the mailbox and verifies it is a genuine reply
|
||||
* from the owner of `expect`'s listing: the plaintext decodes canonically, the
|
||||
* certificate chains to the listing's author, and the signature covers the
|
||||
* listing and this thread. Never throws.
|
||||
*
|
||||
* Like the listing check, it cannot know whether the owner's device was
|
||||
* revoked since.
|
||||
*/
|
||||
export function openReply(input: unknown, threadSecret: Uint8Array, expect: Ref): Opened {
|
||||
try {
|
||||
return open(input, threadSecret, expect);
|
||||
} catch (e) {
|
||||
return fail(e instanceof Error ? e.message : "unreadable");
|
||||
}
|
||||
}
|
||||
|
||||
function open(input: unknown, threadSecret: Uint8Array, expect: Ref): Opened {
|
||||
if (!isObject(input) || !isObject(input.listing)) return fail("not an envelope");
|
||||
const e = input as unknown as Envelope;
|
||||
const threadPub = threadPublic(threadSecret);
|
||||
const epk = hexBytes(e.epk, 32);
|
||||
const ct = typeof e.ct === "string" && /^[0-9a-f]*$/.test(e.ct) && e.ct.length % 2 === 0 ? hexBytes(e.ct, e.ct.length / 2) : null;
|
||||
if (
|
||||
e.v !== VERSION ||
|
||||
e.to !== "buyer" ||
|
||||
e.rcpt !== mailbox(threadPub) ||
|
||||
!epk ||
|
||||
!ct ||
|
||||
ct.length < TAG + 1 ||
|
||||
ct.length > BUCKETS[BUCKETS.length - 1]! + TAG ||
|
||||
!safeInt(e.created_at) ||
|
||||
!safeInt(e.expires_at)
|
||||
) {
|
||||
return fail("not a reply for this conversation");
|
||||
}
|
||||
if (e.listing.author !== expect.author || e.listing.id !== expect.id) {
|
||||
return fail("reply refers to another listing");
|
||||
}
|
||||
|
||||
const rpk = x25519.getPublicKey(threadSecret);
|
||||
const shared = x25519.getSharedSecret(threadSecret, epk);
|
||||
let body: Uint8Array;
|
||||
try {
|
||||
body = unpad(aead(shared, epk, rpk, headerOf(e)).decrypt(ct));
|
||||
} catch {
|
||||
return fail("cannot decrypt");
|
||||
}
|
||||
const text = new TextDecoder("utf-8", { fatal: true }).decode(body);
|
||||
const p: unknown = JSON.parse(text);
|
||||
// Canonical only: nothing unknown or oddly spelled hides in the plaintext.
|
||||
if (canonicalize(p) !== text) return fail("plaintext is not canonical");
|
||||
const bad = checkOwnerPlain(p);
|
||||
if (bad) return fail(bad);
|
||||
const plain = p as Plain;
|
||||
|
||||
if (plain.thread !== threadPub) return fail("reply belongs to another thread");
|
||||
if (plain.listing!.author !== e.listing.author || plain.listing!.id !== e.listing.id) {
|
||||
return fail("reply refers to another listing");
|
||||
}
|
||||
const c = plain.cert!;
|
||||
const certOk =
|
||||
c.v === 1 &&
|
||||
hexBytes(c.author, 32) !== null &&
|
||||
hexBytes(c.device, 32) !== null &&
|
||||
safeInt(c.issued_at) &&
|
||||
safeInt(c.expires_at) &&
|
||||
c.expires_at > c.issued_at &&
|
||||
c.expires_at - c.issued_at <= MAX_CERT_LIFETIME &&
|
||||
signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
|
||||
if (!certOk) return fail("bad certificate");
|
||||
if (c.author !== plain.listing!.author || c.device !== plain.device) {
|
||||
return fail("certificate does not match the listing's author and the device");
|
||||
}
|
||||
if (!(c.issued_at <= plain.sent_at && plain.sent_at < c.expires_at)) {
|
||||
return fail("sent outside the certificate's validity");
|
||||
}
|
||||
if (!signedBy(REPLY_CONTEXT, without(plain, "sig"), plain.sig, plain.device)) {
|
||||
return fail("bad signature");
|
||||
}
|
||||
return { ok: true, plain };
|
||||
}
|
||||
|
||||
/** Structure of an owner's plaintext, as internal/message Plain.validate(ToBuyer). */
|
||||
function checkOwnerPlain(p: unknown): string | null {
|
||||
if (!isObject(p)) return "plaintext is not an object";
|
||||
const q = p as unknown as Plain;
|
||||
if (hexBytes(q.thread, 32) === null) return "bad thread";
|
||||
if (!safeInt(q.n) || q.n < 1 || !safeInt(q.sent_at) || q.sent_at <= 0) return "bad counter or time";
|
||||
if (
|
||||
!isObject(q.listing) ||
|
||||
hexBytes(q.listing.author, 32) === null ||
|
||||
hexBytes(q.listing.id, 16) === null ||
|
||||
hexBytes(q.device, 32) === null ||
|
||||
!isObject(q.cert) ||
|
||||
hexBytes(q.sig, 64) === null
|
||||
) {
|
||||
return "reply is not signed";
|
||||
}
|
||||
const grantFields = q.address !== undefined || q.phone !== undefined || q.email !== undefined ||
|
||||
q.note !== undefined || q.valid_until !== undefined;
|
||||
if (q.t === "text") {
|
||||
if (grantFields) return "text with grant fields";
|
||||
return validField(q.text, MAX_TEXT, 1, true) ? null : "bad text";
|
||||
}
|
||||
if (q.t === "grant") {
|
||||
if (q.text !== undefined) return "a grant carries its words in note";
|
||||
if (!validField(q.address, MAX_ADDRESS, 1, true)) return "bad address";
|
||||
if (q.phone !== undefined && !validField(q.phone, MAX_PHONE, 1, false)) return "bad phone";
|
||||
if (q.email !== undefined && !validField(q.email, MAX_EMAIL, 1, false)) return "bad email";
|
||||
if (q.note !== undefined && !validField(q.note, MAX_NOTE, 1, true)) return "bad note";
|
||||
if (!safeInt(q.valid_until) || q.valid_until <= q.sent_at || q.valid_until - q.sent_at > MAX_GRANT_VALIDITY) {
|
||||
return "bad validity of the grant";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return "unknown type";
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// State shared by the views. Kept apart from main.ts so views can live in
|
||||
// their own modules without importing each other in circles.
|
||||
|
||||
import type { Status } from "./api.ts";
|
||||
|
||||
export const state = {
|
||||
/** What the node that served this page says about itself; null until known. */
|
||||
node: null as Status | null,
|
||||
/** Bumped on every navigation so late responses for an old view are dropped. */
|
||||
generation: 0,
|
||||
};
|
||||
|
||||
export function nowSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
/** Options for verifying a listing against what this node says the network requires. */
|
||||
export function verifyOpts(): { now: number; minPowBits: number } {
|
||||
return { now: nowSeconds(), minPowBits: state.node?.difficulty ?? 0 };
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// The buyer's conversations, kept in this browser only. There are no accounts:
|
||||
// a conversation is its thread key, which is also in the private link the
|
||||
// buyer can bookmark. Losing both loses the conversation, by design.
|
||||
//
|
||||
// Browser storage can be missing (private windows, blocked site data), so every
|
||||
// access is guarded and the page keeps working from memory.
|
||||
|
||||
export interface StoredMessage {
|
||||
dir: "in" | "out";
|
||||
n: number;
|
||||
sent_at: number;
|
||||
t: "text" | "grant";
|
||||
text?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
note?: string;
|
||||
valid_until?: number;
|
||||
/** Envelope hash, for messages received from the owner. */
|
||||
hash?: string;
|
||||
}
|
||||
|
||||
export interface Conversation {
|
||||
author: string;
|
||||
id: string;
|
||||
/** The thread secret, hex. */
|
||||
secret: string;
|
||||
title: string;
|
||||
created: number;
|
||||
updated: number;
|
||||
messages: StoredMessage[];
|
||||
/** Mailbox poll position (unix seconds). */
|
||||
since: number;
|
||||
/** Envelopes already looked at (hash -> their expiry), so they are not verified again. */
|
||||
seen: Record<string, number>;
|
||||
}
|
||||
|
||||
const KEY = "allmende.conversations.v1";
|
||||
|
||||
const cache = new Map<string, Conversation>();
|
||||
let loaded = false;
|
||||
let persistent = true;
|
||||
|
||||
const idOf = (author: string, id: string) => `${author}/${id}`;
|
||||
const HEX = (n: number) => new RegExp(`^[0-9a-f]{${n}}$`);
|
||||
|
||||
function wellFormed(c: unknown): c is Conversation {
|
||||
if (typeof c !== "object" || c === null) return false;
|
||||
const x = c as Record<string, unknown>;
|
||||
return (
|
||||
typeof x.author === "string" && HEX(64).test(x.author) &&
|
||||
typeof x.id === "string" && HEX(32).test(x.id) &&
|
||||
typeof x.secret === "string" && HEX(64).test(x.secret) &&
|
||||
typeof x.title === "string" &&
|
||||
typeof x.created === "number" && typeof x.updated === "number" &&
|
||||
Array.isArray(x.messages) && typeof x.since === "number" &&
|
||||
typeof x.seen === "object" && x.seen !== null
|
||||
);
|
||||
}
|
||||
|
||||
function load(): void {
|
||||
if (loaded) return;
|
||||
loaded = true;
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY);
|
||||
if (!raw) return;
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (typeof parsed !== "object" || parsed === null) return;
|
||||
for (const c of Object.values(parsed)) {
|
||||
if (wellFormed(c)) cache.set(idOf(c.author, c.id), c);
|
||||
}
|
||||
} catch {
|
||||
persistent = false;
|
||||
}
|
||||
}
|
||||
|
||||
function flush(): void {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(Object.fromEntries(cache)));
|
||||
} catch {
|
||||
persistent = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** False when this browser refuses to store anything, so conversations vanish with the page. */
|
||||
export function isPersistent(): boolean {
|
||||
load();
|
||||
if (persistent) {
|
||||
try {
|
||||
localStorage.setItem(KEY + ".probe", "1");
|
||||
localStorage.removeItem(KEY + ".probe");
|
||||
} catch {
|
||||
persistent = false;
|
||||
}
|
||||
}
|
||||
return persistent;
|
||||
}
|
||||
|
||||
export function getConversation(author: string, id: string): Conversation | undefined {
|
||||
load();
|
||||
return cache.get(idOf(author, id));
|
||||
}
|
||||
|
||||
export function saveConversation(c: Conversation): void {
|
||||
load();
|
||||
cache.set(idOf(c.author, c.id), c);
|
||||
flush();
|
||||
}
|
||||
|
||||
export function deleteConversation(author: string, id: string): void {
|
||||
load();
|
||||
cache.delete(idOf(author, id));
|
||||
flush();
|
||||
}
|
||||
|
||||
/** Most recently active first. */
|
||||
export function listConversations(): Conversation[] {
|
||||
load();
|
||||
return [...cache.values()].sort((a, b) => b.updated - a.updated);
|
||||
}
|
||||
|
||||
/** The private link to a conversation. The secret stays in the URL fragment, which is never sent to a server. */
|
||||
export function conversationHash(author: string, id: string, secret: string): string {
|
||||
return `#/c/${author}/${id}/${secret}`;
|
||||
}
|
||||
+7
-7
@@ -11,10 +11,10 @@ import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import { canonicalize } from "./jcs.ts";
|
||||
|
||||
const LISTING_CONTEXT = "allmende-listing-v1\n";
|
||||
const CERT_CONTEXT = "allmende-cert-v1\n";
|
||||
export const CERT_CONTEXT = "allmende-cert-v1\n";
|
||||
|
||||
const DAY = 86_400;
|
||||
const MAX_CERT_LIFETIME = 366 * DAY;
|
||||
export const MAX_CERT_LIFETIME = 366 * DAY;
|
||||
const MAX_LISTING_LIFETIME = 30 * DAY;
|
||||
const MAX_CLOCK_SKEW = 10 * 60;
|
||||
|
||||
@@ -87,7 +87,7 @@ export interface Options {
|
||||
|
||||
const enc = new TextEncoder();
|
||||
|
||||
function hexBytes(s: unknown, bytes: number): Uint8Array | null {
|
||||
export function hexBytes(s: unknown, bytes: number): Uint8Array | null {
|
||||
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
|
||||
return null;
|
||||
}
|
||||
@@ -108,21 +108,21 @@ export function leadingZeroBits(bytes: Uint8Array): number {
|
||||
return n;
|
||||
}
|
||||
|
||||
function without(o: object, key: string): Record<string, unknown> {
|
||||
export function without(o: object, key: string): Record<string, unknown> {
|
||||
const copy = { ...(o as Record<string, unknown>) };
|
||||
delete copy[key];
|
||||
return copy;
|
||||
}
|
||||
|
||||
function isObject(v: unknown): v is Record<string, unknown> {
|
||||
export function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function safeInt(v: unknown): v is number {
|
||||
export function safeInt(v: unknown): v is number {
|
||||
return typeof v === "number" && Number.isSafeInteger(v);
|
||||
}
|
||||
|
||||
function signedBy(
|
||||
export function signedBy(
|
||||
context: string,
|
||||
signed: unknown,
|
||||
sigHex: unknown,
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<body>
|
||||
<header class="top">
|
||||
<a class="brand" href="#/">Allmende</a>
|
||||
<nav id="nav" class="nav"></nav>
|
||||
<span id="status" class="status"></span>
|
||||
</header>
|
||||
<main id="app"></main>
|
||||
|
||||
@@ -212,3 +212,27 @@ pre {
|
||||
.detail-head { flex-direction: column; }
|
||||
.kv { grid-template-columns: 1fr; }
|
||||
}
|
||||
|
||||
/* Messages */
|
||||
.nav { margin-left: auto; }
|
||||
textarea {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 8px 10px;
|
||||
font: inherit;
|
||||
color: var(--text);
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 8px;
|
||||
resize: vertical;
|
||||
}
|
||||
textarea:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
|
||||
.compose .actions { margin-top: 8px; align-items: center; }
|
||||
.small { font-size: 0.85rem; }
|
||||
.pre { white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; }
|
||||
.thread, .convs { list-style: none; margin: 0 0 16px; padding: 0; display: grid; gap: 10px; }
|
||||
.msg { max-width: 85%; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface); }
|
||||
.msg.out { justify-self: end; border-color: var(--accent); }
|
||||
.msg .who { color: var(--muted); font-size: 0.85rem; margin-bottom: 4px; }
|
||||
.grant { border: 2px solid var(--accent); border-radius: 8px; padding: 10px 12px; margin: 4px 0; }
|
||||
input[readonly] { width: 100%; box-sizing: border-box; }
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { after, before, test } from "node:test";
|
||||
|
||||
import type { Envelope } from "../src/message.ts";
|
||||
import { mailbox } from "../src/message.ts";
|
||||
import { NOW, newParty, openAsOwner, openPage, sealReply, startGateway, type Gateway, type Page } from "./helpers.ts";
|
||||
|
||||
const owner = newParty({ title: "Altbau in Ottensen" });
|
||||
const imposter = newParty();
|
||||
const ref = { author: owner.author, id: owner.listing.id };
|
||||
const detail = `#/l/${ref.author}/${ref.id}`;
|
||||
|
||||
let gw: Gateway;
|
||||
before(async () => {
|
||||
gw = await startGateway({ listings: [owner.listing] });
|
||||
});
|
||||
after(async () => {
|
||||
await gw.close();
|
||||
});
|
||||
|
||||
const text = (p: Page) => p.document.body.textContent ?? "";
|
||||
|
||||
/** Types into the contact form on a listing page and submits it. */
|
||||
async function write(p: Page, message: string): Promise<void> {
|
||||
await p.waitFor(() => p.document.querySelector("textarea") !== null, "the contact form");
|
||||
const area = p.document.querySelector("textarea")!;
|
||||
area.value = message;
|
||||
p.document.querySelector("form.compose")!.dispatchEvent(new p.window.Event("submit", { cancelable: true }));
|
||||
}
|
||||
|
||||
test("a first message is encrypted, mined and sent; the conversation opens", async () => {
|
||||
const before = gw.posted.length;
|
||||
const p = openPage(gw.url, detail);
|
||||
try {
|
||||
await write(p, "Ist die Wohnung noch frei? Viele Grüße");
|
||||
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "the conversation view");
|
||||
assert.equal(gw.posted.length, before + 1);
|
||||
|
||||
const env = JSON.parse(gw.posted[before]!) as Envelope;
|
||||
assert.equal(env.to, "owner");
|
||||
assert.equal(env.rcpt, owner.device);
|
||||
assert.ok(!gw.posted[before]!.includes("Ist die Wohnung"), "plaintext must not leave the browser");
|
||||
const plain = openAsOwner(env, owner);
|
||||
assert.equal(plain.text, "Ist die Wohnung noch frei? Viele Grüße");
|
||||
assert.equal(plain.n, 1);
|
||||
|
||||
const m = /^#\/c\/([0-9a-f]{64})\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(p.window.location.hash);
|
||||
assert.ok(m, "the conversation link has the thread secret in the fragment");
|
||||
assert.equal(m[1], ref.author);
|
||||
|
||||
await p.waitFor(() => text(p).includes("Ist die Wohnung noch frei?"), "own message shown");
|
||||
assert.match(text(p), /Conversation about: Altbau in Ottensen|Listing/);
|
||||
assert.match(text(p), /No reply yet/);
|
||||
assert.ok(p.document.querySelector('input[readonly]'), "the private link is shown");
|
||||
|
||||
// Revisiting the listing offers the conversation instead of a second form.
|
||||
p.window.location.hash = detail;
|
||||
await p.waitFor(() => /already written/.test(text(p)), "already written note");
|
||||
assert.equal(p.document.querySelector("textarea"), null);
|
||||
} finally {
|
||||
p.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("links are refused in a first message, and nothing is sent", async () => {
|
||||
const before = gw.posted.length;
|
||||
const p = openPage(gw.url, detail);
|
||||
try {
|
||||
await write(p, "Schreib mir auf https://evil.example/pay");
|
||||
await p.waitFor(() => /must not contain links/.test(text(p)), "link refusal");
|
||||
assert.equal(gw.posted.length, before);
|
||||
assert.match(p.window.location.hash, /^#\/l\//, "stays on the listing");
|
||||
assert.equal(p.document.querySelector("textarea")!.value, "Schreib mir auf https://evil.example/pay", "the text is kept");
|
||||
} finally {
|
||||
p.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a node that refuses the message is reported and the text is kept", async () => {
|
||||
gw.postFails = { status: 429, error: "slow down" };
|
||||
const p = openPage(gw.url, detail);
|
||||
try {
|
||||
await write(p, "Hallo, noch frei?");
|
||||
await p.waitFor(() => /Too many messages/.test(text(p)), "rate limit message");
|
||||
assert.match(p.window.location.hash, /^#\/l\//);
|
||||
assert.equal(p.document.querySelector("textarea")!.value, "Hallo, noch frei?");
|
||||
} finally {
|
||||
gw.postFails = undefined;
|
||||
p.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("verified replies and grants are shown; forged and expired ones are not", async () => {
|
||||
const secret = "5".repeat(64);
|
||||
// The thread public key follows from the secret; compute it with the same code the page uses.
|
||||
const { threadPublic } = await import("../src/message.ts");
|
||||
const tp = threadPublic(Uint8Array.from(Buffer.from(secret, "hex")));
|
||||
const tag = mailbox(tp);
|
||||
const when = NOW - 1800;
|
||||
|
||||
gw.mailboxes.set(tag, [
|
||||
await sealReply(owner, ref, { t: "text", n: 1, text: "Ja, die Wohnung ist noch frei." }, tp, { now: when }),
|
||||
await sealReply(owner, ref, { t: "grant", n: 2, address: "Musterweg 7, 22765 Hamburg", note: "Klingel: Meyer", valid_until: NOW + 86_400 }, tp, { now: when + 60 }),
|
||||
// an old grant that has lapsed
|
||||
await sealReply(owner, ref, { t: "grant", n: 3, address: "Alte Adresse 1", valid_until: NOW - 10 }, tp, { now: when + 90 }),
|
||||
// a stranger pretending to be the owner
|
||||
await sealReply(owner, ref, { t: "text", n: 4, text: "Bitte Kaution überweisen" }, tp, { signer: imposter, now: when + 120 }),
|
||||
// tampered after signing
|
||||
await sealReply(owner, ref, { t: "text", n: 5, text: "harmlos" }, tp, { now: when + 150, afterSign: (q) => void (q.text = "Zahle an IBAN") }),
|
||||
]);
|
||||
|
||||
const p = openPage(gw.url, `#/c/${ref.author}/${ref.id}/${secret}`);
|
||||
try {
|
||||
await p.waitFor(() => /Musterweg 7/.test(text(p)), "the grant card");
|
||||
const t = text(p);
|
||||
assert.match(t, /Ja, die Wohnung ist noch frei\./);
|
||||
assert.match(t, /Klingel: Meyer/);
|
||||
assert.match(t, /Address released by the owner/);
|
||||
assert.match(t, /signature verified/i);
|
||||
assert.ok(!t.includes("Alte Adresse"), "an expired grant is hidden");
|
||||
assert.match(t, /expired and is no longer shown/);
|
||||
assert.ok(!t.includes("Kaution"), "a forged reply is not shown");
|
||||
assert.ok(!t.includes("IBAN"), "a tampered reply is not shown");
|
||||
assert.match(t, /2 message\(s\) in the mailbox could not be confirmed/);
|
||||
|
||||
// Now that the owner has replied, the reply form allows links.
|
||||
await p.waitFor(() => p.document.querySelector("form.compose") !== null, "reply form");
|
||||
const before = gw.posted.length;
|
||||
p.document.querySelector("textarea")!.value = "Danke! Hier die Unterlagen: https://example.org/x";
|
||||
p.document.querySelector("form.compose")!.dispatchEvent(new p.window.Event("submit", { cancelable: true }));
|
||||
await p.waitFor(() => gw.posted.length === before + 1, "the reply to be sent");
|
||||
const env = JSON.parse(gw.posted[before]!) as Envelope;
|
||||
assert.equal(openAsOwner(env, owner).text, "Danke! Hier die Unterlagen: https://example.org/x");
|
||||
assert.equal(openAsOwner(env, owner).n, 1);
|
||||
} finally {
|
||||
p.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("the conversation list shows stored conversations", async () => {
|
||||
const p = openPage(gw.url, detail);
|
||||
try {
|
||||
await write(p, "Noch eine Frage");
|
||||
await p.waitFor(() => p.window.location.hash.startsWith("#/c/"), "conversation");
|
||||
p.window.location.hash = "#/messages";
|
||||
await p.waitFor(() => p.document.querySelectorAll(".convs li").length === 1, "one conversation listed");
|
||||
assert.match(text(p), /Altbau in Ottensen/);
|
||||
} finally {
|
||||
p.close();
|
||||
}
|
||||
});
|
||||
+142
-7
@@ -1,11 +1,14 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { ed25519 } from "@noble/curves/ed25519.js";
|
||||
import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
|
||||
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
||||
import { hkdf } from "@noble/hashes/hkdf.js";
|
||||
import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import { JSDOM, type DOMWindow } from "jsdom";
|
||||
|
||||
import { canonicalize } from "../src/jcs.ts";
|
||||
import { mailbox, sealEnvelope, type Envelope, type Plain, type Ref } from "../src/message.ts";
|
||||
import { leadingZeroBits, type Listing } from "../src/verify.ts";
|
||||
|
||||
/** The clock the browser sees in these tests (unix seconds). */
|
||||
@@ -15,8 +18,23 @@ export const DIFFICULTY = 8;
|
||||
const enc = new TextEncoder();
|
||||
const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");
|
||||
|
||||
/** An owner: identity and device keys, and the certificate between them. */
|
||||
export interface Party {
|
||||
idKey: Uint8Array;
|
||||
devKey: Uint8Array;
|
||||
cert: Record<string, unknown>;
|
||||
author: string;
|
||||
device: string;
|
||||
listing: Listing;
|
||||
}
|
||||
|
||||
/** Creates a validly signed listing under a brand-new identity and device. */
|
||||
export function signListing(fields: Record<string, unknown> = {}): Listing {
|
||||
return newParty(fields).listing;
|
||||
}
|
||||
|
||||
/** Like signListing, but keeps the keys so a test can act as the owner. */
|
||||
export function newParty(fields: Record<string, unknown> = {}, certFields: Record<string, unknown> = {}): Party {
|
||||
const idKey = ed25519.utils.randomSecretKey();
|
||||
const devKey = ed25519.utils.randomSecretKey();
|
||||
const cert: Record<string, unknown> = {
|
||||
@@ -25,6 +43,7 @@ export function signListing(fields: Record<string, unknown> = {}): Listing {
|
||||
device: hex(ed25519.getPublicKey(devKey)),
|
||||
issued_at: NOW - 3600,
|
||||
expires_at: NOW + 90 * 86_400,
|
||||
...certFields,
|
||||
};
|
||||
cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey));
|
||||
|
||||
@@ -52,7 +71,97 @@ export function signListing(fields: Record<string, unknown> = {}): Listing {
|
||||
if (leadingZeroBits(sha256(enc.encode(canonicalize(l)))) >= DIFFICULTY) break;
|
||||
}
|
||||
l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey));
|
||||
return l as unknown as Listing;
|
||||
return {
|
||||
idKey,
|
||||
devKey,
|
||||
cert,
|
||||
author: cert.author as string,
|
||||
device: cert.device as string,
|
||||
listing: l as unknown as Listing,
|
||||
};
|
||||
}
|
||||
|
||||
// --- playing the owner -------------------------------------------------------
|
||||
|
||||
/** What an owner's node does with a buyer's envelope: decrypt it with the device key. */
|
||||
export function openAsOwner(env: Envelope, p: Party): Plain {
|
||||
const sk = ed25519.utils.toMontgomerySecret(p.devKey);
|
||||
const epk = fromHex(env.epk);
|
||||
const rpk = x25519.getPublicKey(sk);
|
||||
const key = hkdf(sha256, x25519.getSharedSecret(sk, epk), concatBytes(epk, rpk), enc.encode("allmende-seal-v1"), 32);
|
||||
const aad = enc.encode(
|
||||
canonicalize({
|
||||
v: env.v,
|
||||
listing: env.listing,
|
||||
to: env.to,
|
||||
rcpt: env.rcpt,
|
||||
epk: env.epk,
|
||||
created_at: env.created_at,
|
||||
expires_at: env.expires_at,
|
||||
}),
|
||||
);
|
||||
const padded = chacha20poly1305(key, new Uint8Array(12), aad).decrypt(fromHex(env.ct));
|
||||
let end = padded.length;
|
||||
while (end > 0 && padded[end - 1] === 0) end--;
|
||||
if (padded[end - 1] !== 0x80) throw new Error("bad padding");
|
||||
return JSON.parse(new TextDecoder().decode(padded.slice(0, end - 1))) as Plain;
|
||||
}
|
||||
|
||||
export interface ReplyOptions {
|
||||
/** Edit the plaintext before it is signed (e.g. to build an invalid message). */
|
||||
beforeSign?: (plain: Record<string, unknown>) => void;
|
||||
/** Edit the plaintext after signing (e.g. to break the signature). */
|
||||
afterSign?: (plain: Record<string, unknown>) => void;
|
||||
/** Sign with another party's device key (a forgery). */
|
||||
signer?: Party;
|
||||
now?: number;
|
||||
difficulty?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a reply the way an owner's node does (internal/message SealToBuyer):
|
||||
* signs the plaintext with the device key and seals it to the thread key.
|
||||
*/
|
||||
export async function sealReply(
|
||||
owner: Party,
|
||||
ref: Ref,
|
||||
fields: Record<string, unknown>,
|
||||
threadPub: string,
|
||||
opts: ReplyOptions = {},
|
||||
): Promise<Envelope> {
|
||||
const now = opts.now ?? NOW;
|
||||
const signer = opts.signer ?? owner;
|
||||
const plain: Record<string, unknown> = {
|
||||
thread: threadPub,
|
||||
sent_at: now,
|
||||
listing: ref,
|
||||
device: signer.device,
|
||||
cert: signer.cert,
|
||||
...fields,
|
||||
};
|
||||
opts.beforeSign?.(plain);
|
||||
plain.sig = hex(ed25519.sign(enc.encode("allmende-reply-v1\n" + canonicalize(plain)), signer.devKey));
|
||||
opts.afterSign?.(plain);
|
||||
return sealEnvelope({
|
||||
listing: ref,
|
||||
to: "buyer",
|
||||
rcpt: mailbox(threadPub),
|
||||
rpk: fromHex(threadPub),
|
||||
body: enc.encode(canonicalize(plain)),
|
||||
now,
|
||||
difficulty: opts.difficulty ?? 6,
|
||||
});
|
||||
}
|
||||
|
||||
function fromHex(s: string): Uint8Array {
|
||||
return Uint8Array.from(Buffer.from(s, "hex"));
|
||||
}
|
||||
|
||||
function concatBytes(a: Uint8Array, b: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(a.length + b.length);
|
||||
out.set(a);
|
||||
out.set(b, a.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
// --- a stand-in for a node's HTTP API -------------------------------------
|
||||
@@ -61,6 +170,12 @@ export interface Gateway {
|
||||
url: string;
|
||||
/** Query strings of every /api/v1/listings search received. */
|
||||
queries: string[];
|
||||
/** Bodies of every POST /api/v1/messages, as received. */
|
||||
posted: string[];
|
||||
/** Envelopes served from GET /api/v1/messages?mailbox=<tag>, by tag. Tests fill it. */
|
||||
mailboxes: Map<string, unknown[]>;
|
||||
/** Make POST /api/v1/messages answer with this status and error. */
|
||||
postFails?: { status: number; error: string };
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -73,12 +188,34 @@ export interface GatewayOptions {
|
||||
|
||||
export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
const queries: string[] = [];
|
||||
const posted: string[] = [];
|
||||
const mailboxes = new Map<string, unknown[]>();
|
||||
const gateway: Gateway = {
|
||||
url: "",
|
||||
queries,
|
||||
posted,
|
||||
mailboxes,
|
||||
close: () => new Promise((ok) => server.close(() => ok())),
|
||||
};
|
||||
const server: Server = createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://x");
|
||||
const json = (code: number, body: unknown) => {
|
||||
res.writeHead(code, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(body));
|
||||
};
|
||||
if (url.pathname === "/api/v1/messages") {
|
||||
if (req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
if (gateway.postFails) return json(gateway.postFails.status, { error: gateway.postFails.error });
|
||||
posted.push(body);
|
||||
json(202, { hash: "x" });
|
||||
});
|
||||
return;
|
||||
}
|
||||
return json(200, mailboxes.get(url.searchParams.get("mailbox") ?? "") ?? []);
|
||||
}
|
||||
if (url.pathname === "/api/v1/status") {
|
||||
if (opts.statusFails) return json(500, { error: "down" });
|
||||
return json(200, {
|
||||
@@ -89,6 +226,7 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
peers: 2,
|
||||
listings: opts.listings.length,
|
||||
difficulty: DIFFICULTY,
|
||||
message_difficulty: 6,
|
||||
});
|
||||
}
|
||||
if (url.pathname === "/api/v1/listings") {
|
||||
@@ -105,11 +243,8 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||
});
|
||||
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
return {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
queries,
|
||||
close: () => new Promise((ok) => server.close(() => ok())),
|
||||
};
|
||||
gateway.url = `http://127.0.0.1:${port}`;
|
||||
return gateway;
|
||||
}
|
||||
|
||||
// --- running the real built UI --------------------------------------------
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { test } from "node:test";
|
||||
|
||||
import { canonicalize } from "../src/jcs.ts";
|
||||
import {
|
||||
InputError,
|
||||
buildToOwner,
|
||||
checkBuyerText,
|
||||
containsLink,
|
||||
envelopeHash,
|
||||
mailbox,
|
||||
newThreadSecret,
|
||||
openReply,
|
||||
threadPublic,
|
||||
toHex,
|
||||
type Envelope,
|
||||
} from "../src/message.ts";
|
||||
import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import { leadingZeroBits } from "../src/verify.ts";
|
||||
import { NOW, newParty, openAsOwner, sealReply } from "./helpers.ts";
|
||||
|
||||
// Written by the Go implementation (internal/message): the browser must
|
||||
// reproduce it byte for byte and open what Go sealed.
|
||||
const fx = JSON.parse(
|
||||
readFileSync(new URL("../../internal/message/testdata/fixture.json", import.meta.url), "utf8"),
|
||||
);
|
||||
|
||||
const fromHex = (s: string) => Uint8Array.from(Buffer.from(s, "hex"));
|
||||
const secret = fromHex(fx.thread_secret);
|
||||
const ref = fx.listing as { author: string; id: string };
|
||||
const toBuyer = () => JSON.parse(fx.to_buyer.canonical) as Envelope;
|
||||
|
||||
test("thread key and mailbox tag match Go", () => {
|
||||
assert.equal(threadPublic(secret), fx.thread_public);
|
||||
assert.equal(mailbox(fx.thread_public), fx.mailbox);
|
||||
});
|
||||
|
||||
test("a buyer's envelope is byte-identical to the one Go sealed", async () => {
|
||||
const env = await buildToOwner({
|
||||
listing: { ...ref, device: fx.device },
|
||||
threadSecret: secret,
|
||||
text: fx.to_owner.plain.text,
|
||||
n: 1,
|
||||
now: fx.now,
|
||||
difficulty: fx.difficulty,
|
||||
first: true,
|
||||
esk: fromHex(fx.to_owner.esk),
|
||||
});
|
||||
assert.equal(canonicalize(env), fx.to_owner.canonical);
|
||||
assert.equal(envelopeHash(env), fx.to_owner.hash);
|
||||
assert.ok(leadingZeroBits(sha256(new TextEncoder().encode(canonicalize(env)))) >= fx.difficulty);
|
||||
});
|
||||
|
||||
test("a reply sealed and signed by Go opens and verifies in the browser", () => {
|
||||
const r = openReply(toBuyer(), secret, ref);
|
||||
assert.ok(r.ok, r.ok ? "" : r.error);
|
||||
assert.equal(canonicalize(r.plain), fx.to_buyer.plain_canonical);
|
||||
assert.equal(r.plain.t, "grant");
|
||||
assert.equal(r.plain.address, "Musterstraße 12, 20255 Hamburg");
|
||||
assert.equal(r.plain.note, "Samstag 10 Uhr, bitte zweimal klingeln \u{1F514}");
|
||||
});
|
||||
|
||||
test("tampering with a Go reply is detected", () => {
|
||||
const flip = (c: string) => (c === "0" ? "1" : "0");
|
||||
const cases: Record<string, (e: Envelope) => void> = {
|
||||
"created_at": (e) => void (e.created_at += 1),
|
||||
"expires_at": (e) => void (e.expires_at -= 1),
|
||||
"listing id": (e) => void (e.listing = { ...e.listing, id: "cd".repeat(16) }),
|
||||
"ciphertext": (e) => void (e.ct = flip(e.ct[0]!) + e.ct.slice(1)),
|
||||
"ephemeral key": (e) => void (e.epk = flip(e.epk[0]!) + e.epk.slice(1)),
|
||||
"low-order ephemeral key": (e) => void (e.epk = "00".repeat(32)),
|
||||
"mailbox": (e) => void (e.rcpt = "ab".repeat(16)),
|
||||
"direction": (e) => void (e.to = "owner"),
|
||||
"version": (e) => void (e.v = 2),
|
||||
"uppercase ct": (e) => void (e.ct = e.ct.toUpperCase()),
|
||||
"empty ct": (e) => void (e.ct = ""),
|
||||
};
|
||||
for (const [name, mutate] of Object.entries(cases)) {
|
||||
const e = toBuyer();
|
||||
mutate(e);
|
||||
assert.equal(openReply(e, secret, ref).ok, false, `${name} went unnoticed`);
|
||||
}
|
||||
// Another conversation's key, or the wrong listing, cannot open it either.
|
||||
assert.equal(openReply(toBuyer(), newThreadSecret(), ref).ok, false);
|
||||
assert.equal(openReply(toBuyer(), secret, { ...ref, id: "cd".repeat(16) }).ok, false);
|
||||
assert.equal(openReply(toBuyer(), secret, { ...ref, author: "cd".repeat(32) }).ok, false);
|
||||
for (const junk of [null, 5, "x", [], {}, { listing: 3 }]) {
|
||||
assert.equal(openReply(junk, secret, ref).ok, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("link detection agrees with Go on every vector", () => {
|
||||
assert.ok(fx.links.length >= 10);
|
||||
for (const c of fx.links as { text: string; link: boolean }[]) {
|
||||
assert.equal(containsLink(c.text), c.link, JSON.stringify(c.text));
|
||||
}
|
||||
});
|
||||
|
||||
test("buyer text rules", () => {
|
||||
assert.equal(checkBuyerText("Hallo, ist das noch frei?", true), null);
|
||||
assert.equal(checkBuyerText("", true), "empty");
|
||||
assert.equal(checkBuyerText("schaut https://x.de", true), "link");
|
||||
assert.equal(checkBuyerText("schaut https://x.de", false), null, "links are fine once the owner replied");
|
||||
assert.equal(checkBuyerText("a".repeat(1001), true), "long");
|
||||
assert.equal(checkBuyerText("a".repeat(1001), false), null);
|
||||
assert.equal(checkBuyerText("a".repeat(2001), false), "long");
|
||||
assert.equal(checkBuyerText("ä".repeat(501), true), "long", "limits count UTF-8 bytes, not characters");
|
||||
assert.equal(checkBuyerText("a\u0007b", true), "control");
|
||||
assert.equal(checkBuyerText("a\nb
c", true), null, "newlines and U+2028 are fine");
|
||||
assert.equal(checkBuyerText("a\uD800b", true), "invalid", "a lone surrogate cannot be sent");
|
||||
});
|
||||
|
||||
test("buildToOwner refuses text that breaks the rules", async () => {
|
||||
const o = newParty();
|
||||
const args = { listing: o.listing, threadSecret: newThreadSecret(), n: 1, now: NOW, difficulty: 4, first: true };
|
||||
await assert.rejects(buildToOwner({ ...args, text: "see https://example.com" }), (e) => e instanceof InputError && e.problem === "link");
|
||||
await assert.rejects(buildToOwner({ ...args, text: "" }), (e) => e instanceof InputError && e.problem === "empty");
|
||||
// Even with the owner's relaxed limit, newlines can blow the 4095-byte plaintext.
|
||||
await assert.rejects(buildToOwner({ ...args, first: false, text: "\n".repeat(2000) }), InputError);
|
||||
});
|
||||
|
||||
test("what the browser seals, the owner's device key opens", async () => {
|
||||
const o = newParty();
|
||||
const tk = newThreadSecret();
|
||||
const env = await buildToOwner({
|
||||
listing: o.listing, threadSecret: tk, text: "Ist die Wohnung noch frei? \u{1F3E0}", n: 1, now: NOW, difficulty: 10, first: true,
|
||||
});
|
||||
assert.equal(env.to, "owner");
|
||||
assert.equal(env.rcpt, o.device);
|
||||
assert.ok(leadingZeroBits(sha256(new TextEncoder().encode(canonicalize(env)))) >= 10);
|
||||
assert.ok(canonicalize(env).length < 10 * 1024);
|
||||
assert.ok(!canonicalize(env).includes(threadPublic(tk)), "the thread key must not appear on the wire");
|
||||
|
||||
const p = openAsOwner(env, o);
|
||||
assert.equal(p.text, "Ist die Wohnung noch frei? \u{1F3E0}");
|
||||
assert.equal(p.thread, threadPublic(tk));
|
||||
|
||||
// Different every time: fresh ephemeral key.
|
||||
const again = await buildToOwner({
|
||||
listing: o.listing, threadSecret: tk, text: "Ist die Wohnung noch frei? \u{1F3E0}", n: 1, now: NOW, difficulty: 4, first: true,
|
||||
});
|
||||
assert.notEqual(again.epk, env.epk);
|
||||
assert.notEqual(again.ct, env.ct);
|
||||
});
|
||||
|
||||
test("ciphertext length only reveals a size bucket", async () => {
|
||||
const o = newParty();
|
||||
const size = async (text: string) =>
|
||||
(await buildToOwner({ listing: o.listing, threadSecret: newThreadSecret(), text, n: 1, now: NOW, difficulty: 2, first: false })).ct.length;
|
||||
assert.equal(await size("hi"), await size("x".repeat(250)));
|
||||
assert.equal(await size("hi"), (512 + 16) * 2);
|
||||
assert.ok((await size("x".repeat(900))) > (await size("hi")));
|
||||
});
|
||||
|
||||
// --- replies built by a TypeScript "owner" ------------------------------------
|
||||
|
||||
async function setup() {
|
||||
const owner = newParty();
|
||||
const tk = newThreadSecret();
|
||||
const tp = threadPublic(tk);
|
||||
const lref = { author: owner.author, id: owner.listing.id };
|
||||
return { owner, tk, tp, lref };
|
||||
}
|
||||
|
||||
test("a genuine reply and grant are accepted", async () => {
|
||||
const { owner, tk, tp, lref } = await setup();
|
||||
const text = await sealReply(owner, lref, { t: "text", n: 1, text: "Ja, noch frei." }, tp);
|
||||
const r = openReply(text, tk, lref);
|
||||
assert.ok(r.ok, r.ok ? "" : r.error);
|
||||
assert.equal(r.plain.text, "Ja, noch frei.");
|
||||
|
||||
const grant = await sealReply(
|
||||
owner, lref,
|
||||
{ t: "grant", n: 2, address: "Weg 1, 20095 Hamburg", phone: "+49 40 1", note: "Samstag 10 Uhr", valid_until: NOW + 7 * 86_400 },
|
||||
tp,
|
||||
);
|
||||
const g = openReply(grant, tk, lref);
|
||||
assert.ok(g.ok, g.ok ? "" : g.error);
|
||||
assert.equal(g.plain.address, "Weg 1, 20095 Hamburg");
|
||||
assert.equal(g.plain.valid_until, NOW + 7 * 86_400);
|
||||
});
|
||||
|
||||
test("forgeries and replays are rejected", async () => {
|
||||
const { owner, tk, tp, lref } = await setup();
|
||||
const imposter = newParty();
|
||||
const base = { t: "text", n: 1, text: "Überweisen Sie die Kaution" };
|
||||
|
||||
const expectBad = async (name: string, env: Promise<Envelope>, why: RegExp, expect = lref, key = tk) => {
|
||||
const r = openReply(await env, key, expect);
|
||||
assert.equal(r.ok, false, `${name} was accepted`);
|
||||
if (!r.ok) assert.match(r.error, why, name);
|
||||
};
|
||||
|
||||
// Signed by another identity's device, claiming to be the listing's owner.
|
||||
await expectBad("imposter", sealReply(owner, lref, base, tp, { signer: imposter }), /certificate/);
|
||||
// The signature no longer matches after the content changed.
|
||||
await expectBad("edited after signing", sealReply(owner, lref, base, tp, { afterSign: (p) => void (p.text = "Kaution an IBAN ...") }), /signature/);
|
||||
// A reply for another thread, moved into this one.
|
||||
const other = threadPublic(newThreadSecret());
|
||||
await expectBad("replayed from another thread",
|
||||
sealReply(owner, lref, base, tp, { beforeSign: (p) => void (p.thread = other), afterSign: (p) => void (p.thread = tp) }),
|
||||
/signature/);
|
||||
// Unsigned, or missing parts.
|
||||
await expectBad("no certificate", sealReply(owner, lref, base, tp, { beforeSign: (p) => void delete p.cert }), /not signed/);
|
||||
await expectBad("no listing", sealReply(owner, lref, base, tp, { beforeSign: (p) => void delete p.listing }), /not signed/);
|
||||
// Unknown field: the plaintext must be exactly the canonical form of what is allowed... and signed.
|
||||
await expectBad("unknown type", sealReply(owner, lref, { ...base, t: "image" }, tp), /unknown type/);
|
||||
await expectBad("text with grant fields", sealReply(owner, lref, { ...base, address: "Weg 1" }, tp), /grant fields/);
|
||||
// A certificate that does not cover the message's time.
|
||||
const stale = newParty({}, { issued_at: NOW - 2000, expires_at: NOW - 10 });
|
||||
await expectBad("certificate expired before sending", sealReply(stale, { author: stale.author, id: stale.listing.id }, base, tp),
|
||||
/certificate's validity/, { author: stale.author, id: stale.listing.id });
|
||||
// Referring to a listing other than the conversation's.
|
||||
await expectBad("another listing", sealReply(owner, { ...lref, id: "cd".repeat(16) }, base, tp), /another listing/);
|
||||
// The signed listing inside disagrees with the envelope's.
|
||||
await expectBad("envelope and plaintext disagree",
|
||||
sealReply(owner, lref, base, tp, { beforeSign: (p) => void (p.listing = { ...lref, id: "ee".repeat(16) }) }), /another listing/);
|
||||
// Encrypted to someone else's thread key.
|
||||
await expectBad("wrong key", sealReply(owner, lref, base, tp), /not a reply|decrypt/, lref, newThreadSecret());
|
||||
|
||||
// Grant rules.
|
||||
const grant = { t: "grant", n: 2, address: "Weg 1", valid_until: NOW + 86_400 };
|
||||
await expectBad("grant without address", sealReply(owner, lref, grant, tp, { beforeSign: (p) => void delete p.address }), /address/);
|
||||
await expectBad("grant valid too long", sealReply(owner, lref, { ...grant, valid_until: NOW + 31 * 86_400 }, tp), /validity/);
|
||||
await expectBad("grant already expired", sealReply(owner, lref, { ...grant, valid_until: NOW }, tp), /validity/);
|
||||
await expectBad("grant with text", sealReply(owner, lref, { ...grant, text: "hi" }, tp), /note/);
|
||||
await expectBad("control character", sealReply(owner, lref, { t: "text", n: 1, text: "a\u0007b" }, tp), /bad text/);
|
||||
await expectBad("counter zero", sealReply(owner, lref, { t: "text", n: 0, text: "x" }, tp), /counter/);
|
||||
});
|
||||
+2
-1
@@ -78,7 +78,8 @@ test("detail view shows the content and a passing verification report", async ()
|
||||
assert.equal(page.document.querySelectorAll(".checks li.ok").length, 6);
|
||||
assert.equal(page.document.querySelectorAll(".checks li.bad").length, 0);
|
||||
assert.ok(page.document.querySelector("a[href^='https://www.openstreetmap.org/']")!.getAttribute("rel")!.includes("noopener"));
|
||||
assert.match(text, /not available yet/);
|
||||
assert.match(text, /Contact the owner/);
|
||||
assert.ok(page.document.querySelector("form.compose textarea"), "the contact form is offered");
|
||||
} finally {
|
||||
page.close();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user