Announce incoming messages on the node's terminal
The node now checks for new messages every 10 s in the background (before, only when the web UI asked), and Inbox.Collect reports newly filed visible messages through OnArrivals. The CLI logs one line per conversation with the listing title and a link to it, never the buyer's text. Hidden messages are not announced, a backlog is capped at 5 lines, and a lock stops a background check and a UI request from filing the same message twice. The e2e checks that node A announces the message before its API is called. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,7 +21,8 @@ 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
|
||||
in the browser (`allmende run` prints a sign-in link; open it to get "My listings")
|
||||
and can release the exact address as a signed message.
|
||||
and can release the exact address as a signed message. When a message arrives the
|
||||
node says so on its terminal (listing, link to the conversation, never the text).
|
||||
|
||||
Owners publish from the same screen: "New listing" takes a title, price and
|
||||
pasted coordinates (only a ~1 km area is published, never the address), and
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
// inboxCheckEvery is how often the node looks for new messages when the
|
||||
// web UI is not open. (The UI triggers a check itself whenever it asks.)
|
||||
inboxCheckEvery = 10 * time.Second
|
||||
// maxNotices caps the lines one check writes, so a backlog after a long
|
||||
// time offline does not flood the terminal.
|
||||
maxNotices = 5
|
||||
)
|
||||
|
||||
// watchInbox files incoming messages in the background, so the owner is told
|
||||
// about them on the terminal even with no browser open. The notices come from
|
||||
// the Inbox's OnArrivals callback, which also fires for checks made by the UI.
|
||||
func watchInbox(ctx context.Context, log *slog.Logger, in *inbox.Inbox) {
|
||||
tick := time.NewTicker(inboxCheckEvery)
|
||||
defer tick.Stop()
|
||||
failing := false
|
||||
for {
|
||||
if _, err := in.Collect(ctx); err != nil && ctx.Err() == nil {
|
||||
if !failing { // say it once, not every ten seconds
|
||||
log.Warn("could not check for new messages", "err", err)
|
||||
}
|
||||
failing = true
|
||||
} else {
|
||||
failing = false
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// arrivalNotice returns the callback that tells the owner about new messages.
|
||||
// It names the listing and links to the conversation but never prints what
|
||||
// the buyer wrote: that is untrusted text and belongs in the browser.
|
||||
func arrivalNotice(ctx context.Context, log *slog.Logger, st *store.Store, httpAddr string) func([]inbox.Arrival) {
|
||||
type conv struct {
|
||||
listing, thread string
|
||||
author string
|
||||
count int
|
||||
started bool
|
||||
}
|
||||
return func(arrivals []inbox.Arrival) {
|
||||
byConv := map[string]*conv{}
|
||||
var order []string
|
||||
for _, a := range arrivals {
|
||||
key := a.Listing.ID + "/" + a.Thread
|
||||
c := byConv[key]
|
||||
if c == nil {
|
||||
c = &conv{listing: a.Listing.ID, thread: a.Thread, author: a.Listing.Author}
|
||||
byConv[key] = c
|
||||
order = append(order, key)
|
||||
}
|
||||
c.count++
|
||||
c.started = c.started || a.New
|
||||
}
|
||||
sort.Strings(order)
|
||||
for n, key := range order {
|
||||
if n == maxNotices {
|
||||
log.Info("more conversations have new messages", "more", len(order)-maxNotices,
|
||||
"open", uiURL(httpAddr, "/mine"))
|
||||
break
|
||||
}
|
||||
c := byConv[key]
|
||||
title := ""
|
||||
if l, err := st.Get(ctx, c.author, c.listing); err == nil && l != nil {
|
||||
title = l.Title
|
||||
}
|
||||
msg := "new message"
|
||||
if c.started {
|
||||
msg = "new conversation"
|
||||
}
|
||||
attrs := []any{"listing", title}
|
||||
if c.count > 1 {
|
||||
attrs = append(attrs, "messages", c.count)
|
||||
}
|
||||
attrs = append(attrs,
|
||||
"conversation", shortID(c.thread),
|
||||
"open", uiURL(httpAddr, fmt.Sprintf("/mine/%s/%s", c.listing, c.thread)))
|
||||
log.Info(msg, attrs...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func shortID(hex string) string {
|
||||
if len(hex) > 8 {
|
||||
return hex[:8]
|
||||
}
|
||||
return hex
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/inbox"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/message"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
)
|
||||
|
||||
func notice(t *testing.T) (func([]inbox.Arrival), *bytes.Buffer) {
|
||||
t.Helper()
|
||||
st, err := store.Open(":memory:", store.Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { st.Close() })
|
||||
var out bytes.Buffer
|
||||
log := slog.New(slog.NewTextHandler(&out, &slog.HandlerOptions{ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
|
||||
if a.Key == slog.TimeKey {
|
||||
return slog.Attr{} // keep the lines comparable
|
||||
}
|
||||
return a
|
||||
}}))
|
||||
return arrivalNotice(context.Background(), log, st, "0.0.0.0:8080"), &out
|
||||
}
|
||||
|
||||
func TestNoticeNamesTheConversationAndLinksToIt(t *testing.T) {
|
||||
say, out := notice(t)
|
||||
ref := message.Ref{Author: strings.Repeat("a", 64), ID: strings.Repeat("1", 32)}
|
||||
thread := strings.Repeat("ab", 32)
|
||||
say([]inbox.Arrival{{Listing: ref, Thread: thread, New: true}})
|
||||
|
||||
got := out.String()
|
||||
for _, want := range []string{
|
||||
"level=INFO", `msg="new conversation"`, "conversation=abababab",
|
||||
"open=http://127.0.0.1:8080/#/mine/" + ref.ID + "/" + thread, // a wildcard bind opens on loopback
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, "token") || strings.Contains(got, "login") {
|
||||
t.Errorf("the notice must not carry the sign-in token:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoticeGroupsMessagesOfOneConversation(t *testing.T) {
|
||||
say, out := notice(t)
|
||||
ref := message.Ref{Author: strings.Repeat("a", 64), ID: strings.Repeat("1", 32)}
|
||||
thread := strings.Repeat("cd", 32)
|
||||
say([]inbox.Arrival{{Listing: ref, Thread: thread}, {Listing: ref, Thread: thread}, {Listing: ref, Thread: thread}})
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(out.String()), "\n")
|
||||
if len(lines) != 1 {
|
||||
t.Fatalf("one conversation, want one line, got %d:\n%s", len(lines), out.String())
|
||||
}
|
||||
if !strings.Contains(lines[0], `msg="new message"`) || !strings.Contains(lines[0], "messages=3") {
|
||||
t.Errorf("want a plain new message with a count of 3: %s", lines[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoticeCapsALongBacklog(t *testing.T) {
|
||||
say, out := notice(t)
|
||||
var arrivals []inbox.Arrival
|
||||
for i := 0; i < 12; i++ {
|
||||
arrivals = append(arrivals, inbox.Arrival{
|
||||
Listing: message.Ref{Author: strings.Repeat("a", 64), ID: strings.Repeat("1", 32)},
|
||||
Thread: fmt.Sprintf("%064x", i), New: true,
|
||||
})
|
||||
}
|
||||
say(arrivals)
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(out.String()), "\n")
|
||||
if len(lines) != maxNotices+1 {
|
||||
t.Fatalf("want %d conversation lines and one summary, got %d:\n%s", maxNotices, len(lines), out.String())
|
||||
}
|
||||
last := lines[len(lines)-1]
|
||||
if !strings.Contains(last, "more=7") || !strings.Contains(last, "#/mine") {
|
||||
t.Errorf("the summary should say how many more and where to look: %s", last)
|
||||
}
|
||||
}
|
||||
+16
-6
@@ -99,19 +99,22 @@ func cmdRun(args []string) error {
|
||||
if token == "" {
|
||||
log.Warn("no admin token found; publishing through the API is disabled")
|
||||
}
|
||||
in := &inbox.Inbox{
|
||||
Store: st, Device: dev, Publisher: node,
|
||||
Difficulty: *msgDifficulty, MaxNewThreads: *maxNewThreads,
|
||||
}
|
||||
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,
|
||||
},
|
||||
Inbox: in,
|
||||
})
|
||||
|
||||
ln, err := net.Listen("tcp", *httpAddr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Set before anything can call Collect (the server and the watcher below).
|
||||
in.OnArrivals = arrivalNotice(ctx, log, st, ln.Addr().String())
|
||||
srv := &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
@@ -144,6 +147,7 @@ func cmdRun(args []string) error {
|
||||
}
|
||||
|
||||
go announce(ctx, log, node, st, dev.Cert.Author)
|
||||
go watchInbox(ctx, log, in)
|
||||
|
||||
<-ctx.Done()
|
||||
log.Info("shutting down")
|
||||
@@ -186,14 +190,20 @@ func announce(ctx context.Context, log *slog.Logger, node *p2p.Node, st *store.S
|
||||
|
||||
// loginURL is the link that signs the owner in to the web UI.
|
||||
func loginURL(listenAddr, token string) string {
|
||||
return uiURL(listenAddr, "/login/"+token)
|
||||
}
|
||||
|
||||
// uiURL is the address of a page of the web UI (route is the part after "#")
|
||||
// as a browser on this machine can open it.
|
||||
func uiURL(listenAddr, route string) string {
|
||||
host, port, err := net.SplitHostPort(listenAddr)
|
||||
if err != nil {
|
||||
return "http://" + listenAddr + "/#/login/" + token
|
||||
return "http://" + listenAddr + "/#" + route
|
||||
}
|
||||
// A wildcard address (0.0.0.0, ::) is not something a browser can open.
|
||||
if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
// JoinHostPort brackets IPv6 addresses.
|
||||
return "http://" + net.JoinHostPort(host, port) + "/#/login/" + token
|
||||
return "http://" + net.JoinHostPort(host, port) + "/#" + route
|
||||
}
|
||||
|
||||
@@ -322,6 +322,13 @@ text rules below are enforced by endpoints.
|
||||
and `address_saved`) and `GET /api/v1/inbox?listing=<id>`, whose rows also
|
||||
carry `last_dir`, `needs_reply`, a text `preview` (empty for hidden messages),
|
||||
`effort` (proof-of-work bits of the first message) and `grant_until`.
|
||||
- **Terminal notice.** The node checks for new messages every 10 s (and on every
|
||||
UI request), so it reports them even with no browser open. For each
|
||||
conversation it logs one line, `new conversation` or `new message`, with the
|
||||
listing's title, a count if there are several, a short conversation id and a
|
||||
link `http://127.0.0.1:8080/#/mine/<listing>/<thread>`. It never prints what
|
||||
the buyer wrote (untrusted text, and it belongs in the browser), and hidden
|
||||
messages are not announced. A backlog is capped at 5 lines plus a summary.
|
||||
- **Owner login.** The page itself never contains the admin token (every node
|
||||
serves the same page, including public gateways). `allmende run` prints a link
|
||||
`http://127.0.0.1:8080/#/login/<token>` to the terminal, not to its log. The
|
||||
|
||||
+42
-9
@@ -10,6 +10,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||
@@ -52,6 +53,24 @@ type Inbox struct {
|
||||
// conversations; 0 means DefaultMaxNewThreads.
|
||||
MaxNewThreads int
|
||||
Clock func() time.Time
|
||||
|
||||
// OnArrivals, if set, is called after a Collect that filed visible new
|
||||
// messages, once per call, with one entry per message. It runs on the
|
||||
// collecting goroutine, so it should return quickly. It never receives
|
||||
// message text. Set it before the Inbox is used.
|
||||
OnArrivals func([]Arrival)
|
||||
|
||||
mu sync.Mutex // one Collect at a time, so a message is filed and announced once
|
||||
}
|
||||
|
||||
// Arrival describes a message that was just filed for one of the owner's
|
||||
// listings. Hidden messages (those that broke the first-message rules) are not
|
||||
// reported.
|
||||
type Arrival struct {
|
||||
Listing message.Ref
|
||||
Thread string
|
||||
// New is true if the message started a conversation.
|
||||
New bool
|
||||
}
|
||||
|
||||
func (i *Inbox) now() time.Time {
|
||||
@@ -91,6 +110,14 @@ type threadKey struct {
|
||||
// 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) {
|
||||
i.mu.Lock()
|
||||
defer i.mu.Unlock()
|
||||
var arrivals []Arrival
|
||||
defer func() {
|
||||
if i.OnArrivals != nil && len(arrivals) > 0 {
|
||||
i.OnArrivals(arrivals)
|
||||
}
|
||||
}()
|
||||
envs, err := i.Store.OwnerMessages(ctx, i.Device.Cert.Author)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -136,22 +163,26 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) {
|
||||
}
|
||||
|
||||
added := 0
|
||||
admit := func(cs []candidate) error {
|
||||
admit := func(cs []candidate, starts bool) 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 {
|
||||
for k, c := range cs {
|
||||
hidden, err := i.file(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
added++
|
||||
if !hidden {
|
||||
arrivals = append(arrivals, Arrival{Listing: c.env.Listing, Thread: c.plain.Thread, New: starts && k == 0})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := admit(known); err != nil {
|
||||
if err := admit(known, false); err != nil {
|
||||
return added, err
|
||||
}
|
||||
|
||||
@@ -191,7 +222,7 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) {
|
||||
return keys[a].thread < keys[b].thread
|
||||
})
|
||||
for k := 0; k < len(keys) && k < room; k++ {
|
||||
if err := admit(fresh[keys[k]]); err != nil {
|
||||
if err := admit(fresh[keys[k]], true); err != nil {
|
||||
return added, err
|
||||
}
|
||||
}
|
||||
@@ -199,16 +230,18 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) {
|
||||
return added, nil
|
||||
}
|
||||
|
||||
func (i *Inbox) file(ctx context.Context, c candidate) error {
|
||||
// file stores one incoming message and reports whether it was hidden.
|
||||
func (i *Inbox) file(ctx context.Context, c candidate) (hidden bool, err error) {
|
||||
replied, err := i.Store.Replied(ctx, c.env.Listing, c.plain.Thread)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
hidden := !replied && c.plain.CheckBuyerFirst() != nil
|
||||
return i.Store.AddInbox(ctx, store.InboxMessage{
|
||||
hidden = !replied && c.plain.CheckBuyerFirst() != nil
|
||||
err = 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)
|
||||
return hidden, err
|
||||
}
|
||||
|
||||
// Reply is what the owner sends back.
|
||||
|
||||
@@ -159,6 +159,57 @@ func TestCollectFilesConversationsOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestArrivalsAreAnnouncedOnceAndWithoutText(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
var calls [][]Arrival
|
||||
f.in.OnArrivals = func(a []Arrival) { calls = append(calls, a) }
|
||||
l := f.listing()
|
||||
ref := message.Ref{Author: l.Author, ID: l.ID}
|
||||
a, b, spam := f.newThread(), f.newThread(), f.newThread()
|
||||
|
||||
if f.collect(); len(calls) != 0 {
|
||||
t.Fatalf("nothing arrived but %d calls were made", len(calls))
|
||||
}
|
||||
|
||||
f.buyer(l, a, 1, "Ist die Wohnung noch frei?", msgDifficulty)
|
||||
f.buyer(l, a, 2, "Ich könnte morgen vorbeikommen.", msgDifficulty)
|
||||
f.buyer(l, b, 1, "Guten Tag", msgDifficulty)
|
||||
f.buyer(l, spam, 1, "Schaut euch https://example.com/x an", msgDifficulty) // hidden
|
||||
f.collect()
|
||||
if len(calls) != 1 {
|
||||
t.Fatalf("one collection must make one call, got %d", len(calls))
|
||||
}
|
||||
got := calls[0]
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("got %d arrivals, want 3 (the hidden one is not announced): %+v", len(got), got)
|
||||
}
|
||||
starts := 0
|
||||
for _, x := range got {
|
||||
if x.Listing != ref {
|
||||
t.Errorf("wrong listing %+v", x.Listing)
|
||||
}
|
||||
if x.Thread == spam.PublicHex() {
|
||||
t.Error("a hidden message was announced")
|
||||
}
|
||||
if x.New {
|
||||
starts++
|
||||
}
|
||||
}
|
||||
if starts != 2 {
|
||||
t.Errorf("%d conversations started, want 2 (a and b)", starts)
|
||||
}
|
||||
|
||||
// Nothing new: no repeat. A further message in a known conversation is not a start.
|
||||
if f.collect(); len(calls) != 1 {
|
||||
t.Fatalf("a second collection announced again: %d calls", len(calls))
|
||||
}
|
||||
f.buyer(l, a, 3, "Noch da?", msgDifficulty)
|
||||
f.collect()
|
||||
if len(calls) != 2 || len(calls[1]) != 1 || calls[1][0].New || calls[1][0].Thread != a.PublicHex() {
|
||||
t.Fatalf("follow-up not announced as a plain message in a: %+v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinksInFirstMessagesAreHiddenUntilTheOwnerReplies(t *testing.T) {
|
||||
f := newFixture(t, 0)
|
||||
l := f.listing()
|
||||
|
||||
@@ -81,6 +81,13 @@ BUYER=$ROOT/scripts/e2e/buyer.ts
|
||||
AUTHOR=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["author"])')
|
||||
SECRET=$(node $BUYER send http://127.0.0.1:18102 $AUTHOR $ID) || bad "buyer could not send via B"
|
||||
ok "buyer posted an encrypted message to node B"
|
||||
# Nobody has called A's API yet: the node itself must notice and tell its owner.
|
||||
wait_for "A's terminal announces the new conversation" 30 grep -q 'msg="new conversation"' "$W/a.log"
|
||||
grep 'msg="new conversation"' "$W/a.log" | grep -q 'listing="Helle Wohnung, renoviert"' && ok "owner's terminal names the listing" || bad "notice does not name the listing"
|
||||
grep 'msg="new conversation"' "$W/a.log" | grep -q "open=http://127.0.0.1:18101/#/mine/$ID/" && ok "and links to the conversation" || bad "notice has no link"
|
||||
grep -q "Ist die Wohnung noch frei" "$W/a.log" && bad "the buyer's text was printed to the terminal"
|
||||
ok "the notice does not show what the buyer wrote"
|
||||
[ "$(grep -c 'msg="new conversation"' "$W/a.log")" = 1 ] || bad "the notice was repeated"
|
||||
inbox_a() { curl -s -H "Authorization: Bearer $TOKEN" http://127.0.0.1:18101/api/v1/inbox | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))'; }
|
||||
wait_for "A receives the message" 20 test "$(inbox_a)" = 1
|
||||
ok "owner's node A decrypted it (via gossip through B)"
|
||||
|
||||
Reference in New Issue
Block a user