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>
This commit is contained in:
2026-11-17 18:29:40 +01:00
co-authored by Claude Sonnet 5.5
parent 918e16ed37
commit 3fd40241bc
30 changed files with 6418 additions and 5 deletions
+155
View File
@@ -0,0 +1,155 @@
import { createServer, type Server } from "node:http";
import { readFileSync } from "node:fs";
import type { AddressInfo } from "node:net";
import { ed25519 } from "@noble/curves/ed25519.js";
import { sha256 } from "@noble/hashes/sha2.js";
import { JSDOM, type DOMWindow } from "jsdom";
import { canonicalize } from "../src/jcs.ts";
import { leadingZeroBits, type Listing } from "../src/verify.ts";
/** The clock the browser sees in these tests (unix seconds). */
export const NOW = 1_800_000_000;
export const DIFFICULTY = 8;
const enc = new TextEncoder();
const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");
/** Creates a validly signed listing under a brand-new identity and device. */
export function signListing(fields: Record<string, unknown> = {}): Listing {
const idKey = ed25519.utils.randomSecretKey();
const devKey = ed25519.utils.randomSecretKey();
const cert: Record<string, unknown> = {
v: 1,
author: hex(ed25519.getPublicKey(idKey)),
device: hex(ed25519.getPublicKey(devKey)),
issued_at: NOW - 3600,
expires_at: NOW + 90 * 86_400,
};
cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey));
const l: Record<string, unknown> = {
v: 1,
id: hex(ed25519.utils.randomSecretKey()).slice(0, 32),
author: cert.author,
device: cert.device,
seq: 1,
created_at: NOW,
expires_at: NOW + 10 * 86_400,
kind: "rent",
category: "apartment",
geohash: "u1xjhx",
price: { amount_cents: 90_000, currency: "EUR", period: "month" },
area_m2: 40,
rooms_x2: 4,
title: "Wohnung",
pow: 0,
cert,
...fields,
};
for (let pow = 0; ; pow++) {
l.pow = pow;
if (leadingZeroBits(sha256(enc.encode(canonicalize(l)))) >= DIFFICULTY) break;
}
l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey));
return l as unknown as Listing;
}
// --- a stand-in for a node's HTTP API -------------------------------------
export interface Gateway {
url: string;
/** Query strings of every /api/v1/listings search received. */
queries: string[];
close(): Promise<void>;
}
export interface GatewayOptions {
listings: unknown[];
/** For a requested listing id, answer with this other listing instead. */
swap?: unknown;
statusFails?: boolean;
}
export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
const queries: string[] = [];
const server: Server = createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://x");
const json = (code: number, body: unknown) => {
res.writeHead(code, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (url.pathname === "/api/v1/status") {
if (opts.statusFails) return json(500, { error: "down" });
return json(200, {
peer_id: "12D3KooWTest",
author: "a".repeat(64),
device: "b".repeat(64),
regions: ["u1x"],
peers: 2,
listings: opts.listings.length,
difficulty: DIFFICULTY,
});
}
if (url.pathname === "/api/v1/listings") {
queries.push(url.search);
return json(200, opts.listings);
}
const m = /^\/api\/v1\/listings\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(url.pathname);
if (m) {
if (opts.swap) return json(200, opts.swap);
const hit = (opts.listings as Listing[]).find((l) => l.author === m[1] && l.id === m[2]);
return hit ? json(200, hit) : json(404, { error: "not found" });
}
json(404, { error: "not found" });
});
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
const { port } = server.address() as AddressInfo;
return {
url: `http://127.0.0.1:${port}`,
queries,
close: () => new Promise((ok) => server.close(() => ok())),
};
}
// --- running the real built UI --------------------------------------------
export interface Page {
window: DOMWindow;
document: Document;
waitFor(pred: () => boolean, what: string, ms?: number): Promise<void>;
close(): void;
}
/** Loads web/dist/index.html in jsdom and runs the built bundle against `gateway`. */
export function openPage(gateway: string, hash = "", lang = "en"): Page {
const dist = new URL("../dist/", import.meta.url);
const html = readFileSync(new URL("index.html", dist), "utf8");
const bundle = readFileSync(new URL("app.js", dist), "utf8");
const dom = new JSDOM(html, {
url: `${gateway}/?lang=${lang}${hash}`,
runScripts: "outside-only",
pretendToBeVisual: true,
});
const w = dom.window;
w.fetch = ((input: string | URL, init?: RequestInit) =>
fetch(new URL(String(input), gateway), init)) as unknown as typeof w.fetch;
w.scrollTo = () => {};
w.Date.now = () => NOW * 1000;
w.eval(bundle);
return {
window: w,
document: w.document,
async waitFor(pred, what, ms = 4000) {
const end = Date.now() + ms;
while (Date.now() < end) {
if (pred()) return;
await new Promise((r) => setTimeout(r, 10));
}
throw new Error(`timed out waiting for: ${what}\n${w.document.body.textContent?.slice(0, 600)}`);
},
close: () => w.close(),
};
}
+41
View File
@@ -0,0 +1,41 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { canonicalize } from "../src/jcs.ts";
import { decodeGeohash } from "../src/geohash.ts";
// These mirror internal/jcs/jcs_test.go.
test("canonical JSON matches the Go test vectors", () => {
const cases: [unknown, string][] = [
[{ b: 1, a: 2, c: [3, 1] }, `{"a":2,"b":1,"c":[3,1]}`],
[{ z: { y: true, x: null } }, `{"z":{"x":null,"y":true}}`],
[`<a href="x">&</a>`, `"<a href=\\"x\\">&</a>"`],
["a\tb\nc\u0001", `"a\\tb\\nc\\u0001"`],
["ä€😀
", `"ä€😀
"`],
["\u007f", `"\u007f"`],
[{ "😀": 1, "￿": 2 }, `{"😀":1,"￿":2}`], // UTF-16 order: surrogates sort first
[-42, "-42"],
];
for (const [input, want] of cases) assert.equal(canonicalize(input), want);
});
test("floats and non-JSON values are rejected", () => {
for (const bad of [1.5, NaN, Infinity, 2 ** 60, undefined, () => 1, 10n]) {
assert.throws(() => canonicalize(bad));
}
});
test("geohash decoding", () => {
const a = decodeGeohash("ezs42")!; // the classic example: 42.605, -5.603
assert.ok(Math.abs(a.lat - 42.605) < 0.03 && Math.abs(a.lon + 5.603) < 0.03);
const kiel = decodeGeohash("u1xjhx")!; // near Kiel: 54.36 N, 10.05 E
assert.ok(Math.abs(kiel.lat - 54.358) < 0.01 && Math.abs(kiel.lon - 10.047) < 0.01);
assert.ok(kiel.latErr < 0.003 && kiel.lonErr < 0.006, "precision 6 is about a kilometre");
// Hamburg (53.55 N, 9.99 E) lies inside the 3-character region cell u1x.
const region = decodeGeohash("u1x")!;
assert.ok(Math.abs(53.55 - region.lat) < region.latErr && Math.abs(9.99 - region.lon) < region.lonErr);
assert.equal(decodeGeohash("u1xja"), null, "'a' is not in the geohash alphabet");
});
+195
View File
@@ -0,0 +1,195 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { after, before, test } from "node:test";
import type { Listing } from "../src/verify.ts";
import { DIFFICULTY, openPage, signListing, startGateway, type Gateway } from "./helpers.ts";
// Produced by the Go implementation; verifies at NOW-equivalent time.
const fixture = JSON.parse(
readFileSync(new URL("../../internal/listing/testdata/fixture.json", import.meta.url), "utf8"),
) as { listing: Listing };
const goSigned = fixture.listing;
const XSS_TITLE = `<img src=x onerror="window.__pwned=1">Haus`;
const XSS_DESC = `<script>window.__pwned=2</script>\nZweite Zeile`;
const tampered = { ...structuredClone(goSigned), id: "ff".repeat(16) } as Listing;
tampered.title = "Gefälschter Titel";
const hostile = signListing({ title: XSS_TITLE, description: XSS_DESC, features: ["<b>fett</b>"] });
let gw: Gateway;
before(async () => {
gw = await startGateway({ listings: [goSigned, tampered, hostile] });
});
after(async () => {
await gw.close();
});
const cardTitles = (doc: Document) =>
[...doc.querySelectorAll(".card h3")].map((e) => e.textContent);
test("search shows verified listings and hides forged ones", async () => {
const page = openPage(gw.url);
try {
await page.waitFor(() => page.document.querySelectorAll(".card").length === 2, "two cards");
const titles = cardTitles(page.document);
assert.ok(titles.includes(goSigned.title!), "the Go-signed listing is shown");
assert.ok(!titles.includes("Gefälschter Titel"), "the forged listing must not be shown");
assert.match(page.document.querySelector(".warn")!.textContent!, /1 result\(s\) hidden/);
assert.match(page.document.querySelector(".card .badge.ok")!.textContent!, /Signature verified/);
assert.match(page.document.body.textContent!, /€1,234\.50 \/ month/);
assert.match(page.document.getElementById("status")!.textContent!, /2 connected nodes/);
} finally {
page.close();
}
});
test("hostile listing text is rendered as text, never as HTML", async () => {
const page = openPage(gw.url);
try {
await page.waitFor(() => page.document.querySelectorAll(".card").length === 2, "cards");
const titles = cardTitles(page.document);
assert.ok(titles.includes(XSS_TITLE), "the markup is shown literally");
assert.equal(page.document.querySelector("img"), null, "no <img> may be created from listing text");
assert.equal((page.window as unknown as { __pwned?: number }).__pwned, undefined);
page.window.location.hash = `#/l/${hostile.author}/${hostile.id}`;
await page.waitFor(() => page.document.querySelector("h1") !== null, "detail view");
assert.equal(page.document.querySelector("h1")!.textContent, XSS_TITLE);
assert.equal(page.document.querySelector("img"), null);
assert.equal(page.document.querySelectorAll("main script").length, 0);
assert.equal(page.document.querySelector(".chips b"), null, "feature markup must stay text");
assert.equal(page.document.querySelector(".desc")!.textContent, XSS_DESC);
assert.equal((page.window as unknown as { __pwned?: number }).__pwned, undefined);
} finally {
page.close();
}
});
test("detail view shows the content and a passing verification report", async () => {
const page = openPage(gw.url, `#/l/${goSigned.author}/${goSigned.id}`);
try {
await page.waitFor(() => page.document.querySelector("h1") !== null, "detail");
const text = page.document.body.textContent!;
assert.equal(page.document.querySelector("h1")!.textContent, goSigned.title);
assert.ok(text.includes("Zeile 2 – Überraschung \u{1F3E0}"), "unicode survives");
assert.equal(page.document.querySelector(".desc")!.textContent, goSigned.description);
assert.equal(page.document.querySelectorAll(".checks li.ok").length, 6);
assert.equal(page.document.querySelectorAll(".checks li.bad").length, 0);
assert.ok(page.document.querySelector("a[href^='https://www.openstreetmap.org/']")!.getAttribute("rel")!.includes("noopener"));
assert.match(text, /not available yet/);
} finally {
page.close();
}
});
test("detail view refuses to show a forged listing", async () => {
const page = openPage(gw.url, `#/l/${tampered.author}/${tampered.id}`);
try {
await page.waitFor(() => page.document.querySelector("#app .error") !== null, "warning");
const text = page.document.body.textContent!;
assert.match(text, /could not be verified/);
assert.ok(!text.includes("Gefälschter Titel"), "forged content must not be displayed");
assert.equal(page.document.querySelector("h1"), null);
assert.ok(page.document.querySelectorAll(".checks li.bad").length >= 1);
} finally {
page.close();
}
});
test("a gateway answering with a different valid listing is caught", async () => {
const other = signListing({ title: "Andere Anzeige" });
const liar = await startGateway({ listings: [], swap: other });
try {
// Ask for goSigned, but the gateway returns `other`, which is validly signed.
const page = openPage(liar.url, `#/l/${goSigned.author}/${goSigned.id}`);
await page.waitFor(() => page.document.querySelector("#app .error") !== null, "warning");
assert.match(page.document.body.textContent!, /could not be verified/);
assert.ok(!page.document.body.textContent!.includes("Andere Anzeige"));
page.close();
} finally {
await liar.close();
}
});
test("a missing listing says so", async () => {
const page = openPage(gw.url, `#/l/${"a".repeat(64)}/${"b".repeat(32)}`);
try {
await page.waitFor(() => /does not exist/.test(page.document.body.textContent!), "not found text");
} finally {
page.close();
}
});
test("filters are translated into the API's units", async () => {
const page = openPage(gw.url);
try {
await page.waitFor(() => page.document.querySelectorAll(".card").length > 0, "initial results");
const set = (name: string, value: string) =>
((page.document.querySelector(`[name=${name}]`) as HTMLInputElement).value = value);
set("kind", "rent");
set("geohash", "U1X");
set("max_price", "1000");
set("min_area", "42.5");
set("min_rooms", "2.5"); // browsers normalise a typed "2,5" to this for type=number
gw.queries.length = 0;
page.document.querySelector("form")!.dispatchEvent(new page.window.Event("submit", { cancelable: true }));
await page.waitFor(() => gw.queries.length > 0, "a search request");
const q = new URLSearchParams(gw.queries.at(-1));
assert.equal(q.get("kind"), "rent");
assert.equal(q.get("geohash"), "u1x", "lower-cased");
assert.equal(q.get("max_price"), "100000", "euros become cents");
assert.equal(q.get("min_area"), "43", "rounded up");
assert.equal(q.get("min_rooms"), "5", "2.5 rooms is stored as 5");
assert.equal(q.get("limit"), "20");
assert.match(page.window.location.hash, /geohash=U1X|geohash=u1x/i);
} finally {
page.close();
}
});
test("an invalid area is reported without calling the API", async () => {
const before = gw.queries.length;
const page = openPage(gw.url, "#/?geohash=u1xa'%20OR%201=1");
try {
await page.waitFor(() => page.document.querySelector("#app .error") !== null, "hint");
assert.equal(gw.queries.length, before, "no request should be sent for an invalid prefix");
} finally {
page.close();
}
});
test("the page still works when the node's status is unavailable", async () => {
const down = await startGateway({ listings: [goSigned], statusFails: true });
try {
const page = openPage(down.url, "", "de");
await page.waitFor(() => /nicht erreichbar/.test(page.document.getElementById("status")!.textContent!), "status error (German)");
// With no difficulty known the verifier still checks everything else.
await page.waitFor(() => page.document.querySelectorAll(".card").length === 1, "card");
assert.match(page.document.querySelector(".badge")!.textContent!, /Signatur geprüft/);
assert.equal(page.document.documentElement.lang, "de");
page.close();
} finally {
await down.close();
}
});
test("the difficulty reported by the node is enforced as a minimum", async () => {
// A listing without any proof-of-work, from a gateway claiming difficulty 8.
const lazy = signListing({ title: "Ohne Arbeit" });
const weak = structuredClone(lazy);
assert.ok(DIFFICULTY > 0);
// Re-signing is impossible here, so simply check the real one passes and a forged PoW fails.
weak.pow += 1;
const g = await startGateway({ listings: [lazy, weak] });
try {
const page = openPage(g.url);
await page.waitFor(() => page.document.querySelectorAll(".card").length >= 1, "cards");
assert.equal(page.document.querySelectorAll(".card").length, 1, "the altered one is hidden");
page.close();
} finally {
await g.close();
}
});
+137
View File
@@ -0,0 +1,137 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { ed25519 } from "@noble/curves/ed25519.js";
import { canonicalize } from "../src/jcs.ts";
import { verifyListing, type Listing } from "../src/verify.ts";
// Written by the Go implementation (internal/listing/fixture_test.go).
const fixture = JSON.parse(
readFileSync(new URL("../../internal/listing/testdata/fixture.json", import.meta.url), "utf8"),
) as { now: number; difficulty: number; canonical: string; listing: Listing };
const opts = { now: fixture.now, minPowBits: fixture.difficulty };
const fresh = (): Listing => structuredClone(fixture.listing);
const failing = (l: unknown, o = opts) =>
verifyListing(l, o).checks.filter((c) => !c.ok).map((c) => c.id);
test("canonicalization is byte-identical to Go", () => {
assert.equal(canonicalize(fixture.listing), fixture.canonical);
});
test("a listing signed by Go verifies in the browser", () => {
const v = verifyListing(fixture.listing, opts);
assert.deepEqual(failing(fixture.listing), []);
assert.equal(v.ok, true);
assert.ok(v.powBits >= fixture.difficulty);
assert.equal(v.checks.length, 6);
});
test("tampering with any signed field is detected", () => {
const edits: Record<string, (l: Listing) => void> = {
price: (l) => (l.price!.amount_cents = 1),
title: (l) => (l.title = "Betrug"),
description: (l) => (l.description += "!"),
geohash: (l) => (l.geohash = "u30000"),
seq: (l) => (l.seq += 1),
expires_at: (l) => (l.expires_at += 1),
feature: (l) => l.features!.push("pool"),
};
for (const [name, edit] of Object.entries(edits)) {
const l = fresh();
edit(l);
assert.ok(failing(l).includes("signature"), `${name} change not detected`);
}
});
test("tampering with the certificate is detected", () => {
const l = fresh();
l.cert.expires_at += 86_400;
assert.deepEqual(failing(l), ["certificate"]);
const m = fresh();
m.cert.device = "00".repeat(32);
assert.ok(failing(m).includes("certificate"));
});
test("a certificate for another identity or device is rejected", () => {
const l = fresh();
l.author = "ab".repeat(32);
assert.ok(failing(l).includes("binding"));
assert.ok(failing(l).includes("signature"));
});
test("a self-signed listing from a new identity is internally consistent", () => {
// Verification proves integrity and the identity -> device chain. It does
// not make an unknown identity trustworthy; that is a separate question.
const idKey = ed25519.utils.randomSecretKey();
const devKey = ed25519.utils.randomSecretKey();
const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");
const enc = new TextEncoder();
const cert: Record<string, unknown> = {
v: 1,
author: hex(ed25519.getPublicKey(idKey)),
device: hex(ed25519.getPublicKey(devKey)),
issued_at: fixture.now - 3600,
expires_at: fixture.now + 30 * 86_400,
};
cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey));
const l: Record<string, unknown> = {
v: 1,
id: "11".repeat(16),
author: cert.author,
device: cert.device,
seq: 1,
created_at: fixture.now,
expires_at: fixture.now + 86_400,
geohash: "u1xjhx",
pow: 0,
cert,
};
// Mine a little proof-of-work so it also passes the PoW check.
for (let pow = 0; ; pow++) {
l.pow = pow;
const v = verifyListing({ ...l, sig: "00".repeat(64) }, { ...opts, minPowBits: 8 });
if (v.powBits >= 8) break;
}
l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey));
assert.deepEqual(failing(l, { ...opts, minPowBits: 8 }), []);
});
test("a signature made for another purpose does not verify (domain separation)", () => {
// Sign the listing bytes with the certificate context instead of the listing one.
const l = fresh();
assert.ok(failing({ ...l, sig: l.cert.sig }).includes("signature"));
});
test("time windows", () => {
const day = 86_400;
assert.ok(failing(fixture.listing, { ...opts, now: fixture.now + 20 * day }).includes("validity"), "expired listing");
assert.ok(failing(fixture.listing, { ...opts, now: fixture.now - 3600 }).includes("validity"), "created in the future");
assert.ok(failing(fixture.listing, { ...opts, now: fixture.listing.cert.expires_at + 1 }).includes("validity"), "expired certificate");
const l = fresh();
l.created_at = l.cert.issued_at - 10; // before the certificate existed
assert.ok(failing(l).includes("validity"));
});
test("insufficient proof-of-work is reported", () => {
const v = verifyListing(fixture.listing, { ...opts, minPowBits: 40 });
assert.deepEqual(
v.checks.filter((c) => !c.ok).map((c) => c.id),
["pow"],
);
});
test("garbage never throws and never verifies", () => {
for (const junk of [null, undefined, 5, "x", [], {}, { cert: 5 }, { cert: {} }, { v: 1, cert: [] }]) {
assert.equal(verifyListing(junk, opts).ok, false);
}
const floaty = fresh();
floaty.price!.amount_cents = 1.5;
assert.equal(verifyListing(floaty, opts).ok, false);
});