diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 5a70fb6..846b9a5 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -579,6 +579,14 @@ the reports: `hidden`, `trusted` counts per category, `others`, `signals`, (admin token): `GET /api/v1/signals`, `DELETE /api/v1/signals/{author}/{id}`, `POST /api/v1/reports` (`{listing, category, note}`). +**In the browser** (`web/src/reports.ts`). Every listing page asks the node what +it makes of the reports and says so if the node hides the listing, and who +flagged it (counts per reason; reports from reporters the node does not trust +are mentioned and not counted). A "Report this listing" form mines the proof-of-work +and sends a tip. When the operator is signed in, a second form signs a report +(or withdraws it). `#/mine/reports` is the operator's queue of tips, grouped by +listing: report as the reason a visitor gave, or dismiss. + **Not built yet:** vouching (who becomes trusted is the operator's choice for now), signed blocklists you subscribe to by curator key, an owner's signed reply to a report, and reputation for reporters whose reports are overruled. diff --git a/scripts/e2e.sh b/scripts/e2e.sh index 3450ac5..6e61ce0 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -125,6 +125,22 @@ UI=$ROOT/scripts/e2e/ui.ts node $UI buyer http://127.0.0.1:18102 http://127.0.0.1:18101 $TOKEN $AUTHOR $ID > $W/ui-buyer.txt 2>&1 \ && { sed 's/^OK /PASS: UI: /' $W/ui-buyer.txt; } || { cat $W/ui-buyer.txt; bad "the buyer flow through the web UI"; } +echo "== abuse reports: the operator's report hides the listing on A; B receives it but does not count a stranger's" +count() { curl -s "http://127.0.0.1:$1/api/v1/listings$2" | python3 -c 'import json,sys; print(len(json.load(sys.stdin)))'; } +[ "$(count 18101 '')" = 1 ] && [ "$(count 18102 '')" = 1 ] && ok "both nodes list it before any report" || bad "the listing is missing before the report" +REPORT="{\"listing\":{\"author\":\"$AUTHOR\",\"id\":\"$ID\"},\"category\":\"scam\",\"note\":\"e2e\"}" +curl -s -o /dev/null -w "%{http_code}" -X POST -d "$REPORT" http://127.0.0.1:18101/api/v1/reports | grep -q 401 && ok "reporting needs the admin token" +curl -s -X POST -H "Authorization: Bearer $TOKEN" -d "$REPORT" http://127.0.0.1:18101/api/v1/reports \ + | python3 -c 'import json,sys; s=json.load(sys.stdin); assert s["hidden"] and s["own"]=="scam", s' && ok "A signed the report and hides the listing" || bad "A did not hide it" +[ "$(count 18101 '')" = 0 ] && [ "$(count 18101 '?hidden=1')" = 1 ] && ok "A leaves it out of search; ?hidden=1 still lists it" || bad "A's search does not hide it" +curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1:18101/api/v1/listings/$AUTHOR/$ID | grep -q 200 && ok "its own link still works" || bad "a hidden listing is not reachable by its link" +wait_for "B received A's signed report" 20 bash -c "curl -s 'http://127.0.0.1:18102/api/v1/reports?author=$AUTHOR&id=$ID' | grep -q '\"others\":1'" +ok "B received it through the network" +[ "$(count 18102 '')" = 1 ] && ok "B does not trust A, so it still shows the listing" || bad "B hid a listing on a stranger's report" +sleep 1 # a newer report must be dated a second later +curl -s -X POST -H "Authorization: Bearer $TOKEN" -d "${REPORT/scam/withdrawn}" http://127.0.0.1:18101/api/v1/reports >/dev/null +[ "$(count 18101 '')" = 1 ] && ok "withdrawing the report shows the listing again" || bad "a withdrawn report still hides it" + echo "== recover on A (simulate a stolen machine)" OLD_DEVICE=$(curl -s http://127.0.0.1:18101/api/v1/status | python3 -c 'import json,sys; print(json.load(sys.stdin)["device"])') kill ${PIDS[0]}; wait ${PIDS[0]} 2>/dev/null diff --git a/web/dist/app.js b/web/dist/app.js index 8fc25c9..4081559 100644 --- a/web/dist/app.js +++ b/web/dist/app.js @@ -82,6 +82,28 @@ async function postMessage(envelope) { } throw new HttpError(res.status, detail, requiredBits); } +async function getReportSummary(author, id) { + try { + const res = await fetch(`/api/v1/reports?author=${author}&id=${id}`); + if (!res.ok) return null; + const s = await res.json(); + if (typeof s.hidden !== "boolean" || typeof s.trusted !== "object" || s.trusted === null) return null; + return { hidden: s.hidden, trusted: s.trusted, others: Number(s.others) || 0, signals: Number(s.signals) || 0, own: s.own }; + } catch { + return null; + } +} +async function postSignal(body) { + const res = await fetch("/api/v1/signals", { method: "POST", headers: { "Content-Type": "application/json" }, body }); + if (res.ok) return; + let detail = res.statusText; + try { + const b = await res.json(); + if (typeof b.error === "string") detail = b.error; + } catch { + } + throw new HttpError(res.status, detail); +} async function pollMailbox(tag, since) { const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`); if (!Array.isArray(data)) throw new Error("unexpected response"); @@ -189,6 +211,36 @@ var de = { "send.404": "Dieser Knoten kennt die Anzeige nicht (mehr), oder der Anbieter hat sein Ger\xE4t gewechselt. Lade die Anzeige neu.", "send.429": "Zu viele Nachrichten. Bitte warte einen Moment.", "send.busy": "Diese Anzeige bekommt gerade sehr viele Nachrichten. Versuche es sp\xE4ter noch einmal.", + "rep.hiddenNotice": "Diese Anzeige wird auf diesem Knoten nicht in der Suche gezeigt, weil sie gemeldet wurde. Du siehst sie, weil du den Link kennst.", + "rep.counts": "Gemeldet von vertrauensw\xFCrdigen Betreibern: {list}.", + "rep.others": "Dazu kommen {n} Meldungen von Betreibern, denen dieser Knoten nicht vertraut. Sie z\xE4hlen nicht.", + "rep.cat.scam": "Betrug", + "rep.cat.illegal": "rechtswidrige Inhalte", + "rep.cat.category": "falsche Kategorie", + "rep.cat.other": "Sonstiges", + "rep.report": "Anzeige melden", + "rep.intro": "Deine Meldung geht an den Betreiber dieses Knotens. Sie blendet nichts aus: er entscheidet.", + "rep.reason": "Grund", + "rep.note": "Anmerkung (optional)", + "rep.send": "Melden", + "rep.working": "Wird vorbereitet \u2026", + "rep.thanks": "Danke. Der Betreiber dieses Knotens wurde informiert.", + "rep.fail": "Die Meldung konnte nicht gesendet werden: {detail}", + "rep.operator": "Als Betreiber melden", + "rep.operatorIntro": "Deine Meldung wird signiert und im Netz verbreitet. Auf deinem Knoten blendet sie die Anzeige sofort aus.", + "rep.operatorSend": "Signiert melden", + "rep.withdraw": "Meine Meldung zur\xFCckziehen", + "rep.done": "Gemeldet.", + "rep.withdrawn": "Zur\xFCckgezogen.", + "rep.mine": "Deine Meldung: {what}.", + "rep.title": "Meldungen", + "rep.tipsIntro": "Hinweise von Besuchern dieses Knotens. Sie blenden nichts aus: du entscheidest, ob du selbst meldest.", + "rep.none": "Keine Hinweise von Besuchern.", + "rep.work": "Aufwand {n} Bit", + "rep.sign": "Als \u201E{what}\u201C melden", + "rep.dismiss": "Verwerfen", + "rep.open": "Anzeige ansehen", + "rep.back": "\u2190 Meine Anzeigen", "send.other": "Senden fehlgeschlagen: {detail}", "send.network": "Der Knoten ist nicht erreichbar.", "chat.back": "\u2190 Zur Anzeige", @@ -447,6 +499,36 @@ var en = { "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.busy": "This listing is receiving a lot of messages right now. Please try again later.", + "rep.hiddenNotice": "This listing is hidden from search on this node because it was reported. You can see it because you have its link.", + "rep.counts": "Reported by trusted operators: {list}.", + "rep.others": "{n} more reports came from operators this node does not trust. They do not count.", + "rep.cat.scam": "scam", + "rep.cat.illegal": "illegal content", + "rep.cat.category": "wrong category", + "rep.cat.other": "other", + "rep.report": "Report this listing", + "rep.intro": "Your report goes to the operator of this node. It hides nothing by itself: they decide.", + "rep.reason": "Reason", + "rep.note": "Note (optional)", + "rep.send": "Send report", + "rep.working": "Preparing \u2026", + "rep.thanks": "Thank you. The operator of this node has been told.", + "rep.fail": "The report could not be sent: {detail}", + "rep.operator": "Report as operator", + "rep.operatorIntro": "Your report is signed and shared with the network. On your node it hides the listing at once.", + "rep.operatorSend": "Sign and report", + "rep.withdraw": "Withdraw my report", + "rep.done": "Reported.", + "rep.withdrawn": "Withdrawn.", + "rep.mine": "Your report: {what}.", + "rep.title": "Reports", + "rep.tipsIntro": "Tips from visitors of this node. They hide nothing: you decide whether to report yourself.", + "rep.none": "No tips from visitors.", + "rep.work": "Effort {n} bits", + "rep.sign": "Report as \u201C{what}\u201D", + "rep.dismiss": "Dismiss", + "rep.open": "View listing", + "rep.back": "\u2190 My listings", "send.other": "Sending failed: {detail}", "send.network": "The node is not reachable.", "chat.back": "\u2190 Back to the listing", @@ -4913,6 +4995,15 @@ async function unblockThread(listing, thread) { async function getBlocked() { return await call("GET", "/api/v1/blocked"); } +async function getTips() { + return await call("GET", "/api/v1/signals"); +} +async function dismissTips(author, listing) { + await call("DELETE", `/api/v1/signals/${e(author)}/${e(listing)}`); +} +async function signReport(author, listing, category, note) { + await call("POST", "/api/v1/reports", { listing: { author, id: listing }, category, note }); +} async function getAddress(listing) { try { return await call("GET", `/api/v1/listings/${e(listing)}/address`); @@ -5010,6 +5101,7 @@ async function showOwner(listingId, thread) { h("p", null, h("a", { class: "btn primary", href: "#/mine/new" }, t("own.new"))), listingsBox, h("p", null, h("a", { class: "btn", href: "#/mine/regions" }, t("reg.title"))), + h("p", null, h("a", { class: "btn", href: "#/mine/reports" }, t("rep.title"))), h("p", null, h("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))) ); const reqTitle = h("h2", { class: "pane-title" }); @@ -5531,6 +5623,198 @@ function openSheet(listingId, thread, opener, done) { ); } +// src/reports.ts +var REASONS = ["scam", "illegal", "category", "other"]; +var MAX_NOTE_BYTES = 300; +var reasonLabel = (c) => REASONS.includes(c) ? t(`rep.cat.${c}`) : c; +var utf82 = (s) => new TextEncoder().encode(s).length; +async function sendTip(author, id, category, note) { + const bits = state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY; + const body = { category, created_at: nowSeconds(), listing: { author, id }, note, pow: 0, v: 1 }; + await mine(body, bits); + await postSignal(canonicalize(body)); +} +function describe2(e2) { + if (e2 instanceof Unauthorized) return t("reg.signedOut"); + if (e2 instanceof HttpError) return e2.detail; + return t("send.network"); +} +function reasonFields() { + const select2 = h("select", { name: "category" }, ...REASONS.map((c) => h("option", { value: c }, reasonLabel(c)))); + const note = h("textarea", { name: "note", rows: 3, maxlength: MAX_NOTE_BYTES, "aria-label": t("rep.note"), placeholder: t("rep.note") }); + return { + nodes: [h("label", null, t("rep.reason"), " ", select2), note], + read: () => ({ category: select2.value, note: note.value.trim() }) + }; +} +function summaryLines(sum) { + const out = []; + if (sum.hidden) out.push(h("p", { class: "note warn", role: "status" }, t("rep.hiddenNotice"))); + const counted = Object.entries(sum.trusted).filter(([, n]) => n > 0); + if (counted.length) { + out.push(h("p", { class: "muted" }, t("rep.counts", { list: counted.map(([c, n]) => `${reasonLabel(c)} (${n})`).join(", ") }))); + } + if (sum.others > 0) out.push(h("p", { class: "muted small" }, t("rep.others", { n: sum.others }))); + if (sum.own) out.push(h("p", { class: "muted" }, t("rep.mine", { what: reasonLabel(sum.own) }))); + return out; +} +function reportPanel(l) { + const lines = h("div", null); + const root = h("section", { class: "panel report" }, lines, visitorForm(l)); + const refresh = () => void getReportSummary(l.author, l.id).then((sum) => { + if (!sum) return; + clear(lines); + append(lines, summaryLines(sum)); + }); + if (getToken()) root.append(operatorForm(l, refresh)); + refresh(); + return root; +} +function visitorForm(l) { + const fields = reasonFields(); + const status = h("p", { class: "muted", role: "status" }); + const problem = h("p", { class: "error", role: "alert" }); + const button = h("button", { type: "submit", class: "btn" }, t("rep.send")); + const form = h( + "form", + { + class: "compose", + onsubmit: (ev) => { + ev.preventDefault(); + const { category, note } = fields.read(); + problem.textContent = ""; + if (utf82(note) > MAX_NOTE_BYTES) { + problem.textContent = t("rep.fail", { detail: t("rep.note") }); + return; + } + button.disabled = true; + status.textContent = t("rep.working"); + void sendTip(l.author, l.id, category, note).then(() => { + clear(form); + form.append(h("p", { role: "status" }, t("rep.thanks"))); + }).catch((e2) => { + button.disabled = false; + status.textContent = ""; + problem.textContent = t("rep.fail", { detail: describe2(e2) }); + }); + } + }, + h("p", { class: "muted" }, t("rep.intro")), + ...fields.nodes, + h("div", { class: "actions" }, button), + status, + problem + ); + return h("details", { class: "report-form" }, h("summary", null, t("rep.report")), form); +} +function operatorForm(l, changed) { + const fields = reasonFields(); + const status = h("p", { class: "muted", role: "status" }); + const problem = h("p", { class: "error", role: "alert" }); + const act = (category, note, done) => { + problem.textContent = ""; + void signReport(l.author, l.id, category, note).then(() => { + status.textContent = t(done); + changed(); + }).catch((e2) => { + problem.textContent = t("rep.fail", { detail: describe2(e2) }); + }); + }; + return h( + "details", + { class: "report-form" }, + h("summary", null, t("rep.operator")), + h( + "form", + { + class: "compose", + onsubmit: (ev) => { + ev.preventDefault(); + const { category, note } = fields.read(); + act(category, note, "rep.done"); + } + }, + h("p", { class: "muted" }, t("rep.operatorIntro")), + ...fields.nodes, + h( + "div", + { class: "actions" }, + h("button", { type: "submit", class: "btn primary" }, t("rep.operatorSend")), + h("button", { type: "button", class: "btn", onclick: () => act("withdrawn", "", "rep.withdrawn") }, t("rep.withdraw")) + ), + status, + problem + ) + ); +} +async function showReports() { + const root = document.getElementById("app"); + clear(root); + if (!getToken()) { + renderLogin(false); + return; + } + const list = h("div", null); + const problem = h("p", { class: "error", role: "alert" }); + append(root, [ + h("a", { class: "back", href: "#/mine" }, t("rep.back")), + h("h1", null, t("rep.title")), + h("p", { class: "muted" }, t("rep.tipsIntro")), + problem, + list + ]); + const load2 = async () => { + let tips; + try { + tips = await getTips(); + } catch (e2) { + if (e2 instanceof Unauthorized) return renderLogin(true); + problem.textContent = describe2(e2); + return; + } + clear(list); + if (tips.length === 0) { + list.append(h("p", { class: "muted" }, t("rep.none"))); + return; + } + const byListing = /* @__PURE__ */ new Map(); + for (const tip of tips) byListing.set(`${tip.author}/${tip.listing}`, [...byListing.get(`${tip.author}/${tip.listing}`) ?? [], tip]); + for (const group of byListing.values()) list.append(card(group, load2, problem)); + }; + await load2(); +} +function card(group, reload, problem) { + const first = group[0]; + const fail2 = (e2) => { + problem.textContent = describe2(e2); + }; + const categories = [...new Set(group.map((g) => g.category))]; + return h( + "section", + { class: "panel" }, + h("h2", null, h("a", { href: `#/l/${first.author}/${first.listing}` }, first.title || t("rep.open"))), + h( + "ul", + null, + ...group.map( + (g) => h("li", null, `${reasonLabel(g.category)}: ${g.note || "\u2013"} `, h("span", { class: "muted small" }, `(${t("rep.work", { n: g.work })})`)) + ) + ), + h( + "div", + { class: "actions" }, + ...categories.map( + (c) => h( + "button", + { type: "button", class: "btn", onclick: () => void signReport(first.author, first.listing, c, group.find((g) => g.category === c)?.note ?? "").then(reload).catch(fail2) }, + t("rep.sign", { what: reasonLabel(c) }) + ) + ), + h("button", { type: "button", class: "btn", onclick: () => void dismissTips(first.author, first.listing).then(reload).catch(fail2) }, t("rep.dismiss")) + ) + ); +} + // src/parse.ts function parseEuros(input) { const s = input.replace(/[€\s ]|eur/gi, ""); @@ -6233,7 +6517,7 @@ function navigate(hash) { if (location.hash === hash || hash === "#/" && location.hash === "") route(); else location.hash = hash; } -function card(l) { +function card2(l) { const facts = [ label("cat", l.category), l.area_m2 ? t("card.area", { n: l.area_m2 }) : "", @@ -6276,7 +6560,7 @@ async function loadResults(gen, q, root) { for (const raw of items) { const verdict = verifyListing(raw, opts); if (verdict.ok) { - cards.append(card(raw)); + cards.append(card2(raw)); shown++; } else { hidden++; @@ -6388,7 +6672,8 @@ function listingBody(l) { ), l.description ? h("section", { class: "panel" }, h("p", { class: "desc" }, l.description)) : h("span"), 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"), - contactPanel(l) + contactPanel(l), + reportPanel(l) ]; } async function showDetail(author, id) { @@ -6455,6 +6740,7 @@ function route() { else if (c) void showConversation(c[1], c[2], c[3]); else if (path === "/messages") showInbox(); else if (path === "/mine/regions") showRegions(); + else if (path === "/mine/reports") void showReports(); else if (path === "/mine/new") void showPublish(); else if (edit) void showPublish(edit[1]); else if (own) void showOwner(own[1], own[2]); diff --git a/web/src/api.ts b/web/src/api.ts index e50dc88..695b4c1 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -88,6 +88,47 @@ export async function postMessage(envelope: Envelope): Promise { throw new HttpError(res.status, detail, requiredBits); } +/** What one node makes of the abuse reports about a listing. */ +export interface ReportSummary { + /** The node's own rules hide the listing from search. */ + hidden: boolean; + /** Reports from reporters this node trusts, by category. */ + trusted: Record; + /** Reports from reporters it does not trust: shown, never counted. */ + others: number; + /** Tips from visitors waiting for the operator. */ + signals: number; + /** The operator's own report, if any. */ + own?: string; +} + +/** The reports about a listing, or null if this node cannot say. */ +export async function getReportSummary(author: string, id: string): Promise { + try { + const res = await fetch(`/api/v1/reports?author=${author}&id=${id}`); + if (!res.ok) return null; + const s = (await res.json()) as Partial; + if (typeof s.hidden !== "boolean" || typeof s.trusted !== "object" || s.trusted === null) return null; + return { hidden: s.hidden, trusted: s.trusted, others: Number(s.others) || 0, signals: Number(s.signals) || 0, own: s.own }; + } catch { + return null; + } +} + +/** Tells the node's operator about a listing. Unsigned: backed only by proof-of-work (see sendTip). */ +export async function postSignal(body: string): Promise { + const res = await fetch("/api/v1/signals", { method: "POST", headers: { "Content-Type": "application/json" }, body }); + if (res.ok) return; + let detail = res.statusText; + try { + const b = (await res.json()) as { error?: unknown }; + if (typeof b.error === "string") detail = b.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 { const data = await getJSON(`/api/v1/messages?mailbox=${encodeURIComponent(tag)}&since=${since}`); diff --git a/web/src/i18n.ts b/web/src/i18n.ts index 7b8cb83..35083b4 100644 --- a/web/src/i18n.ts +++ b/web/src/i18n.ts @@ -72,6 +72,36 @@ const de = { "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.busy": "Diese Anzeige bekommt gerade sehr viele Nachrichten. Versuche es später noch einmal.", + "rep.hiddenNotice": "Diese Anzeige wird auf diesem Knoten nicht in der Suche gezeigt, weil sie gemeldet wurde. Du siehst sie, weil du den Link kennst.", + "rep.counts": "Gemeldet von vertrauenswürdigen Betreibern: {list}.", + "rep.others": "Dazu kommen {n} Meldungen von Betreibern, denen dieser Knoten nicht vertraut. Sie zählen nicht.", + "rep.cat.scam": "Betrug", + "rep.cat.illegal": "rechtswidrige Inhalte", + "rep.cat.category": "falsche Kategorie", + "rep.cat.other": "Sonstiges", + "rep.report": "Anzeige melden", + "rep.intro": "Deine Meldung geht an den Betreiber dieses Knotens. Sie blendet nichts aus: er entscheidet.", + "rep.reason": "Grund", + "rep.note": "Anmerkung (optional)", + "rep.send": "Melden", + "rep.working": "Wird vorbereitet …", + "rep.thanks": "Danke. Der Betreiber dieses Knotens wurde informiert.", + "rep.fail": "Die Meldung konnte nicht gesendet werden: {detail}", + "rep.operator": "Als Betreiber melden", + "rep.operatorIntro": "Deine Meldung wird signiert und im Netz verbreitet. Auf deinem Knoten blendet sie die Anzeige sofort aus.", + "rep.operatorSend": "Signiert melden", + "rep.withdraw": "Meine Meldung zurückziehen", + "rep.done": "Gemeldet.", + "rep.withdrawn": "Zurückgezogen.", + "rep.mine": "Deine Meldung: {what}.", + "rep.title": "Meldungen", + "rep.tipsIntro": "Hinweise von Besuchern dieses Knotens. Sie blenden nichts aus: du entscheidest, ob du selbst meldest.", + "rep.none": "Keine Hinweise von Besuchern.", + "rep.work": "Aufwand {n} Bit", + "rep.sign": "Als „{what}“ melden", + "rep.dismiss": "Verwerfen", + "rep.open": "Anzeige ansehen", + "rep.back": "← Meine Anzeigen", "send.other": "Senden fehlgeschlagen: {detail}", "send.network": "Der Knoten ist nicht erreichbar.", "chat.back": "← Zur Anzeige", @@ -355,6 +385,36 @@ const en: Record = { "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.busy": "This listing is receiving a lot of messages right now. Please try again later.", + "rep.hiddenNotice": "This listing is hidden from search on this node because it was reported. You can see it because you have its link.", + "rep.counts": "Reported by trusted operators: {list}.", + "rep.others": "{n} more reports came from operators this node does not trust. They do not count.", + "rep.cat.scam": "scam", + "rep.cat.illegal": "illegal content", + "rep.cat.category": "wrong category", + "rep.cat.other": "other", + "rep.report": "Report this listing", + "rep.intro": "Your report goes to the operator of this node. It hides nothing by itself: they decide.", + "rep.reason": "Reason", + "rep.note": "Note (optional)", + "rep.send": "Send report", + "rep.working": "Preparing …", + "rep.thanks": "Thank you. The operator of this node has been told.", + "rep.fail": "The report could not be sent: {detail}", + "rep.operator": "Report as operator", + "rep.operatorIntro": "Your report is signed and shared with the network. On your node it hides the listing at once.", + "rep.operatorSend": "Sign and report", + "rep.withdraw": "Withdraw my report", + "rep.done": "Reported.", + "rep.withdrawn": "Withdrawn.", + "rep.mine": "Your report: {what}.", + "rep.title": "Reports", + "rep.tipsIntro": "Tips from visitors of this node. They hide nothing: you decide whether to report yourself.", + "rep.none": "No tips from visitors.", + "rep.work": "Effort {n} bits", + "rep.sign": "Report as “{what}”", + "rep.dismiss": "Dismiss", + "rep.open": "View listing", + "rep.back": "← My listings", "send.other": "Sending failed: {detail}", "send.network": "The node is not reachable.", "chat.back": "← Back to the listing", diff --git a/web/src/main.ts b/web/src/main.ts index 432da65..7ce81f4 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -5,6 +5,7 @@ import { decodeGeohash } from "./geohash.ts"; import { lang, t, type Key } from "./i18n.ts"; import { contactPanel, showConversation, showInbox } from "./chat.ts"; import { showOwner } from "./owner.ts"; +import { reportPanel, showReports } from "./reports.ts"; import { getToken, setToken } from "./ownerApi.ts"; import { showPublish } from "./publish.ts"; import { showRegions } from "./regions.ts"; @@ -299,6 +300,7 @@ function listingBody(l: Listing): HTMLElement[] { ? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f)))) : h("span"), contactPanel(l), + reportPanel(l), ]; } @@ -377,6 +379,7 @@ function route(): void { else if (c) void showConversation(c[1]!, c[2]!, c[3]!); else if (path === "/messages") showInbox(); else if (path === "/mine/regions") showRegions(); + else if (path === "/mine/reports") void showReports(); else if (path === "/mine/new") void showPublish(); else if (edit) void showPublish(edit[1]); else if (own) void showOwner(own[1], own[2]); diff --git a/web/src/message.ts b/web/src/message.ts index 588d21a..34ed356 100644 --- a/web/src/message.ts +++ b/web/src/message.ts @@ -213,7 +213,7 @@ const tick = () => new Promise((r) => setTimeout(r, 0)); * 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 { +export async function mine(env: { pow: number }, difficulty: number): Promise { const canon = canonicalize({ ...env, pow: 0 }); const marker = '"pow":0,'; const at = canon.indexOf(marker); diff --git a/web/src/owner.ts b/web/src/owner.ts index 3166efb..079509a 100644 --- a/web/src/owner.ts +++ b/web/src/owner.ts @@ -91,6 +91,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise { return (await call("GET", "/api/v1/blocked")) as Blocked[]; } +/** A visitor's tip about a listing, as the operator sees it. */ +export interface Tip { + id: number; + author: string; + listing: string; + title?: string; + category: string; + note: string; + created_at: number; + work: number; +} + +export async function getTips(): Promise { + return (await call("GET", "/api/v1/signals")) as Tip[]; +} + +export async function dismissTips(author: string, listing: string): Promise { + await call("DELETE", `/api/v1/signals/${e(author)}/${e(listing)}`); +} + +/** Signs a report as this node's operator and shares it; the answer is the node's new view. */ +export async function signReport(author: string, listing: string, category: string, note: string): Promise { + await call("POST", "/api/v1/reports", { listing: { author, id: listing }, category, note }); +} + /** The saved address of a listing, or null if none is saved. */ export async function getAddress(listing: string): Promise
{ try { diff --git a/web/src/reports.ts b/web/src/reports.ts new file mode 100644 index 0000000..e64fb34 --- /dev/null +++ b/web/src/reports.ts @@ -0,0 +1,238 @@ +// Abuse reports in the browser: the notice on a flagged listing, the form a +// visitor uses to tip off the node's operator, and the operator's own report +// form and queue of tips. Nothing here hides anything: a node's rules do, and +// they are the operator's (see "Abuse reports" in docs/PROTOCOL.md). + +import { HttpError, getReportSummary, postSignal, type ReportSummary } from "./api.ts"; +import { append, clear, h } from "./dom.ts"; +import { t, type Key } from "./i18n.ts"; +import { canonicalize } from "./jcs.ts"; +import { DEFAULT_MESSAGE_DIFFICULTY, mine } from "./message.ts"; +import { renderLogin } from "./owner.ts"; +import { Unauthorized, dismissTips, getToken, getTips, signReport, type Tip } from "./ownerApi.ts"; +import { nowSeconds, state } from "./state.ts"; +import type { Listing } from "./verify.ts"; + +/** The reasons a visitor or an operator can give, in the order they are offered. */ +const REASONS = ["scam", "illegal", "category", "other"] as const; +const MAX_NOTE_BYTES = 300; + +const reasonLabel = (c: string): string => (REASONS as readonly string[]).includes(c) ? t(`rep.cat.${c}` as Key) : c; +const utf8 = (s: string) => new TextEncoder().encode(s).length; + +/** + * Tells the node's operator about a listing. A visitor has no key, so the + * request is not signed: it is backed by proof-of-work, mined here like the + * proof of a message, and the node keeps it for its operator only. + */ +async function sendTip(author: string, id: string, category: string, note: string): Promise { + const bits = state.node?.message_difficulty ?? DEFAULT_MESSAGE_DIFFICULTY; + // Keys in canonical order; `pow` must be followed by another key (see mine()). + const body = { category, created_at: nowSeconds(), listing: { author, id }, note, pow: 0, v: 1 }; + await mine(body, bits); + await postSignal(canonicalize(body)); +} + +function describe(e: unknown): string { + if (e instanceof Unauthorized) return t("reg.signedOut"); + if (e instanceof HttpError) return e.detail; + return t("send.network"); +} + +/** A select of reasons and a note box, with the way to read them back. */ +function reasonFields(): { nodes: HTMLElement[]; read: () => { category: string; note: string } } { + const select = h("select", { name: "category" }, ...REASONS.map((c) => h("option", { value: c }, reasonLabel(c)))); + const note = h("textarea", { name: "note", rows: 3, maxlength: MAX_NOTE_BYTES, "aria-label": t("rep.note"), placeholder: t("rep.note") }); + return { + nodes: [h("label", null, t("rep.reason"), " ", select), note], + read: () => ({ category: select.value, note: note.value.trim() }), + }; +} + +/** What this node makes of the reports about the listing, as a few lines of text. */ +function summaryLines(sum: ReportSummary): HTMLElement[] { + const out: HTMLElement[] = []; + if (sum.hidden) out.push(h("p", { class: "note warn", role: "status" }, t("rep.hiddenNotice"))); + const counted = Object.entries(sum.trusted).filter(([, n]) => n > 0); + if (counted.length) { + out.push(h("p", { class: "muted" }, t("rep.counts", { list: counted.map(([c, n]) => `${reasonLabel(c)} (${n})`).join(", ") }))); + } + if (sum.others > 0) out.push(h("p", { class: "muted small" }, t("rep.others", { n: sum.others }))); + if (sum.own) out.push(h("p", { class: "muted" }, t("rep.mine", { what: reasonLabel(sum.own) }))); + return out; +} + +/** + * The report section of a listing page. It fills in once the node has said what + * it makes of the reports, and works without that: the forms are always there. + */ +export function reportPanel(l: Listing): HTMLElement { + const lines = h("div", null); + const root = h("section", { class: "panel report" }, lines, visitorForm(l)); + const refresh = () => + void getReportSummary(l.author, l.id).then((sum) => { + if (!sum) return; + clear(lines); + append(lines, summaryLines(sum)); + }); + if (getToken()) root.append(operatorForm(l, refresh)); + refresh(); + return root; +} + +function visitorForm(l: Listing): HTMLElement { + const fields = reasonFields(); + const status = h("p", { class: "muted", role: "status" }); + const problem = h("p", { class: "error", role: "alert" }); + const button = h("button", { type: "submit", class: "btn" }, t("rep.send")); + const form = h( + "form", + { + class: "compose", + onsubmit: (ev: Event) => { + ev.preventDefault(); + const { category, note } = fields.read(); + problem.textContent = ""; + if (utf8(note) > MAX_NOTE_BYTES) { + problem.textContent = t("rep.fail", { detail: t("rep.note") }); + return; + } + button.disabled = true; + status.textContent = t("rep.working"); + void sendTip(l.author, l.id, category, note) + .then(() => { + clear(form); + form.append(h("p", { role: "status" }, t("rep.thanks"))); + }) + .catch((e: unknown) => { + button.disabled = false; + status.textContent = ""; + problem.textContent = t("rep.fail", { detail: describe(e) }); + }); + }, + }, + h("p", { class: "muted" }, t("rep.intro")), + ...fields.nodes, + h("div", { class: "actions" }, button), + status, + problem, + ); + return h("details", { class: "report-form" }, h("summary", null, t("rep.report")), form); +} + +/** The operator's own signed report (or taking it back). Only offered with the admin token. */ +function operatorForm(l: Listing, changed: () => void): HTMLElement { + const fields = reasonFields(); + const status = h("p", { class: "muted", role: "status" }); + const problem = h("p", { class: "error", role: "alert" }); + const act = (category: string, note: string, done: Key) => { + problem.textContent = ""; + void signReport(l.author, l.id, category, note) + .then(() => { + status.textContent = t(done); + changed(); + }) + .catch((e: unknown) => { + problem.textContent = t("rep.fail", { detail: describe(e) }); + }); + }; + return h( + "details", + { class: "report-form" }, + h("summary", null, t("rep.operator")), + h( + "form", + { + class: "compose", + onsubmit: (ev: Event) => { + ev.preventDefault(); + const { category, note } = fields.read(); + act(category, note, "rep.done"); + }, + }, + h("p", { class: "muted" }, t("rep.operatorIntro")), + ...fields.nodes, + h( + "div", + { class: "actions" }, + h("button", { type: "submit", class: "btn primary" }, t("rep.operatorSend")), + h("button", { type: "button", class: "btn", onclick: () => act("withdrawn", "", "rep.withdrawn") }, t("rep.withdraw")), + ), + status, + problem, + ), + ); +} + +// --- the operator's queue ----------------------------------------------------------- + +/** The tips visitors left on this node, one card per listing. */ +export async function showReports(): Promise { + const root = document.getElementById("app")!; + clear(root); + if (!getToken()) { + renderLogin(false); + return; + } + const list = h("div", null); + const problem = h("p", { class: "error", role: "alert" }); + append(root, [ + h("a", { class: "back", href: "#/mine" }, t("rep.back")), + h("h1", null, t("rep.title")), + h("p", { class: "muted" }, t("rep.tipsIntro")), + problem, + list, + ]); + + const load = async (): Promise => { + let tips: Tip[]; + try { + tips = await getTips(); + } catch (e) { + if (e instanceof Unauthorized) return renderLogin(true); + problem.textContent = describe(e); + return; + } + clear(list); + if (tips.length === 0) { + list.append(h("p", { class: "muted" }, t("rep.none"))); + return; + } + const byListing = new Map(); + for (const tip of tips) byListing.set(`${tip.author}/${tip.listing}`, [...(byListing.get(`${tip.author}/${tip.listing}`) ?? []), tip]); + for (const group of byListing.values()) list.append(card(group, load, problem)); + }; + await load(); +} + +function card(group: Tip[], reload: () => Promise, problem: HTMLElement): HTMLElement { + const first = group[0]!; + const fail = (e: unknown) => { + problem.textContent = describe(e); + }; + const categories = [...new Set(group.map((g) => g.category))]; + return h( + "section", + { class: "panel" }, + h("h2", null, h("a", { href: `#/l/${first.author}/${first.listing}` }, first.title || t("rep.open"))), + h( + "ul", + null, + ...group.map((g) => + h("li", null, `${reasonLabel(g.category)}: ${g.note || "–"} `, h("span", { class: "muted small" }, `(${t("rep.work", { n: g.work })})`)), + ), + ), + h( + "div", + { class: "actions" }, + ...categories.map((c) => + h( + "button", + { type: "button", class: "btn", onclick: () => void signReport(first.author, first.listing, c, group.find((g) => g.category === c)?.note ?? "").then(reload).catch(fail) }, + t("rep.sign", { what: reasonLabel(c) }), + ), + ), + h("button", { type: "button", class: "btn", onclick: () => void dismissTips(first.author, first.listing).then(reload).catch(fail) }, t("rep.dismiss")), + ), + ); +} diff --git a/web/test/chat.test.ts b/web/test/chat.test.ts index 2737a30..73e27c2 100644 --- a/web/test/chat.test.ts +++ b/web/test/chat.test.ts @@ -56,7 +56,7 @@ test("a first message is encrypted, mined and sent; the conversation opens", asy // 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); + assert.equal(p.document.querySelector("section.contact textarea"), null); } finally { p.close(); } diff --git a/web/test/helpers.ts b/web/test/helpers.ts index f2234a8..2055cdc 100644 --- a/web/test/helpers.ts +++ b/web/test/helpers.ts @@ -176,6 +176,12 @@ export interface Gateway { mailboxes: Map; /** Make POST /api/v1/messages answer with this status and error. */ postFails?: { status: number; error: string }; + /** What GET /api/v1/reports answers; unset, the route does not exist (an older node). */ + reports?: unknown; + /** Bodies POSTed to /api/v1/signals (a visitor's tips), in order. */ + tips: string[]; + /** Make POST /api/v1/signals answer with this status and error. */ + tipFails?: { status: number; error: string }; /** What GET /api/v1/messages/required answers (bits); unset, the route does not exist (an older node). */ requiredBits?: number; /** Refuse the next POST once with 429, asking for this many bits of proof-of-work. */ @@ -209,6 +215,7 @@ export async function startGateway(opts: GatewayOptions): Promise { queries, posted, mailboxes, + tips: [], close: () => new Promise((ok) => server.close(() => ok())), }; const server: Server = createServer((req, res) => { @@ -222,9 +229,23 @@ export async function startGateway(opts: GatewayOptions): Promise { res.writeHead(200, { "Content-Type": "text/tab-separated-values" }); return void res.end(readFileSync(new URL("../static/places.tsv", import.meta.url))); } + if (url.pathname === "/api/v1/reports" && req.method === "GET") { + return gateway.reports === undefined ? json(404, { error: "not found" }) : json(200, gateway.reports); + } + if (url.pathname === "/api/v1/signals" && req.method === "POST") { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + if (gateway.tipFails) return json(gateway.tipFails.status, { error: gateway.tipFails.error }); + gateway.tips.push(body); + res.writeHead(202); + res.end(); + }); + return; + } // 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|blocked)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) { + if (writesListing || /^\/api\/v1\/(mine|inbox|regions|blocked|signals|reports)|^\/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/reports.test.ts b/web/test/reports.test.ts new file mode 100644 index 0000000..b992ee9 --- /dev/null +++ b/web/test/reports.test.ts @@ -0,0 +1,168 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { afterEach, beforeEach, test } from "node:test"; + +import { canonicalize } from "../src/jcs.ts"; +import { NOW, newParty, openPage, startGateway, type Gateway, type Page } from "./helpers.ts"; + +const TOKEN = "cd34".repeat(16); +const seller = newParty({ title: "Altbau in Ottensen" }); +const ref = { author: seller.author, id: seller.listing.id }; +const detail = `#/l/${ref.author}/${ref.id}`; + +let gw: Gateway; +let page: Page | undefined; +let calls: { method: string; path: string; body: string; auth: string }[]; + +beforeEach(async () => { + gw = await startGateway({ listings: [seller.listing] }); + calls = []; +}); +afterEach(async () => { + page?.close(); + page = undefined; + await gw.close(); +}); + +const open = (hash: string) => (page = openPage(gw.url, hash)); +const text = () => page!.document.body.textContent ?? ""; +const qa = (sel: string) => [...page!.document.querySelectorAll(sel)]; +const button = (label: string) => qa("button").find((b) => b.textContent === label) as HTMLButtonElement | undefined; + +/** Fills the first form of the report panel (the visitor's) and submits it. */ +function tipOff(category: string, note: string): void { + const form = page!.document.querySelector("section.report details.report-form form")!; + (form.querySelector("select") as HTMLSelectElement).value = category; + (form.querySelector("textarea") as HTMLTextAreaElement).value = note; + form.dispatchEvent(new page!.window.Event("submit", { cancelable: true })); +} + +const zeroBits = (s: string): number => { + let bits = 0; + for (const byte of createHash("sha256").update(s).digest()) { + if (byte === 0) { + bits += 8; + continue; + } + return bits + Math.clz32(byte) - 24; + } + return bits; +}; + +test("a listing the node hides says so, and who flagged it", async () => { + gw.reports = { hidden: true, trusted: { scam: 2, illegal: 1 }, others: 3, signals: 0 }; + open(detail); + await page!.waitFor(() => /hidden from search/.test(text()), "the notice"); + assert.match(text(), /scam \(2\)/); + assert.match(text(), /illegal content \(1\)/); + assert.match(text(), /3 more reports/); + assert.match(text(), /Altbau in Ottensen/, "the listing itself is still shown"); +}); + +test("a listing without reports shows no notice, and an older node without the route still works", async () => { + gw.reports = { hidden: false, trusted: {}, others: 0, signals: 0 }; + open(detail); + await page!.waitFor(() => button("Send report") !== undefined, "the report form"); + assert.doesNotMatch(text(), /hidden from search/); + page!.close(); + + gw.reports = undefined; // 404 + open(detail); + await page!.waitFor(() => button("Send report") !== undefined, "the report form without a summary"); +}); + +test("a visitor's tip is mined, canonical and sent to the node, and nothing else happens", async () => { + open(detail); + await page!.waitFor(() => button("Send report") !== undefined, "the report form"); + tipOff("scam", "Will Vorkasse nach Spanien"); + await page!.waitFor(() => gw.tips.length === 1, "the tip to arrive"); + + const body = gw.tips[0]!; + const sent = JSON.parse(body) as Record; + assert.equal(body, canonicalize(sent), "the node only accepts the canonical form"); + assert.deepEqual(sent.listing, ref); + assert.equal(sent.category, "scam"); + assert.equal(sent.note, "Will Vorkasse nach Spanien"); + assert.equal(sent.v, 1); + assert.ok(zeroBits(body) >= 6, "it did the proof-of-work the node asked for"); + assert.ok(Math.abs((sent.created_at as number) - NOW) < 60, "dated by the page's clock"); + + await page!.waitFor(() => /Thank you/.test(text()), "thanks"); + assert.equal(button("Send report"), undefined, "the form is gone once it was sent"); +}); + +test("a refused tip is explained and the text is kept", async () => { + gw.tipFails = { status: 429, error: "too many requests from this address; try again in a minute" }; + open(detail); + await page!.waitFor(() => button("Send report") !== undefined, "the report form"); + tipOff("other", "Sieht komisch aus"); + await page!.waitFor(() => /too many requests/.test(text()), "the node's explanation"); + assert.equal(button("Send report")!.disabled, false, "the visitor can try again"); + assert.equal(page!.document.querySelector("section.report textarea")!.value, "Sieht komisch aus"); +}); + +test("only the signed-in operator gets the form that signs a report", async () => { + open(detail); + await page!.waitFor(() => button("Send report") !== undefined, "the report form"); + assert.doesNotMatch(text(), /Report as operator/, "a visitor must not be offered it"); + page!.close(); + + gw.owner = (r) => { + calls.push({ method: r.method, path: r.path, body: r.body, auth: r.auth }); + return r.method === "POST" && r.path === "/api/v1/reports" ? { status: 200, body: {} } : undefined; + }; + open(`#/login/${TOKEN}`); + await page!.waitFor(() => page!.window.location.hash === "#/mine", "signed in"); + page!.window.location.hash = detail; + await page!.waitFor(() => /Report as operator/.test(text()), "the operator's form"); + + const form = qa("section.report details.report-form form")[1]!; + (form.querySelector("select") as HTMLSelectElement).value = "illegal"; + (form.querySelector("textarea") as HTMLTextAreaElement).value = "bestätigt"; + form.dispatchEvent(new page!.window.Event("submit", { cancelable: true })); + await page!.waitFor(() => calls.some((c) => c.method === "POST" && c.path === "/api/v1/reports"), "the report"); + + const post = calls.find((c) => c.method === "POST" && c.path === "/api/v1/reports")!; + assert.equal(post.auth, `Bearer ${TOKEN}`); + assert.deepEqual(JSON.parse(post.body), { listing: ref, category: "illegal", note: "bestätigt" }); + + button("Withdraw my report")!.click(); + await page!.waitFor(() => calls.filter((c) => c.method === "POST" && c.path === "/api/v1/reports").length === 2, "the withdrawal"); + assert.equal(JSON.parse(calls.filter((c) => c.method === "POST")[1]!.body).category, "withdrawn"); +}); + +test("the operator's queue lists tips by listing; they can be turned into a report or dismissed", async () => { + const tips = [ + { id: 1, author: ref.author, listing: ref.id, title: "Altbau in Ottensen", category: "scam", note: "Vorkasse", created_at: 1, work: 19 }, + { id: 2, author: ref.author, listing: ref.id, title: "Altbau in Ottensen", category: "other", note: "", created_at: 2, work: 14 }, + ]; + gw.owner = (r) => { + calls.push({ method: r.method, path: r.path, body: r.body, auth: r.auth }); + if (r.method === "GET" && r.path === "/api/v1/signals") return { status: 200, body: tips }; + if (r.method === "POST" && r.path === "/api/v1/reports") return { status: 200, body: {} }; + if (r.method === "DELETE") return { status: 204 }; + return undefined; + }; + open(`#/login/${TOKEN}`); + await page!.waitFor(() => page!.window.location.hash === "#/mine", "signed in"); + page!.window.location.hash = "#/mine/reports"; + await page!.waitFor(() => /Vorkasse/.test(text()), "the tips"); + assert.equal(qa("section.panel").length, 1, "two tips about one listing make one card"); + assert.match(text(), /Effort 19 bits/); + assert.match(text(), /Altbau in Ottensen/); + + button("Report as “scam”")!.click(); + await page!.waitFor(() => calls.some((c) => c.method === "POST" && c.path === "/api/v1/reports"), "the report"); + assert.deepEqual(JSON.parse(calls.find((c) => c.path === "/api/v1/reports")!.body), { + listing: ref, category: "scam", note: "Vorkasse", + }); + + button("Dismiss")!.click(); + await page!.waitFor(() => calls.some((c) => c.method === "DELETE"), "the dismissal"); + assert.equal(calls.find((c) => c.method === "DELETE")!.path, `/api/v1/signals/${ref.author}/${ref.id}`); +}); + +test("without signing in the queue leads to the sign-in", async () => { + open("#/mine/reports"); + await page!.waitFor(() => /sign in|Sign in|token/i.test(text()), "the sign-in"); +});