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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 20:50:38 +01:00
co-authored by Claude Sonnet 5.5
parent a54094ea35
commit 13c82f8d59
14 changed files with 433 additions and 3 deletions
+10
View File
@@ -339,6 +339,16 @@ text rules below are enforced by endpoints.
unseen until room frees up (or they expire); highest work first, then oldest. 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 Envelopes that fail to decrypt are remembered (`inbox_seen`) and not tried
again. 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**. - Messages carry **no attachments and no images**.
- The decrypted inbox is stored only on the owner's node, in its database. The - 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 exact address is a private per-listing field there, never signed or
+3
View File
@@ -112,6 +112,9 @@ func New(cfg Config) http.Handler {
mux.HandleFunc("GET /api/v1/inbox/{id}/{thread}", s.admin(s.getThread)) 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("POST /api/v1/inbox/{id}/{thread}", s.admin(s.reply))
mux.HandleFunc("DELETE /api/v1/inbox/{id}/{thread}", s.admin(s.deleteThread)) 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("PUT /api/v1/listings/{id}/address", s.admin(s.putAddress))
mux.HandleFunc("GET /api/v1/listings/{id}/address", s.admin(s.getAddress)) 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.HandleFunc("DELETE /api/v1/listings/{id}/address", s.admin(s.deleteAddress))
+45
View File
@@ -2,6 +2,7 @@ package api
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"io" "io"
@@ -399,6 +400,50 @@ func (s *server) deleteThread(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent) 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 // threadRef reads {id} and {thread} from the path. The listing is always the
// node's own: the inbox holds nobody else's conversations. // node's own: the inbox holds nobody else's conversations.
func (s *server) threadRef(w http.ResponseWriter, r *http.Request) (message.Ref, string, bool) { func (s *server) threadRef(w http.ResponseWriter, r *http.Request) (message.Ref, string, bool) {
+33
View File
@@ -428,3 +428,36 @@ func TestStatusReportsMessageDifficulty(t *testing.T) {
t.Fatalf("message_difficulty = %v", st["message_difficulty"]) 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)
}
}
+50 -1
View File
@@ -133,6 +133,15 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) {
return 0, err 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 var known []candidate
fresh := map[threadKey][]candidate{} fresh := map[threadKey][]candidate{}
for k, e := range envs { for k, e := range envs {
@@ -148,9 +157,16 @@ func (i *Inbox) Collect(ctx context.Context) (int, error) {
} }
continue 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() work, _ := e.Work()
c := candidate{hash: h, env: e, plain: p, work: 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) exists, err := i.Store.HasThread(ctx, e.Listing, p.Thread)
if err != nil { if err != nil {
return 0, err return 0, err
@@ -244,6 +260,39 @@ func (i *Inbox) file(ctx context.Context, c candidate) (hidden bool, err error)
return hidden, err 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. // Reply is what the owner sends back.
type Reply struct { type Reply struct {
Type string // message.TypeText or message.TypeGrant Type string // message.TypeText or message.TypeGrant
+63
View File
@@ -414,3 +414,66 @@ func TestAddressesAndThreadsCanBeErased(t *testing.T) {
t.Fatalf("an erased conversation came back (%d)", n) 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)
}
}
+64
View File
@@ -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) `DELETE FROM addresses WHERE author = ? AND listing_id = ?`, ref.Author, ref.ID)
return err 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()
}
+14
View File
@@ -141,6 +141,15 @@ CREATE TABLE IF NOT EXISTS inbox_seen (
hash TEXT PRIMARY KEY, hash TEXT PRIMARY KEY,
expires_at INTEGER NOT NULL expires_at INTEGER NOT NULL
) WITHOUT ROWID; ) 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. -- The exact address of a listing, only ever read by its owner's node.
CREATE TABLE IF NOT EXISTS addresses ( CREATE TABLE IF NOT EXISTS addresses (
author TEXT NOT NULL, 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 { 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, 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 return n + m + k, nil
} }
+56 -1
View File
@@ -291,6 +291,11 @@ var de = {
"own.delete": "Unterhaltung l\xF6schen", "own.delete": "Unterhaltung l\xF6schen",
"own.deleteSure": "Wirklich l\xF6schen? Sie wird von deinem Knoten entfernt.", "own.deleteSure": "Wirklich l\xF6schen? Sie wird von deinem Knoten entfernt.",
"own.deleteYes": "Ja, l\xF6schen", "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.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.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", "own.fNote": "Hinweis an die Person",
@@ -543,6 +548,11 @@ var en = {
"own.delete": "Delete conversation", "own.delete": "Delete conversation",
"own.deleteSure": "Really delete? It is removed from your node.", "own.deleteSure": "Really delete? It is removed from your node.",
"own.deleteYes": "Yes, delete", "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.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.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", "own.fNote": "Note to the buyer",
@@ -4864,6 +4874,15 @@ async function sendReply(listing, thread, r) {
async function deleteThread(listing, thread) { async function deleteThread(listing, thread) {
await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(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) { async function getAddress(listing) {
try { try {
return await call("GET", `/api/v1/listings/${e(listing)}/address`); return await call("GET", `/api/v1/listings/${e(listing)}/address`);
@@ -4978,6 +4997,7 @@ async function showOwner(listingId, thread) {
addr.root, addr.root,
chips, chips,
reqBox, reqBox,
blockedList(listingId, () => void refresh()),
h("p", { class: "muted small" }, t("own.limitNote")) h("p", { class: "muted small" }, t("own.limitNote"))
] : [h("p", { class: "muted pick" }, t("own.pickListing"))] ] : [h("p", { class: "muted pick" }, t("own.pickListing"))]
); );
@@ -4995,7 +5015,8 @@ async function showOwner(listingId, thread) {
firstNote, firstNote,
addressHint, addressHint,
composer2(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())), composer2(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())),
deleteControl2(listingId, thread) deleteControl2(listingId, thread),
blockControl(listingId, thread)
]); ]);
} else { } else {
threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : "")); 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"))); slot.append(h("button", { type: "button", class: "btn", onclick: ask }, t("own.delete")));
return slot; 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) { function addressCard(listingId, changed) {
const root = h("div", { class: "panel addr" }); const root = h("div", { class: "panel addr" });
let saved = null; let saved = null;
+10
View File
@@ -199,6 +199,11 @@ const de = {
"own.delete": "Unterhaltung löschen", "own.delete": "Unterhaltung löschen",
"own.deleteSure": "Wirklich löschen? Sie wird von deinem Knoten entfernt.", "own.deleteSure": "Wirklich löschen? Sie wird von deinem Knoten entfernt.",
"own.deleteYes": "Ja, löschen", "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.sheetTitle": "Adresse freigeben",
"own.sheetHelp": "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.", "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<keyof typeof de, string> = {
"own.delete": "Delete conversation", "own.delete": "Delete conversation",
"own.deleteSure": "Really delete? It is removed from your node.", "own.deleteSure": "Really delete? It is removed from your node.",
"own.deleteYes": "Yes, delete", "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.sheetTitle": "Release address",
"own.sheetHelp": "own.sheetHelp":
"A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.", "A signed message, visible only to this person. Their screen hides it after the date. They could still have copied it.",
+41
View File
@@ -111,6 +111,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
addr!.root, addr!.root,
chips, chips,
reqBox, reqBox,
blockedList(listingId, () => void refresh()),
h("p", { class: "muted small" }, t("own.limitNote")), h("p", { class: "muted small" }, t("own.limitNote")),
] ]
: [h("p", { class: "muted pick" }, t("own.pickListing"))], : [h("p", { class: "muted pick" }, t("own.pickListing"))],
@@ -132,6 +133,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
addressHint, addressHint,
composer(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())), composer(listingId, thread, () => void refresh(), (opener) => openSheet(listingId, thread, opener, () => void refresh())),
deleteControl(listingId, thread), deleteControl(listingId, thread),
blockControl(listingId, thread),
]); ]);
} else { } else {
threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : "")); threadPane.append(h("p", { class: "muted pick" }, listingId ? t("own.pickRequest") : ""));
@@ -451,6 +453,45 @@ function deleteControl(listingId: string, thread: string): HTMLElement {
return slot; 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. */ /** The listing's saved address, shown and editable. It lives on this node only. */
function addressCard(listingId: string, changed: () => void): { root: HTMLElement } { function addressCard(listingId: string, changed: () => void): { root: HTMLElement } {
const root = h("div", { class: "panel addr" }); const root = h("div", { class: "panel addr" });
+18
View File
@@ -157,6 +157,24 @@ export async function deleteThread(listing: string, thread: string): Promise<voi
await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`); await call("DELETE", `/api/v1/inbox/${e(listing)}/${e(thread)}`);
} }
export async function blockThread(listing: string, thread: string): Promise<void> {
await call("PUT", `/api/v1/inbox/${e(listing)}/${e(thread)}/block`);
}
export async function unblockThread(listing: string, thread: string): Promise<void> {
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<Blocked[]> {
return (await call("GET", "/api/v1/blocked")) as Blocked[];
}
/** The saved address of a listing, or null if none is saved. */ /** The saved address of a listing, or null if none is saved. */
export async function getAddress(listing: string): Promise<Address | null> { export async function getAddress(listing: string): Promise<Address | null> {
try { try {
+1 -1
View File
@@ -220,7 +220,7 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
} }
// The owner's token-protected routes are played by the test, if it sets `owner`. // 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); 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 = ""; let body = "";
req.on("data", (c) => (body += c)); req.on("data", (c) => (body += c));
req.on("end", () => { req.on("end", () => {
+25
View File
@@ -18,6 +18,7 @@ function fakeNode() {
const s = { const s = {
token: TOKEN, token: TOKEN,
calls: [] as { method: string; path: string; body: string; auth: string }[], 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, address: { address: "Musterweg 7, 22765 Hamburg", phone: "+49 40 1" } as Address | null,
mine: [ 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 }, { 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` } }; if (regions.includes("zzz")) return { status: 400, body: { error: `"zzz" is not a region: use 3 geohash characters` } };
return { status: 200, body: { regions } }; 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")) }; 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); const th = /^\/api\/v1\/inbox\/([0-9a-f]{32})\/([0-9a-f]{64})$/.exec(r.path);
if (th) { 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}`); 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 () => { test("a token that stops working sends the owner back to sign in", async () => {
open(`#/login/${TOKEN}`); open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings"); await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings");