From 13c82f8d592784298c409359c01ce53e9c1609f5 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Wed, 18 Nov 2026 20:50:38 +0100 Subject: [PATCH] messaging: owners can block a conversation A blocked thread key is dropped unread (not announced, not counted against the daily new-conversation limit). API, UI button with confirmation, and a list with unblock. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- docs/PROTOCOL.md | 10 ++++++ internal/api/api.go | 3 ++ internal/api/messages.go | 45 ++++++++++++++++++++++++ internal/api/messages_test.go | 33 ++++++++++++++++++ internal/inbox/inbox.go | 51 +++++++++++++++++++++++++++- internal/inbox/inbox_test.go | 63 ++++++++++++++++++++++++++++++++++ internal/store/inbox.go | 64 +++++++++++++++++++++++++++++++++++ internal/store/store.go | 14 ++++++++ web/dist/app.js | 57 ++++++++++++++++++++++++++++++- web/src/i18n.ts | 10 ++++++ web/src/owner.ts | 41 ++++++++++++++++++++++ web/src/ownerApi.ts | 18 ++++++++++ web/test/helpers.ts | 2 +- web/test/owner.test.ts | 25 ++++++++++++++ 14 files changed, 433 insertions(+), 3 deletions(-) diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 0ffa63e..4d55632 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -339,6 +339,16 @@ text rules below are enforced by endpoints. 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. +- **Block.** The owner can block a conversation (`PUT + /api/v1/inbox/{listing}/{thread}/block`): it is erased, and every later + envelope of that thread key is dropped unread, unannounced and not counted + against the new-conversation limit. `DELETE` on the same path lifts the block + (what arrived meanwhile is gone), `GET /api/v1/blocked` lists blocks. The + buyer is not told. A block lasts as long as its listing is stored. It + stops a thread key, not a person: a buyer can start over with a new key, + which costs a first message again (proof-of-work, the link ban, the daily + limit). Plain *delete* only erases; the thread would reappear as a new + conversation if the buyer wrote 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 diff --git a/internal/api/api.go b/internal/api/api.go index 4adf218..5a8b98d 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -112,6 +112,9 @@ func New(cfg Config) http.Handler { mux.HandleFunc("GET /api/v1/inbox/{id}/{thread}", s.admin(s.getThread)) mux.HandleFunc("POST /api/v1/inbox/{id}/{thread}", s.admin(s.reply)) mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}", s.admin(s.deleteThread)) + mux.HandleFunc("PUT /api/v1/inbox/{id}/{thread}/block", s.admin(s.blockThread)) + mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}/block", s.admin(s.unblockThread)) + mux.HandleFunc("GET /api/v1/blocked", s.admin(s.listBlocked)) mux.HandleFunc("PUT /api/v1/listings/{id}/address", s.admin(s.putAddress)) mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress)) mux.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress)) diff --git a/internal/api/messages.go b/internal/api/messages.go index 6853f51..d722dc9 100644 --- a/internal/api/messages.go +++ b/internal/api/messages.go @@ -2,6 +2,7 @@ package api import ( "bytes" + "context" "encoding/json" "errors" "io" @@ -399,6 +400,50 @@ func (s *server) deleteThread(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } +func (s *server) blockThread(w http.ResponseWriter, r *http.Request) { + s.blockOrUnblock(w, r, s.Inbox.Block) +} + +func (s *server) unblockThread(w http.ResponseWriter, r *http.Request) { + s.blockOrUnblock(w, r, s.Inbox.Unblock) +} + +func (s *server) blockOrUnblock(w http.ResponseWriter, r *http.Request, do func(context.Context, message.Ref, string) error) { + ref, thread, ok := s.threadRef(w, r) + if !ok { + return + } + switch err := do(r.Context(), ref, thread); { + case err == nil: + w.WriteHeader(http.StatusNoContent) + case errors.Is(err, inbox.ErrNoThread), errors.Is(err, inbox.ErrNotOwner): + fail(w, http.StatusNotFound, "no such conversation") + default: + fail(w, http.StatusInternalServerError, "internal error") + } +} + +type blockedView struct { + Listing string `json:"listing"` + Thread string `json:"thread"` + BlockedAt int64 `json:"blocked_at"` +} + +// listBlocked lists the conversations the owner blocked, so a block can be lifted. +func (s *server) listBlocked(w http.ResponseWriter, r *http.Request) { + bs, err := s.Store.BlockedThreads(r.Context(), s.Device.Cert.Author) + if err != nil { + fail(w, http.StatusInternalServerError, "internal error") + return + } + out := make([]blockedView, 0, len(bs)) + for _, b := range bs { + out = append(out, blockedView{Listing: b.Listing.ID, Thread: b.Thread, BlockedAt: b.BlockedAt}) + } + noStore(w) + writeJSON(w, http.StatusOK, out) +} + // 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) { diff --git a/internal/api/messages_test.go b/internal/api/messages_test.go index 4e7ddd3..2a54df0 100644 --- a/internal/api/messages_test.go +++ b/internal/api/messages_test.go @@ -428,3 +428,36 @@ func TestStatusReportsMessageDifficulty(t *testing.T) { t.Fatalf("message_difficulty = %v", st["message_difficulty"]) } } + +func TestBlockingAConversationOverTheAPI(t *testing.T) { + f := newFixture(t, token) + l := f.publish(t) + tk := newThread(t) + f.send(t, buyerHello(t, l, tk, "Hallo")) + f.do(t, "GET", "/api/v1/inbox?listing="+l.ID, "", true) // collects + + path := "/api/v1/inbox/" + l.ID + "/" + tk.PublicHex() + if code, _ := f.do(t, "PUT", path+"/block", "", false); code != 401 { + t.Fatalf("blocking without the token: %d", code) + } + if code, body := f.do(t, "PUT", path+"/block", "", true); code != 204 { + t.Fatalf("block: %d %s", code, body) + } + if code, _ := f.do(t, "GET", path, "", true); code != 404 { + t.Fatalf("a blocked conversation can still be read: %d", code) + } + var bl []blockedView + code, body := f.do(t, "GET", "/api/v1/blocked", "", true) + if code != 200 || json.Unmarshal(body, &bl) != nil || len(bl) != 1 || bl[0].Thread != tk.PublicHex() || bl[0].Listing != l.ID { + t.Fatalf("blocked list: %d %s", code, body) + } + if code, _ := f.do(t, "PUT", "/api/v1/inbox/"+l.ID+"/"+strings.Repeat("0", 64)+"/block", "", true); code != 404 { + t.Fatalf("blocking an unknown thread: %d", code) + } + if code, body := f.do(t, "DELETE", path+"/block", "", true); code != 204 { + t.Fatalf("unblock: %d %s", code, body) + } + if _, body := f.do(t, "GET", "/api/v1/blocked", "", true); string(bytes.TrimSpace(body)) != "[]" { + t.Fatalf("blocked list after unblocking: %s", body) + } +} diff --git a/internal/inbox/inbox.go b/internal/inbox/inbox.go index e02afcf..596d6dc 100644 --- a/internal/inbox/inbox.go +++ b/internal/inbox/inbox.go @@ -133,6 +133,15 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) { return 0, err } + blockedList, err := i.Store.BlockedThreads(ctx, i.Device.Cert.Author) + if err != nil { + return 0, err + } + blocked := map[threadKey]bool{} + for _, b := range blockedList { + blocked[threadKey{b.Listing, b.Thread}] = true + } + var known []candidate fresh := map[threadKey][]candidate{} for k, e := range envs { @@ -148,9 +157,16 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) { } continue } + key := threadKey{e.Listing, p.Thread} + if blocked[key] { + // The owner blocked this conversation: drop it unread, count nothing. + 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 @@ -244,6 +260,39 @@ func (i *Inbox) file(ctx context.Context, c candidate) (hidden bool, err error) return hidden, err } +// Block erases a conversation and drops everything its thread key sends from +// now on, without notice to the buyer. A buyer can start over with a new +// thread key, which costs a first message (proof-of-work, link ban, the daily +// new-conversation limit) again. +func (i *Inbox) Block(ctx context.Context, ref message.Ref, thread string) error { + if ref.Author != i.Device.Cert.Author { + return ErrNotOwner + } + ok, err := i.Store.BlockThread(ctx, ref, thread, i.now().Unix()) + if err != nil { + return err + } + if !ok { + return ErrNoThread + } + return nil +} + +// Unblock lifts a block. Envelopes that arrived while blocked are gone. +func (i *Inbox) Unblock(ctx context.Context, ref message.Ref, thread string) error { + if ref.Author != i.Device.Cert.Author { + return ErrNotOwner + } + ok, err := i.Store.UnblockThread(ctx, ref, thread) + if err != nil { + return err + } + if !ok { + return ErrNoThread + } + return nil +} + // Reply is what the owner sends back. type Reply struct { Type string // message.TypeText or message.TypeGrant diff --git a/internal/inbox/inbox_test.go b/internal/inbox/inbox_test.go index 215112d..b881042 100644 --- a/internal/inbox/inbox_test.go +++ b/internal/inbox/inbox_test.go @@ -414,3 +414,66 @@ func TestAddressesAndThreadsCanBeErased(t *testing.T) { t.Fatalf("an erased conversation came back (%d)", n) } } + +func TestABlockedConversationStaysSilentAndFreesNothingElse(t *testing.T) { + f := newFixture(t, 1) // one new conversation per day + l := f.listing() + ref := message.Ref{Author: l.Author, ID: l.ID} + var announced int + f.in.OnArrivals = func(a []Arrival) { announced += len(a) } + + spam := f.newThread() + f.buyer(l, spam, 1, "Hallo", msgDifficulty) + f.collect() + if err := f.in.Block(ctx, ref, spam.PublicHex()); err != nil { + t.Fatal(err) + } + if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 { + t.Fatal("the blocked conversation is still listed") + } + announced = 0 + + // The buyer keeps writing in the same thread: nothing is filed or announced. + f.buyer(l, spam, 2, "Hallo?", msgDifficulty) + f.buyer(l, spam, 3, "Antwortet bitte", msgDifficulty) + if n := f.collect(); n != 0 || announced != 0 { + t.Fatalf("a blocked thread got through: filed %d, announced %d", n, announced) + } + if th, _ := f.st.Threads(ctx, l.Author); len(th) != 0 { + t.Fatal("a blocked thread reappeared") + } + + // Blocking is per thread: someone else (here under a new daily budget) is heard. + f.now = f.now.Add(25 * time.Hour) + other := f.newThread() + f.buyer(l, other, 1, "Guten Tag", msgDifficulty) + if n := f.collect(); n != 1 { + t.Fatalf("another buyer was not heard: %d", n) + } + + // The block can be lifted; the buyer's later messages arrive again. + if err := f.in.Unblock(ctx, ref, spam.PublicHex()); err != nil { + t.Fatal(err) + } + f.now = f.now.Add(25 * time.Hour) // it starts a new conversation, which the daily limit applies to + f.buyer(l, spam, 4, "Noch da?", msgDifficulty) + f.collect() + if th, _ := f.st.Threads(ctx, l.Author); len(th) != 2 { + t.Fatalf("after unblocking, %d conversations, want 2", len(th)) + } +} + +func TestBlockingNeedsAnExistingConversationOfYours(t *testing.T) { + f := newFixture(t, 0) + l := f.listing() + tk := f.newThread() + if err := f.in.Block(ctx, message.Ref{Author: l.Author, ID: l.ID}, tk.PublicHex()); !errors.Is(err, ErrNoThread) { + t.Fatalf("blocking an unknown thread: %v", err) + } + if err := f.in.Block(ctx, message.Ref{Author: "someone-else", ID: l.ID}, tk.PublicHex()); !errors.Is(err, ErrNotOwner) { + t.Fatalf("blocking another author's listing: %v", err) + } + if err := f.in.Unblock(ctx, message.Ref{Author: l.Author, ID: l.ID}, tk.PublicHex()); !errors.Is(err, ErrNoThread) { + t.Fatalf("unblocking a thread that is not blocked: %v", err) + } +} diff --git a/internal/store/inbox.go b/internal/store/inbox.go index ec5ad4f..fb34371 100644 --- a/internal/store/inbox.go +++ b/internal/store/inbox.go @@ -237,3 +237,67 @@ func (s *Store) DeleteAddress(ctx context.Context, ref message.Ref) error { `DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID) return err } + +// BlockThread erases a conversation and remembers its thread key, so the +// envelopes the buyer keeps sending are dropped unread. It reports whether the +// conversation existed; blocking an unknown thread does nothing. +func (s *Store) BlockThread(ctx context.Context, ref message.Ref, thread string, now int64) (bool, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return false, err + } + defer tx.Rollback() + res, err := tx.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() + if n == 0 { + return false, nil + } + if _, err := tx.ExecContext(ctx, ` + INSERT OR IGNORE INTO inbox_blocked (author, listing_id, thread, blocked_at) VALUES (?, ?, ?, ?)`, + ref.Author, ref.ID, thread, now); err != nil { + return false, err + } + return true, tx.Commit() +} + +// UnblockThread lifts a block. What was sent while blocked is gone. +func (s *Store) UnblockThread(ctx context.Context, ref message.Ref, thread string) (bool, error) { + res, err := s.db.ExecContext(ctx, + `DELETE FROM inbox_blocked 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 +} + +// Blocked is one blocked conversation. +type Blocked struct { + Listing message.Ref + Thread string + BlockedAt int64 +} + +// BlockedThreads lists the author's blocked conversations, newest first. +func (s *Store) BlockedThreads(ctx context.Context, author string) ([]Blocked, error) { + rows, err := s.db.QueryContext(ctx, ` + SELECT listing_id, thread, blocked_at FROM inbox_blocked WHERE author = ? + ORDER BY blocked_at DESC, thread`, author) + if err != nil { + return nil, err + } + defer rows.Close() + var out []Blocked + for rows.Next() { + b := Blocked{Listing: message.Ref{Author: author}} + if err := rows.Scan(&b.Listing.ID, &b.Thread, &b.BlockedAt); err != nil { + return nil, err + } + out = append(out, b) + } + return out, rows.Err() +} diff --git a/internal/store/store.go b/internal/store/store.go index c9fc12d..36adeeb 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -141,6 +141,15 @@ CREATE TABLE IF NOT EXISTS inbox_seen ( hash TEXT PRIMARY KEY, expires_at INTEGER NOT NULL ) WITHOUT ROWID; +-- Conversations the owner blocked: further envelopes of the thread are dropped +-- unread. Rows go when their listing does (see Expire). +CREATE TABLE IF NOT EXISTS inbox_blocked ( + author TEXT NOT NULL, + listing_id TEXT NOT NULL, + thread TEXT NOT NULL, + blocked_at INTEGER NOT NULL, + PRIMARY KEY (author, listing_id, thread) +) 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, @@ -516,6 +525,11 @@ func (s *Store) Expire(ctx context.Context) (int64, error) { if _, err := s.db.ExecContext(ctx, `DELETE FROM inbox_seen WHERE expires_at <= ?`, now); err != nil { return n + m + k, err } + if _, err := s.db.ExecContext(ctx, ` + DELETE FROM inbox_blocked WHERE NOT EXISTS ( + SELECT 1 FROM listings l WHERE l.author = inbox_blocked.author AND l.id = inbox_blocked.listing_id)`); err != nil { + return n + m + k, err + } return n + m + k, nil } diff --git a/web/dist/app.js b/web/dist/app.js index b6e364a..d296a5a 100644 --- a/web/dist/app.js +++ b/web/dist/app.js @@ -291,6 +291,11 @@ var de = { "own.delete": "Unterhaltung l\xF6schen", "own.deleteSure": "Wirklich l\xF6schen? Sie wird von deinem Knoten entfernt.", "own.deleteYes": "Ja, l\xF6schen", + "own.block": "Blockieren", + "own.blockSure": "Blockieren? Die Unterhaltung wird gel\xF6scht und weitere Nachrichten dieser Person werden ungelesen verworfen. Sie erf\xE4hrt davon nichts.", + "own.blockYes": "Ja, blockieren", + "own.blocked": "Blockiert ({n})", + "own.unblock": "Freigeben", "own.sheetTitle": "Adresse freigeben", "own.sheetHelp": "Eine signierte Nachricht, nur f\xFCr diese Person sichtbar. Ihr Bildschirm blendet sie nach dem Datum aus. Sie k\xF6nnte sie trotzdem kopiert haben.", "own.fNote": "Hinweis an die Person", @@ -543,6 +548,11 @@ var en = { "own.delete": "Delete conversation", "own.deleteSure": "Really delete? It is removed from your node.", "own.deleteYes": "Yes, delete", + "own.block": "Block", + "own.blockSure": "Block? The conversation is deleted and anything more from this person is dropped unread. They are not told.", + "own.blockYes": "Yes, block", + "own.blocked": "Blocked ({n})", + "own.unblock": "Unblock", "own.sheetTitle": "Release address", "own.sheetHelp": "A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.", "own.fNote": "Note to the buyer", @@ -4864,6 +4874,15 @@ async function sendReply(listing, thread, r) { async function deleteThread(listing, thread) { await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`); } +async function blockThread(listing, thread) { + await call("PUT", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`); +} +async function unblockThread(listing, thread) { + await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`); +} +async function getBlocked() { + return await call("GET", "/api/v1/blocked"); +} async function getAddress(listing) { try { return await call("GET", `/api/v1/listings/${e(listing)}/address`); @@ -4978,6 +4997,7 @@ async function showOwner(listingId, thread) { addr.root, chips, reqBox, + blockedList(listingId, () => void refresh()), h("p", { class: "muted small" }, t("own.limitNote")) ] : [h("p", { class: "muted pick" }, t("own.pickListing"))] ); @@ -4995,7 +5015,8 @@ async function showOwner(listingId, thread) { firstNote, addressHint, composer2(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())), - deleteControl2(listingId, thread) + deleteControl2(listingId, thread), + blockControl(listingId, thread) ]); } else { threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : "")); @@ -5273,6 +5294,40 @@ function deleteControl2(listingId, thread) { slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.delete"))); return slot; } +function blockControl(listingId, thread) { + const slot = h("p", null); + const ask = () => { + clear(slot); + append(slot, [ + t("own.blockSure"), + " ", + h("button", { type: "button", class: "btn", onclick: () => void blockThread(listingId, thread).then(() => location.hash = `#/mine/${listingId}`) }, t("own.blockYes")) + ]); + }; + slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.block"))); + return slot; +} +function blockedList(listingId, changed) { + const box = h("details", { class: "blocked", hidden: true }); + void getBlocked().then((all) => { + const mine2 = all.filter((b) => b.listing === listingId); + if (mine2.length === 0) return; + box.hidden = false; + append(box, [ + h("summary", null, t("own.blocked", { n: mine2.length })), + ...mine2.map( + (b) => h( + "p", + { class: "muted small" }, + `#${b.thread.slice(0, 6)} \xB7 ${new Date(b.blocked_at * 1e3).toLocaleDateString()} `, + h("button", { type: "button", class: "btn", onclick: () => void unblockThread(listingId, b.thread).then(changed) }, t("own.unblock")) + ) + ) + ]); + }).catch(() => { + }); + return box; +} function addressCard(listingId, changed) { const root = h("div", { class: "panel addr" }); let saved = null; diff --git a/web/src/i18n.ts b/web/src/i18n.ts index f0473cd..30c006a 100644 --- a/web/src/i18n.ts +++ b/web/src/i18n.ts @@ -199,6 +199,11 @@ const de = { "own.delete": "Unterhaltung löschen", "own.deleteSure": "Wirklich löschen? Sie wird von deinem Knoten entfernt.", "own.deleteYes": "Ja, löschen", + "own.block": "Blockieren", + "own.blockSure": "Blockieren? Die Unterhaltung wird gelöscht und weitere Nachrichten dieser Person werden ungelesen verworfen. Sie erfährt davon nichts.", + "own.blockYes": "Ja, blockieren", + "own.blocked": "Blockiert ({n})", + "own.unblock": "Freigeben", "own.sheetTitle": "Adresse freigeben", "own.sheetHelp": "Eine signierte Nachricht, nur für diese Person sichtbar. Ihr Bildschirm blendet sie nach dem Datum aus. Sie könnte sie trotzdem kopiert haben.", @@ -476,6 +481,11 @@ const en: Record = { "own.delete": "Delete conversation", "own.deleteSure": "Really delete? It is removed from your node.", "own.deleteYes": "Yes, delete", + "own.block": "Block", + "own.blockSure": "Block? The conversation is deleted and anything more from this person is dropped unread. They are not told.", + "own.blockYes": "Yes, block", + "own.blocked": "Blocked ({n})", + "own.unblock": "Unblock", "own.sheetTitle": "Release address", "own.sheetHelp": "A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.", diff --git a/web/src/owner.ts b/web/src/owner.ts index 5d3c7a7..3166efb 100644 --- a/web/src/owner.ts +++ b/web/src/owner.ts @@ -111,6 +111,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise void refresh()), h("p", { class: "muted small" }, t("own.limitNote")), ] : [h("p", { class: "muted pick" }, t("own.pickListing"))], @@ -132,6 +133,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())), deleteControl(listingId, thread), + blockControl(listingId, thread), ]); } else { threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : "")); @@ -451,6 +453,45 @@ function deleteControl(listingId: string, thread: string): HTMLElement { return slot; } +function blockControl(listingId: string, thread: string): HTMLElement { + const slot = h("p", null); + const ask = () => { + clear(slot); + append(slot, [ + t("own.blockSure"), + " ", + h("button", { type: "button", class: "btn", onclick: () => void o.blockThread(listingId, thread).then(() => (location.hash = `#/mine/${listingId}`)) }, t("own.blockYes")), + ]); + }; + slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.block"))); + return slot; +} + +/** The blocked conversations of one listing, each with a way to lift the block. */ +function blockedList(listingId: string, changed: () => void): HTMLElement { + const box = h("details", { class: "blocked", hidden: true }); + void o + .getBlocked() + .then((all) => { + const mine = all.filter((b) => b.listing === listingId); + if (mine.length === 0) return; + box.hidden = false; + append(box, [ + h("summary", null, t("own.blocked", { n: mine.length })), + ...mine.map((b) => + h( + "p", + { class: "muted small" }, + `#${b.thread.slice(0, 6)} · ${new Date(b.blocked_at * 1000).toLocaleDateString()} `, + h("button", { type: "button", class: "btn", onclick: () => void o.unblockThread(listingId, b.thread).then(changed) }, t("own.unblock")), + ), + ), + ]); + }) + .catch(() => {}); + return box; +} + /** The listing's saved address, shown and editable. It lives on this node only. */ function addressCard(listingId: string, changed: () => void): { root: HTMLElement } { const root = h("div", { class: "panel addr" }); diff --git a/web/src/ownerApi.ts b/web/src/ownerApi.ts index 72dd89b..fe1eacb 100644 --- a/web/src/ownerApi.ts +++ b/web/src/ownerApi.ts @@ -157,6 +157,24 @@ export async function deleteThread(listing: string, thread: string): Promise { + await call("PUT", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`); +} + +export async function unblockThread(listing: string, thread: string): Promise { + await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`); +} + +export interface Blocked { + listing: string; + thread: string; + blocked_at: number; +} + +export async function getBlocked(): Promise { + return (await call("GET", "/api/v1/blocked")) as Blocked[]; +} + /** The saved address of a listing, or null if none is saved. */ export async function getAddress(listing: string): Promise
{ try { diff --git a/web/test/helpers.ts b/web/test/helpers.ts index b974c94..333b808 100644 --- a/web/test/helpers.ts +++ b/web/test/helpers.ts @@ -220,7 +220,7 @@ export async function startGateway(opts: GatewayOptions): Promise { } // The owner's token-protected routes are played by the test, if it sets `owner`. const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname); - if (writesListing || /^\/api\/v1\/(mine|inbox|regions)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) { + if (writesListing || /^\/api\/v1\/(mine|inbox|regions|blocked)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { diff --git a/web/test/owner.test.ts b/web/test/owner.test.ts index ccf11ab..f17abbb 100644 --- a/web/test/owner.test.ts +++ b/web/test/owner.test.ts @@ -18,6 +18,7 @@ function fakeNode() { const s = { token: TOKEN, calls: [] as { method: string; path: string; body: string; auth: string }[], + blocked: [] as { listing: string; thread: string; blocked_at: number }[], address: { address: "Musterweg 7, 22765 Hamburg", phone: "+49 40 1" } as Address | null, mine: [ { id: L1, title: "Helle Wohnung", kind: "rent", price: { amount_cents: 115000, currency: "EUR", period: "month" }, expires_at: NOW + 86400 * 30, threads: 3, needs_reply: 1, hidden: 1, address_saved: true }, @@ -46,6 +47,13 @@ function fakeNode() { if (regions.includes("zzz")) return { status: 400, body: { error: `"zzz" is not a region: use 3 geohash characters` } }; return { status: 200, body: { regions } }; } + if (r.path === "/api/v1/blocked") return { status: 200, body: s.blocked }; + const bl = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})\/block$/.exec(r.path); + if (bl) { + if (r.method === "DELETE") s.blocked = s.blocked.filter((b) => b.thread !== bl[2]); + else s.blocked.push({ listing: bl[1]!, thread: bl[2]!, blocked_at: NOW }); + return { status: 204 }; + } if (r.path === "/api/v1/inbox") return { status: 200, body: s.threads.filter((t) => t.listing === r.query.get("listing")) }; const th = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(r.path); if (th) { @@ -329,6 +337,23 @@ test("deleting a conversation asks first, then goes back to the requests", async assert.equal(node.s.calls.filter((c) => c.method === "DELETE")[0]!.path, `/api/v1/inbox/${L1}/${T_LINK}`); }); +test("blocking asks first, goes back to the requests, and can be undone", async () => { + open(`#/login/${TOKEN}`); + await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings"); + page!.window.location.hash = `#/mine/${L1}/${T_LINK}`; + await page!.waitFor(() => button("Block") !== undefined, "the block button"); + + button("Block")!.click(); + assert.equal(node.s.blocked.length, 0, "nothing is blocked by one click"); + button("Yes, block")!.click(); + await page!.waitFor(() => page!.window.location.hash === `#/mine/${L1}`, "back to the requests"); + assert.equal(node.s.blocked[0]!.thread, T_LINK); + + await page!.waitFor(() => text().includes("Blocked (1)"), "the blocked list"); + button("Unblock")!.click(); + await page!.waitFor(() => node.s.blocked.length === 0, "the block lifted"); +}); + test("a token that stops working sends the owner back to sign in", async () => { open(`#/login/${TOKEN}`); await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");