Files
allmende/web/src/main.ts
T
nilsandClaude Sonnet 5.5 3fd40241bc Add browser UI with in-browser signature verification
Every node now serves a search and listing-detail UI at GET /. It is
vanilla TypeScript, bundled unminified into web/dist (committed) and
embedded with go:embed, so `go build` is enough to run a node.

The browser verifies each listing itself (certificate, binding, validity,
signature, proof-of-work) with pure-JS ed25519, so a gateway can withhold
listings but not forge them. Unverifiable results are hidden and their
content is never shown. Listing text is only inserted via textContent and
the UI is served with a strict CSP.

Canonical JSON is reimplemented in TypeScript and tested against a golden
fixture signed by the Go code. /api/v1/status now reports difficulty.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 18:29:40 +01:00

363 lines
13 KiB
TypeScript

import { getListing, getStatus, search, type Status } from "./api.ts";
import { append, clear, h } from "./dom.ts";
import { date, price, rooms, shortKey } from "./format.ts";
import { decodeGeohash } from "./geohash.ts";
import { lang, t, type Key } from "./i18n.ts";
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
const PAGE = 20;
const GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
const app = document.getElementById("app")!;
const statusEl = document.getElementById("status")!;
// Not called `status`: that would collide with the built-in window.status.
let nodeInfo: Status | null = null;
/** Bumped on every navigation so late responses for an old view are dropped. */
let generation = 0;
// --- helpers --------------------------------------------------------------
function verifyOpts() {
return { now: Math.floor(Date.now() / 1000), minPowBits: nodeInfo?.difficulty ?? 0 };
}
/** Translates a value from a listing if it is a known one; unknown values are shown as plain text. */
function label(prefix: "kind" | "cat", value: string | undefined): string {
if (!value) return "";
const key = `${prefix}.${value}` as Key;
const known = ["kind.rent", "kind.sale", "cat.apartment", "cat.house", "cat.room", "cat.commercial"];
return known.includes(key) ? t(key) : value;
}
function where(geohash: string): string {
const a = decodeGeohash(geohash);
if (!a) return geohash;
const ns = a.lat >= 0 ? "N" : "S";
const ew = a.lon >= 0 ? (lang === "de" ? "O" : "E") : lang === "de" ? "W" : "W";
return `${Math.abs(a.lat).toFixed(2)}° ${ns}, ${Math.abs(a.lon).toFixed(2)}° ${ew}`;
}
function badge(ok: boolean): HTMLElement {
return h("span", { class: ok ? "badge ok" : "badge bad" }, (ok ? "✓ " : "✗ ") + t(ok ? "badge.ok" : "badge.bad"));
}
function num(v: string | null): number {
const n = Number((v ?? "").replace(",", "."));
return Number.isFinite(n) && n > 0 ? n : 0;
}
/** Converts the human-friendly URL parameters into the API's units. */
function toApi(p: URLSearchParams): URLSearchParams {
const q = new URLSearchParams();
for (const k of ["kind", "category", "geohash"]) {
const v = p.get(k)?.trim().toLowerCase();
if (v) q.set(k, v);
}
const eur = num(p.get("max_price"));
if (eur) q.set("max_price", String(Math.round(eur * 100)));
const area = num(p.get("min_area"));
if (area) q.set("min_area", String(Math.ceil(area)));
const r = num(p.get("min_rooms"));
if (r) q.set("min_rooms", String(Math.ceil(r * 2)));
return q;
}
// --- search view ----------------------------------------------------------
function field(text: string, input: HTMLElement, hint?: string): HTMLElement {
return h("label", { class: "field" }, h("span", { class: "field-label" }, text), input, hint && h("span", { class: "hint" }, hint));
}
function select(name: string, current: string, options: [string, string][]): HTMLSelectElement {
const el = h("select", { name });
for (const [value, text] of options) {
el.append(h("option", { value, selected: value === current }, text));
}
return el;
}
function searchForm(params: URLSearchParams): HTMLFormElement {
const get = (k: string) => params.get(k) ?? "";
const regions = h("datalist", { id: "regions" }, ...(nodeInfo?.regions ?? []).map((r) => h("option", { value: r })));
const form = h(
"form",
{ class: "filters" },
field(t("filter.kind"), select("kind", get("kind"), [["", t("filter.any")], ["rent", t("kind.rent")], ["sale", t("kind.sale")]])),
field(
t("filter.category"),
select("category", get("category"), [
["", t("filter.any")],
["apartment", t("cat.apartment")],
["house", t("cat.house")],
["room", t("cat.room")],
["commercial", t("cat.commercial")],
]),
),
field(
t("filter.region"),
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: nodeInfo?.regions[0] ?? "u1x" }),
t("filter.regionHint"),
),
field(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
field(t("filter.minArea"), h("input", { name: "min_area", type: "number", min: 0, step: 5, value: get("min_area") })),
field(t("filter.minRooms"), h("input", { name: "min_rooms", type: "number", min: 0, step: 0.5, value: get("min_rooms") })),
h(
"div",
{ class: "actions" },
h("button", { type: "submit", class: "btn primary" }, t("filter.search")),
h("button", { type: "button", class: "btn", onclick: () => navigate("#/") }, t("filter.reset")),
),
regions,
);
form.addEventListener("submit", (e) => {
e.preventDefault();
const q = new URLSearchParams();
for (const [k, v] of new FormData(form)) {
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
}
const s = q.toString();
navigate(s ? `#/?${s}` : "#/");
});
return form;
}
function navigate(hash: string): void {
if (location.hash === hash || (hash === "#/" && location.hash === "")) route();
else location.hash = hash;
}
function card(l: Listing): HTMLElement {
const facts = [
label("cat", l.category),
l.area_m2 ? t("card.area", { n: l.area_m2 }) : "",
l.rooms_x2 ? rooms(l.rooms_x2) : "",
].filter(Boolean);
return h(
"a",
{ class: "card", href: `#/l/${l.author}/${l.id}` }, // author and id were verified to be hex
h("div", { class: "card-top" }, h("h3", null, l.title ?? ""), badge(true)),
h("p", { class: "price" }, price(l)),
h("p", { class: "facts" }, facts.join(" · ")),
h("p", { class: "muted" }, where(l.geohash)),
);
}
async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement): Promise<void> {
const cards = h("div", { class: "cards" });
const foot = h("div", { class: "results-foot" });
append(root, [cards, foot]);
let offset = 0;
let shown = 0;
let hidden = 0;
const more = async (): Promise<void> => {
clear(foot);
foot.append(h("p", { class: "muted" }, t("results.loading")));
let items: unknown[];
try {
const paged = new URLSearchParams(q);
paged.set("limit", String(PAGE));
paged.set("offset", String(offset));
items = await search(paged);
} catch {
if (gen !== generation) return;
clear(foot);
foot.append(h("p", { class: "error" }, t("results.error")));
return;
}
if (gen !== generation) return;
const opts = verifyOpts();
for (const raw of items) {
const verdict = verifyListing(raw, opts);
if (verdict.ok) {
cards.append(card(raw as Listing));
shown++;
} else {
hidden++;
}
}
offset += items.length;
clear(foot);
if (hidden > 0) foot.append(h("p", { class: "warn" }, t("results.hidden", { n: hidden })));
if (shown === 0 && items.length < PAGE) foot.append(h("p", { class: "muted" }, t("results.none")));
if (items.length === PAGE) {
foot.append(h("button", { type: "button", class: "btn", onclick: () => void more() }, t("results.more")));
}
};
await more();
}
function showSearch(params: URLSearchParams): void {
const gen = generation;
clear(app);
const results = h("div", { class: "results", "aria-live": "polite" });
app.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
const prefix = params.get("geohash")?.trim().toLowerCase();
if (prefix && !GEOHASH_PREFIX.test(prefix)) {
results.append(h("p", { class: "error" }, t("filter.regionHint")));
return;
}
void loadResults(gen, toApi(params), results);
}
// --- detail view ----------------------------------------------------------
function checkList(v: Verdict): HTMLElement {
return h(
"ul",
{ class: "checks" },
...v.checks.map((c) =>
h(
"li",
{ class: c.ok ? "ok" : "bad" },
h("span", { class: "mark", "aria-hidden": "true" }, c.ok ? "✓" : "✗"),
h("span", null, t(`verify.${c.id}` as Key)),
c.info && h("span", { class: "muted info" }, c.info),
),
),
);
}
function verification(raw: unknown, l: Listing, v: Verdict): HTMLElement {
return h(
"section",
{ class: "panel" },
h("h2", null, t("verify.title")),
h("p", { class: "muted" }, t("verify.intro")),
checkList(v),
v.ok &&
h(
"dl",
{ class: "kv" },
h("dt", null, t("verify.owner")),
h("dd", { class: "mono" }, shortKey(l.author)),
h("dt", null, t("verify.device")),
h("dd", { class: "mono" }, shortKey(l.device)),
),
h("p", { class: "muted" }, t("verify.limit")),
// Never echo the content of a listing that failed verification, not even as raw data.
v.ok && h("details", null, h("summary", null, t("verify.raw")), h("pre", null, JSON.stringify(raw, null, 2))),
);
}
function listingBody(l: Listing): HTMLElement[] {
const area = decodeGeohash(l.geohash);
const fact = (k: Key, v: string): Array<HTMLElement | false> =>
v ? [h("dt", null, t(k)), h("dd", null, v)] : [false];
const map =
area &&
h(
"a",
{
href: `https://www.openstreetmap.org/?mlat=${area.lat.toFixed(5)}&mlon=${area.lon.toFixed(5)}#map=14/${area.lat.toFixed(5)}/${area.lon.toFixed(5)}`,
target: "_blank",
rel: "noopener noreferrer",
},
t("detail.map"),
);
return [
h("div", { class: "detail-head" }, h("h1", null, l.title ?? ""), badge(true)),
h("p", { class: "price big" }, price(l)),
h(
"section",
{ class: "panel" },
h("h2", null, t("detail.facts")),
h(
"dl",
{ class: "kv" },
...(
[
...fact("detail.kind", label("kind", l.kind)),
...fact("detail.category", label("cat", l.category)),
...fact("detail.area", l.area_m2 ? t("card.area", { n: l.area_m2 }) : ""),
...fact("detail.rooms", l.rooms_x2 ? rooms(l.rooms_x2) : ""),
...fact("detail.published", date(l.created_at)),
...fact("detail.expires", date(l.expires_at)),
...fact("detail.version", String(l.seq)),
...fact("detail.location", where(l.geohash)),
].filter(Boolean) as HTMLElement[]
),
),
map && h("p", null, map),
),
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"),
h("section", { class: "panel contact" }, h("h2", null, t("detail.contact")), h("p", null, t("detail.contactSoon"))),
];
}
async function showDetail(author: string, id: string): Promise<void> {
const gen = generation;
clear(app);
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
app.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
let raw: unknown;
try {
raw = await getListing(author, id);
} catch {
if (gen !== generation) return;
clear(body);
body.append(h("p", { class: "error" }, t("results.error")));
return;
}
if (gen !== generation) return;
clear(body);
if (raw === null) {
body.append(h("p", { class: "muted" }, t("detail.notFound")));
return;
}
const l = raw as Listing;
let v = verifyListing(raw, verifyOpts());
// A gateway could answer with a different, validly signed listing.
if (v.ok && (l.author !== author || l.id !== id)) {
v = { ...v, ok: false, checks: [...v.checks, { id: "binding", ok: false, info: "not the listing that was requested" }] };
}
if (!v.ok) {
body.append(h("p", { class: "error" }, t("detail.unverified")), verification(raw, l, v));
return;
}
append(body, [...listingBody(l), verification(raw, l, v)]);
}
// --- boot -----------------------------------------------------------------
function route(): void {
generation++;
const hash = location.hash.replace(/^#/, "") || "/";
const q = hash.indexOf("?");
const path = q < 0 ? hash : hash.slice(0, q);
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
if (m) void showDetail(m[1]!, m[2]!);
else showSearch(params);
window.scrollTo(0, 0);
}
async function boot(): Promise<void> {
document.documentElement.lang = lang;
document.getElementById("foot")!.textContent = t("footer.text");
try {
nodeInfo = await getStatus();
statusEl.textContent = t("status.line", {
listings: nodeInfo.listings,
peers: nodeInfo.peers,
regions: nodeInfo.regions.join(", "),
});
} catch {
statusEl.textContent = t("status.unreachable");
}
window.addEventListener("hashchange", route);
route();
}
void boot();