Publish, edit, renew and delete listings from the web UI

- Form at #/mine/new and #/mine/<id>/edit: coordinates pasted and encoded
  to a precision-6 geohash in the browser (about 1 km, OSM link to check, no
  map tiles), euro price parsing, optional exact address saved on the node only
- Region guard: refuses places the node does not follow; region fixed on edit
- Owner view: days left with a warning under 5 days, manual Renew (30 days),
  Edit, Delete with confirmation
- Tests (jsdom and pure logic), docs, rebuilt web/dist

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 20:18:08 +01:00
co-authored by Claude Sonnet 5.5
parent 7348067350
commit d021989f09
16 changed files with 1846 additions and 87 deletions
+2 -1
View File
@@ -212,7 +212,8 @@ export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
res.end(JSON.stringify(body));
};
// The owner's token-protected routes are played by the test, if it sets `owner`.
if (/^\/api\/v1\/(mine|inbox)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
const writesListing = req.method !== "GET" && /^\/api\/v1\/listings(\/[0-9a-f]{32})?$/.test(url.pathname);
if (writesListing || /^\/api\/v1\/(mine|inbox)|^\/api\/v1\/listings\/[0-9a-f]{32}\/address$/.test(url.pathname)) {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
+118
View File
@@ -0,0 +1,118 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { MAX_LIFETIME_DAYS, draftFromListing } from "../src/draft.ts";
import { parseEuros, parseRoomsX2 } from "../src/parse.ts";
import { cellMetres, decodeGeohash, encodeGeohash, parseCoordinates } from "../src/geohash.ts";
import type { Listing } from "../src/verify.ts";
test("geohash encoding matches known vectors", () => {
assert.equal(encodeGeohash(57.64911, 10.40744, 11), "u4pruydqqvj"); // the classic example
assert.equal(encodeGeohash(42.605, -5.603, 5), "ezs42"); // from the geohash specification
assert.equal(encodeGeohash(0, 0, 1), "s");
assert.equal(encodeGeohash(-90, -180, 6), "000000");
assert.equal(encodeGeohash(53.5511, 9.9937).length, 6);
});
test("encoding agrees with the geohash the Go code wrote", () => {
const fx = JSON.parse(readFileSync(new URL("../../internal/listing/testdata/fixture.json", import.meta.url), "utf8")) as { listing: Listing };
const g = fx.listing.geohash;
const area = decodeGeohash(g)!;
assert.equal(encodeGeohash(area.lat, area.lon, g.length), g);
});
test("encode and decode round trip within the cell", () => {
for (const [lat, lon] of [[53.5511, 9.9937], [48.1371, 11.5754], [-33.8688, 151.2093], [89.9, 179.9], [-89.9, -179.9], [0.0001, -0.0001]] as const) {
const g = encodeGeohash(lat, lon);
const a = decodeGeohash(g)!;
assert.ok(Math.abs(a.lat - lat) <= a.latErr, `lat of ${g}`);
assert.ok(Math.abs(a.lon - lon) <= a.lonErr, `lon of ${g}`);
assert.equal(encodeGeohash(a.lat, a.lon), g, "the centre of a cell encodes to the same cell");
}
});
test("a published cell is about a kilometre wide", () => {
const c = cellMetres(encodeGeohash(53.5511, 9.9937))!;
assert.ok(c.height > 500 && c.height < 700, `height ${c.height}`);
assert.ok(c.width > 600 && c.width < 1300, `width ${c.width}`);
assert.equal(cellMetres("!!"), null);
});
test("coordinates are read from what people copy from maps", () => {
const hh = { lat: 53.5511, lon: 9.9937 };
for (const text of [
"53.5511, 9.9937",
"53.5511,9.9937",
" 53.5511 , 9.9937 ",
"53.5511; 9.9937",
"53,5511; 9,9937", // German decimal comma, semicolon between
"53.5511 9.9937",
"53,5511 9,9937",
"https://www.openstreetmap.org/#map=17/53.5511/9.9937",
"https://www.openstreetmap.org/?mlat=53.5511&mlon=9.9937#map=14/53.5511/9.9937",
"https://www.google.com/maps/place/Hamburg/@53.5511,9.9937,15z/data=!3m1",
]) {
assert.deepEqual(parseCoordinates(text), hh, text);
}
assert.deepEqual(parseCoordinates("-33.8688, 151.2093"), { lat: -33.8688, lon: 151.2093 });
assert.deepEqual(parseCoordinates("53, 9"), { lat: 53, lon: 9 });
});
test("things that are not a position are refused", () => {
for (const text of ["", "Hamburg", "53.5511", "91, 10", "10, 181", "53.5511, 9.9937, 12", "a, b", "1e3, 5", "NaN, 1", "53.5511 / 9.9937 / 4", "https://example.org/x"]) {
assert.equal(parseCoordinates(text), null, JSON.stringify(text));
}
});
test("euro amounts are read in German and English notation", () => {
const ok: Record<string, number> = {
"1150": 115000,
"1.150": 115000, // thousands separator
"1,150": 115000,
"1.150,50": 115050,
"1,150.50": 115050,
"1150.5": 115050,
"1150,5": 115050,
"1150.50": 115050,
"€ 1 150": 115000,
"1150 EUR": 115000,
"485.000": 48500000,
"1.485.000,00": 148500000,
"0,5": 50,
"12": 1200,
};
for (const [text, cents] of Object.entries(ok)) assert.equal(parseEuros(text), cents, text);
for (const text of ["", "0", "0,00", "-5", "abc", "1,2,3x", "12.345,678", "1e5", "99999999999999999999"]) {
assert.equal(parseEuros(text), null, JSON.stringify(text));
}
});
test("rooms are read in half steps", () => {
assert.equal(parseRoomsX2("2"), 4);
assert.equal(parseRoomsX2("2.5"), 5);
assert.equal(parseRoomsX2("2,5"), 5);
assert.equal(parseRoomsX2(" 0.5 "), 1);
assert.equal(parseRoomsX2("0"), 0);
for (const bad of ["", "2.3", "-1", "abc", "101", "1/2"]) assert.equal(parseRoomsX2(bad), null, bad);
});
test("a draft reproduces a listing for a fresh term", () => {
const l = {
kind: "rent", category: "apartment", geohash: "u1x0nw",
price: { amount_cents: 115000, currency: "EUR", period: "month" },
area_m2: 62, rooms_x2: 5, features: ["Balkon"], title: "Helle Wohnung", description: "Ruhig.\nSüdseite.",
} as unknown as Listing;
assert.deepEqual(draftFromListing(l), {
kind: "rent", category: "apartment", geohash: "u1x0nw",
price: { amount_cents: 115000, currency: "EUR", period: "month" },
area_m2: 62, rooms_x2: 5, features: ["Balkon"], title: "Helle Wohnung", description: "Ruhig.\nSüdseite.",
expires_in_days: MAX_LIFETIME_DAYS,
});
assert.equal(draftFromListing({ ...l, delegate: "12D3KooWabcdefgh" } as Listing, 7).delegate, "12D3KooWabcdefgh");
assert.equal(draftFromListing(l, 7).expires_in_days, 7);
assert.equal(draftFromListing({ ...l, price: { amount_cents: 1, currency: "EUR", period: "once" } } as Listing).price.period, "once");
// Optional parts default to empty, not undefined: the API takes them as given.
const bare = draftFromListing({ geohash: "u1x0nw", kind: "sale", category: "house", title: "x" } as unknown as Listing);
assert.deepEqual([bare.area_m2, bare.rooms_x2, bare.features, bare.description], [0, 0, [], ""]);
});
+333
View File
@@ -0,0 +1,333 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, test } from "node:test";
import { encodeGeohash } from "../src/geohash.ts";
import type { Address, Mine } from "../src/ownerApi.ts";
import { NOW, openPage, startGateway, type Gateway, type Page } from "./helpers.ts";
const TOKEN = "cd34".repeat(16);
const AUTHOR = "a".repeat(64); // the stub gateway's /status reports this author
const NEW_ID = "33".repeat(16);
const L1 = "11".repeat(16);
const HAMBURG = "53.5511, 9.9937";
const HAMBURG_CELL = encodeGeohash(53.5511, 9.9937);
/** A listing of this node, as the public API serves it. */
const own = (over: Record<string, unknown> = {}) => ({
v: 1, id: L1, author: AUTHOR, device: "b".repeat(64), seq: 3, created_at: NOW - 86400, expires_at: NOW + 3 * 86400,
kind: "rent", category: "apartment", geohash: HAMBURG_CELL,
price: { amount_cents: 115000, currency: "EUR", period: "month" },
area_m2: 62, rooms_x2: 5, features: ["Balkon", "Aufzug"], title: "Helle Wohnung", description: "Ruhig.\nSüdseite.",
pow: 1, cert: {}, sig: "", ...over,
});
function fakeNode() {
const s = {
calls: [] as { method: string; path: string; body: string; auth: string }[],
address: null as Address | null,
fail: null as { status: number; error: string } | null,
mine: [] as Mine[],
};
const handler: NonNullable<Gateway["owner"]> = (r) => {
s.calls.push({ method: r.method, path: r.path, body: r.body, auth: r.auth });
if (r.auth !== `Bearer ${TOKEN}`) return { status: 401, body: { error: "unauthorized" } };
if (r.method === "POST" && r.path === "/api/v1/listings") {
if (s.fail) return { status: s.fail.status, body: { error: s.fail.error } };
return { status: 200, body: own({ id: NEW_ID, ...JSON.parse(r.body) }) };
}
if (r.method === "PUT" && /^\/api\/v1\/listings\/[0-9a-f]{32}$/.test(r.path)) {
if (s.fail) return { status: s.fail.status, body: { error: s.fail.error } };
return { status: 200, body: own({ ...JSON.parse(r.body) }) };
}
if (r.method === "DELETE" && /^\/api\/v1\/listings\/[0-9a-f]{32}$/.test(r.path)) return { status: 200, body: {} };
if (r.path === "/api/v1/mine") return { status: 200, body: s.mine };
if (r.path === "/api/v1/inbox") return { status: 200, body: [] };
if (/\/address$/.test(r.path)) {
if (r.method === "PUT") { s.address = JSON.parse(r.body) as Address; return { status: 204 }; }
return s.address ? { status: 200, body: s.address } : { status: 404, body: { error: "none" } };
}
return undefined;
};
return { s, handler };
}
let gw: Gateway;
let node: ReturnType<typeof fakeNode>;
let page: Page | undefined;
beforeEach(async () => {
gw = await startGateway({ listings: [own()] });
node = fakeNode();
gw.owner = node.handler;
node.s.mine = [
{ id: L1, title: "Helle Wohnung", kind: "rent", price: { amount_cents: 115000, currency: "EUR", period: "month" }, expires_at: NOW + 3 * 86400, threads: 0, needs_reply: 0, hidden: 0, address_saved: false },
];
});
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 q = <T extends Element = HTMLElement>(sel: string) => page!.document.querySelector<T>(sel);
const qa = (sel: string) => [...page!.document.querySelectorAll(sel)];
const input = (name: string) => q<HTMLInputElement>(`[name="${name}"]`)!;
const button = (label: string) => qa("button").find((b) => b.textContent === label) as HTMLButtonElement | undefined;
const submit = () => q("form.form")!.dispatchEvent(new page!.window.Event("submit", { cancelable: true }));
const writes = (method: string) => node.s.calls.filter((c) => c.method === method && c.path.startsWith("/api/v1/listings") && !c.path.endsWith("/address"));
const set = (name: string, value: string) => { input(name).value = value; input(name).dispatchEvent(new page!.window.Event("input", { bubbles: true })); };
/** Signs in with the login link and opens the new-listing form. */
async function newForm(): Promise<void> {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = "#/mine/new";
await page!.waitFor(() => q("form.form") !== null, "the form");
}
function fillValid(): void {
set("title", "Helle 2,5-Zimmer-Wohnung – Altbau");
set("description", "Ruhige Altbauwohnung.\nBezug ab 1. Februar.");
set("price", "1.150,50");
set("area", "62");
set("rooms", "2,5");
set("features", "Balkon, Aufzug, Balkon ,");
set("location", HAMBURG);
}
test("signed out, the form asks to sign in; signed in, the listings offer a New listing button", async () => {
open("#/mine/new");
await page!.waitFor(() => q('input[name="token"]') !== null, "the sign-in form");
assert.equal(q("form.form"), null);
page!.close();
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
assert.equal(q<HTMLAnchorElement>(".pane-listings a.btn.primary")!.getAttribute("href"), "#/mine/new");
});
test("a valid form publishes the draft, saves the address, and opens the listing", async () => {
await newForm();
assert.match(text(), /Publish a listing/);
fillValid();
set("address", "Musterweg 7, 22765 Hamburg");
set("phone", "+49 40 1234567");
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing to be sent");
const post = writes("POST")[0]!;
assert.equal(post.auth, `Bearer ${TOKEN}`);
assert.deepEqual(JSON.parse(post.body), {
kind: "rent",
category: "apartment",
geohash: HAMBURG_CELL,
price: { amount_cents: 115050, currency: "EUR", period: "month" },
area_m2: 62,
rooms_x2: 5,
features: ["Balkon", "Aufzug"],
title: "Helle 2,5-Zimmer-Wohnung – Altbau",
description: "Ruhige Altbauwohnung.\nBezug ab 1. Februar.",
expires_in_days: 30,
});
await page!.waitFor(() => page!.window.location.hash === `#/mine/${NEW_ID}`, "navigation to the new listing");
assert.deepEqual(node.s.address, { address: "Musterweg 7, 22765 Hamburg", phone: "+49 40 1234567" });
assert.ok(!post.body.includes("Musterweg"), "the exact address never goes into the listing");
});
test("optional parts may be left empty, and a sale is priced once", async () => {
await newForm();
set("title", "Reihenhaus");
set("price", "485000");
set("location", HAMBURG);
q<HTMLInputElement>('input[name="kind"][value="sale"]')!.checked = true;
q('input[name="kind"][value="sale"]')!.dispatchEvent(new page!.window.Event("change", { bubbles: true }));
q<HTMLSelectElement>('select[name="category"]')!.value = "house";
q<HTMLSelectElement>('select[name="days"]')!.value = "14";
assert.match(q("form.form")!.textContent!, /Price \(€\)/, "the label follows the offer");
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing");
assert.deepEqual(JSON.parse(writes("POST")[0]!.body), {
kind: "sale", category: "house", geohash: HAMBURG_CELL,
price: { amount_cents: 48500000, currency: "EUR", period: "once" },
area_m2: 0, rooms_x2: 0, features: [], title: "Reihenhaus", description: "", expires_in_days: 14,
});
await page!.waitFor(() => page!.window.location.hash === `#/mine/${NEW_ID}`, "navigation to the new listing");
assert.equal(node.s.calls.filter((c) => c.method === "PUT" && c.path.endsWith("/address")).length, 0, "no address, nothing saved");
});
test("every problem is explained next to its field, and nothing is sent", async () => {
await newForm();
submit();
await page!.waitFor(() => qa(".form .error").some((e) => e.textContent), "errors");
const msgs = () => qa(".form .field .error").map((e) => e.textContent).filter(Boolean);
assert.equal(msgs().length, 3, "title, price and location are required");
assert.match(text(), /enter a title/);
assert.match(text(), /amount above 0/);
assert.match(text(), /coordinates could not be read/);
assert.equal(input("title").getAttribute("aria-invalid"), "true");
assert.equal(writes("POST").length, 0);
set("title", "x".repeat(121));
set("price", "abc");
set("area", "6x");
set("rooms", "2.3");
set("features", Array.from({ length: 21 }, (_, i) => `f${i}`).join(","));
set("description", "a".repeat(4001));
set("location", "Hamburg");
submit();
assert.equal(msgs().length, 7);
assert.match(text(), /whole number/);
assert.match(text(), /half steps/);
assert.match(text(), /At most 20 features/);
assert.match(text(), /description is too long/);
assert.equal(writes("POST").length, 0);
fillValid(); // fixing the fields clears the messages
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing once it is valid");
assert.equal(msgs().length, 0);
});
test("a place in a region this node does not follow is refused, with the way out", async () => {
await newForm();
fillValid();
set("location", "48.1371, 11.5754"); // Munich
submit();
await page!.waitFor(() => /does not follow region/.test(text()), "the region message");
assert.match(text(), /--region u28/);
assert.match(text(), /choose a place in u1x/);
assert.equal(writes("POST").length, 0);
});
test("the location shows what will be published, and accepts a map link", async () => {
await newForm();
set("location", "https://www.openstreetmap.org/#map=17/53.5511/9.9937");
const preview = () => qa(".form p.muted.small").map((p) => p.textContent).join("|");
assert.match(preview(), new RegExp(`code ${HAMBURG_CELL}`));
assert.match(preview(), /about \d+ × \d+ m/);
const a = q<HTMLAnchorElement>('.form a[href^="https://www.openstreetmap.org/"]')!;
assert.match(a.getAttribute("rel")!, /noopener/);
assert.equal(a.getAttribute("target"), "_blank");
fillValid();
set("location", "https://www.openstreetmap.org/#map=17/53.5511/9.9937");
set("title", "Mit Link eingefügt");
submit();
await page!.waitFor(() => writes("POST").length === 1, "the listing");
assert.equal(JSON.parse(writes("POST")[0]!.body).geohash, HAMBURG_CELL);
});
test("a refusal from the node is shown and the form keeps what was typed", async () => {
await newForm();
fillValid();
node.s.fail = { status: 400, error: "price out of range" };
submit();
await page!.waitFor(() => /Failed: price out of range/.test(text()), "the node's message");
assert.equal(input("title").value, "Helle 2,5-Zimmer-Wohnung – Altbau");
assert.equal(q<HTMLButtonElement>('button[type="submit"]')!.disabled, false, "it can be tried again");
assert.equal(page!.window.location.hash, "#/mine/new");
node.s.fail = null;
submit();
await page!.waitFor(() => page!.window.location.hash === `#/mine/${NEW_ID}`, "a second try works");
});
test("changing a listing starts from what is published, and re-publishes it", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${L1}/edit`;
await page!.waitFor(() => q("form.form") !== null, "the form");
assert.match(text(), /Edit listing/);
assert.equal(input("title").value, "Helle Wohnung");
assert.equal(input("price").value, "1150");
assert.equal(input("area").value, "62");
assert.equal(input("rooms").value, "2.5");
assert.equal(input("features").value, "Balkon, Aufzug");
assert.match(q<HTMLTextAreaElement>('textarea[name="description"]')!.value, /Ruhig\.\nSüdseite\./);
assert.match(input("location").value, /^53\.\d+, 9\.\d+$/);
assert.equal(q('input[name="address"]'), null, "the address is edited where requests are handled");
set("title", "Helle Wohnung, jetzt renoviert");
set("price", "1200");
submit();
await page!.waitFor(() => writes("PUT").length === 1, "the new version");
const put = writes("PUT")[0]!;
assert.equal(put.path, `/api/v1/listings/${L1}`);
const body = JSON.parse(put.body);
assert.equal(body.title, "Helle Wohnung, jetzt renoviert");
assert.equal(body.price.amount_cents, 120000);
assert.equal(body.geohash, HAMBURG_CELL, "the unchanged location keeps its cell");
assert.deepEqual(body.features, ["Balkon", "Aufzug"]);
await page!.waitFor(() => page!.window.location.hash === `#/mine/${L1}`, "back to the listing");
});
test("the region of an existing listing cannot be changed", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${L1}/edit`;
await page!.waitFor(() => q("form.form") !== null, "the form");
set("location", "52.52, 13.405"); // Berlin: another region
submit();
await page!.waitFor(() => /region cannot change/.test(text()), "the region message");
assert.equal(writes("PUT").length, 0);
});
test("a listing that does not exist cannot be edited", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${"99".repeat(16)}/edit`;
await page!.waitFor(() => /does not exist/.test(text()), "the not-found notice");
assert.equal(q("form.form"), null);
});
test("a listing that expires soon is flagged, and Renew publishes it again for 30 days", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
assert.match(qa(".pane-listings .ocard")[0]!.textContent!, /3 days left/);
assert.ok(qa(".pane-listings .ocard .badge.warn").some((b) => /days left/.test(b.textContent!)), "flagged as running out");
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => button("Renew") !== undefined, "the Renew button");
assert.match(text(), /Expires soon/);
button("Renew")!.click();
await page!.waitFor(() => writes("PUT").length === 1, "the renewal");
const body = JSON.parse(writes("PUT")[0]!.body);
assert.equal(body.expires_in_days, 30);
assert.equal(body.title, "Helle Wohnung", "nothing else changes");
assert.equal(body.geohash, HAMBURG_CELL);
assert.deepEqual(body.features, ["Balkon", "Aufzug"]);
assert.equal(body.price.period, "month");
});
test("a comfortable listing is not nagged about, and an expired one says so", async () => {
node.s.mine = [{ ...node.s.mine[0]!, expires_at: NOW + 20 * 86400 }];
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
assert.match(qa(".pane-listings .ocard")[0]!.textContent!, /20 days left/);
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => button("Renew") !== undefined, "the bar");
assert.doesNotMatch(text(), /Expires soon/);
page!.close();
node.s.mine = [{ ...node.s.mine[0]!, expires_at: NOW - 10 }];
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings again");
assert.match(qa(".pane-listings .ocard")[0]!.textContent!, /Expired/);
});
test("deleting a listing asks first, then withdraws it", async () => {
open(`#/login/${TOKEN}`);
await page!.waitFor(() => qa(".pane-listings .ocard").length === 1, "the listings");
page!.window.location.hash = `#/mine/${L1}`;
await page!.waitFor(() => button("Delete listing") !== undefined, "the delete button");
button("Delete listing")!.click();
assert.match(text(), /people can no longer reach you/);
assert.equal(writes("DELETE").length, 0, "one click deletes nothing");
button("Yes, delete")!.click();
await page!.waitFor(() => writes("DELETE").length === 1, "the deletion");
assert.equal(writes("DELETE")[0]!.path, `/api/v1/listings/${L1}`);
await page!.waitFor(() => page!.window.location.hash === "#/mine", "back to the listings");
});