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:
@@ -0,0 +1,34 @@
|
||||
// Talks to the node that served this page. Everything it returns is untrusted
|
||||
// until verify.ts has checked it.
|
||||
|
||||
export interface Status {
|
||||
peer_id: string;
|
||||
author: string;
|
||||
device: string;
|
||||
regions: string[];
|
||||
peers: number;
|
||||
listings: number;
|
||||
difficulty: number;
|
||||
}
|
||||
|
||||
async function getJSON(url: string): Promise<unknown> {
|
||||
const res = await fetch(url, { headers: { Accept: "application/json" } });
|
||||
if (res.status === 404) return null;
|
||||
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export async function getStatus(): Promise<Status> {
|
||||
return (await getJSON("/api/v1/status")) as Status;
|
||||
}
|
||||
|
||||
/** Returns raw, unverified listing objects. */
|
||||
export async function search(params: URLSearchParams): Promise<unknown[]> {
|
||||
const data = await getJSON(`/api/v1/listings?${params}`);
|
||||
if (!Array.isArray(data)) throw new Error("unexpected response");
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function getListing(author: string, id: string): Promise<unknown | null> {
|
||||
return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Tiny DOM builder. Listing content comes from strangers, so it is only ever
|
||||
// inserted as text nodes or attribute values, never as HTML.
|
||||
|
||||
export type Child = Node | string | number | null | undefined | false;
|
||||
export type Props = Record<string, string | number | boolean | ((e: Event) => void) | undefined>;
|
||||
|
||||
export function h<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
props: Props | null = null,
|
||||
...children: Child[]
|
||||
): HTMLElementTagNameMap[K] {
|
||||
const el = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(props ?? {})) {
|
||||
if (value === undefined || value === false) continue;
|
||||
if (typeof value === "function") {
|
||||
el.addEventListener(key.replace(/^on/, "").toLowerCase(), value);
|
||||
} else if (value === true) {
|
||||
el.setAttribute(key, "");
|
||||
} else {
|
||||
el.setAttribute(key, String(value));
|
||||
}
|
||||
}
|
||||
append(el, children);
|
||||
return el;
|
||||
}
|
||||
|
||||
export function append(parent: Node, children: Child[]): void {
|
||||
for (const c of children) {
|
||||
if (c === null || c === undefined || c === false) continue;
|
||||
parent.appendChild(typeof c === "object" ? c : document.createTextNode(String(c)));
|
||||
}
|
||||
}
|
||||
|
||||
export function clear(el: Element): void {
|
||||
while (el.firstChild) el.removeChild(el.firstChild);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { lang, t } from "./i18n.ts";
|
||||
import type { Listing } from "./verify.ts";
|
||||
|
||||
export function money(cents: number): string {
|
||||
return new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(cents / 100);
|
||||
}
|
||||
|
||||
/** rooms_x2 stores rooms * 2, so 2.5 rooms are 5. */
|
||||
export function rooms(x2: number): string {
|
||||
return t("card.rooms", { n: (x2 / 2).toLocaleString(lang, { maximumFractionDigits: 1 }) });
|
||||
}
|
||||
|
||||
export function date(unix: number): string {
|
||||
return new Date(unix * 1000).toLocaleDateString(lang, { dateStyle: "medium" });
|
||||
}
|
||||
|
||||
export function price(l: Listing): string {
|
||||
if (!l.price) return "";
|
||||
const base = money(l.price.amount_cents);
|
||||
return l.price.period === "month" ? `${base} ${t("card.perMonth")}` : base;
|
||||
}
|
||||
|
||||
/** A key shortened for display: abcd1234…9f2e */
|
||||
export function shortKey(hex: string): string {
|
||||
return hex.length > 16 ? `${hex.slice(0, 8)}…${hex.slice(-4)}` : hex;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Geohash decoding, only to show where a listing roughly is.
|
||||
|
||||
const ALPHABET = "0123456789bcdefghjkmnpqrstuvwxyz";
|
||||
|
||||
export interface Area {
|
||||
lat: number;
|
||||
lon: number;
|
||||
/** Half the height and width of the cell, in degrees. */
|
||||
latErr: number;
|
||||
lonErr: number;
|
||||
}
|
||||
|
||||
export function decodeGeohash(hash: string): Area | null {
|
||||
let lat: [number, number] = [-90, 90];
|
||||
let lon: [number, number] = [-180, 180];
|
||||
let evenBit = true;
|
||||
for (const ch of hash) {
|
||||
const idx = ALPHABET.indexOf(ch);
|
||||
if (idx < 0) return null;
|
||||
for (let bit = 4; bit >= 0; bit--) {
|
||||
const on = (idx >> bit) & 1;
|
||||
const range = evenBit ? lon : lat;
|
||||
const mid = (range[0] + range[1]) / 2;
|
||||
if (on) range[0] = mid;
|
||||
else range[1] = mid;
|
||||
evenBit = !evenBit;
|
||||
}
|
||||
}
|
||||
return {
|
||||
lat: (lat[0] + lat[1]) / 2,
|
||||
lon: (lon[0] + lon[1]) / 2,
|
||||
latErr: (lat[1] - lat[0]) / 2,
|
||||
lonErr: (lon[1] - lon[0]) / 2,
|
||||
};
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
// German first (the launch region is Germany), English as fallback.
|
||||
|
||||
const de = {
|
||||
"app.tagline": "Wohnungen und Häuser, getragen von allen. Kostenlos, ohne Konzern.",
|
||||
"status.line": "{listings} Anzeigen · {peers} verbundene Knoten · Regionen: {regions}",
|
||||
"status.unreachable": "Dieser Knoten ist nicht erreichbar.",
|
||||
"filter.kind": "Angebot",
|
||||
"filter.category": "Art",
|
||||
"filter.region": "Gebiet (Geohash)",
|
||||
"filter.regionHint": "z. B. u1x für den Raum Hamburg, genauer: u1xj",
|
||||
"filter.maxPrice": "Preis bis (€)",
|
||||
"filter.minArea": "Fläche ab (m²)",
|
||||
"filter.minRooms": "Zimmer ab",
|
||||
"filter.any": "Alle",
|
||||
"filter.search": "Suchen",
|
||||
"filter.reset": "Zurücksetzen",
|
||||
"kind.rent": "Miete",
|
||||
"kind.sale": "Kauf",
|
||||
"cat.apartment": "Wohnung",
|
||||
"cat.house": "Haus",
|
||||
"cat.room": "Zimmer",
|
||||
"cat.commercial": "Gewerbe",
|
||||
"results.none": "Keine Anzeigen gefunden.",
|
||||
"results.loading": "Lädt …",
|
||||
"results.more": "Mehr laden",
|
||||
"results.hidden": "{n} Ergebnis(se) ausgeblendet, weil die Signatur nicht geprüft werden konnte.",
|
||||
"results.error": "Die Suche ist fehlgeschlagen.",
|
||||
"card.perMonth": "/ Monat",
|
||||
"card.rooms": "{n} Zimmer",
|
||||
"card.area": "{n} m²",
|
||||
"badge.ok": "Signatur geprüft",
|
||||
"badge.bad": "Nicht verifiziert",
|
||||
"detail.back": "← Zurück zur Suche",
|
||||
"detail.notFound": "Diese Anzeige gibt es nicht (mehr).",
|
||||
"detail.unverified":
|
||||
"Diese Anzeige konnte nicht verifiziert werden und wird deshalb nicht angezeigt. Sie könnte gefälscht oder verändert sein.",
|
||||
"detail.features": "Ausstattung",
|
||||
"detail.facts": "Eckdaten",
|
||||
"detail.kind": "Angebot",
|
||||
"detail.category": "Art",
|
||||
"detail.area": "Fläche",
|
||||
"detail.rooms": "Zimmer",
|
||||
"detail.published": "Veröffentlicht",
|
||||
"detail.expires": "Läuft ab",
|
||||
"detail.version": "Version",
|
||||
"detail.location": "Lage (ungefähr, ca. 1 km)",
|
||||
"detail.map": "Auf OpenStreetMap ansehen (externe Seite)",
|
||||
"detail.contact": "Kontakt",
|
||||
"detail.contactSoon":
|
||||
"Der Kontakt zum Anbieter läuft über dessen eigenen Knoten und ist noch nicht verfügbar. Die genaue Adresse wird nie öffentlich verteilt.",
|
||||
"verify.title": "Prüfung in deinem Browser",
|
||||
"verify.intro":
|
||||
"Diese Prüfung läuft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt fälschen.",
|
||||
"verify.limit":
|
||||
"Nicht prüfbar: ob der Anbieter sein Gerät inzwischen gesperrt hat. Das weiß nur das Netzwerk; dein Knoten kennt den aktuellen Stand.",
|
||||
"verify.format": "Aufbau der Anzeige",
|
||||
"verify.certificate": "Gerätezertifikat des Anbieters ist gültig",
|
||||
"verify.binding": "Zertifikat gehört zu diesem Anbieter und Gerät",
|
||||
"verify.validity": "Zeiträume (Zertifikat, Anzeige) stimmen",
|
||||
"verify.signature": "Signatur passt zum Inhalt",
|
||||
"verify.pow": "Rechenaufwand gegen Spam (Proof-of-Work)",
|
||||
"verify.owner": "Anbieter (Identität)",
|
||||
"verify.device": "Gerät",
|
||||
"verify.raw": "Rohdaten (so signiert)",
|
||||
"footer.text":
|
||||
"Allmende ist freie Software (AGPL-3.0). Es gibt keinen Betreiber und keine Gebühren.",
|
||||
} as const;
|
||||
|
||||
const en: Record<keyof typeof de, string> = {
|
||||
"app.tagline": "Homes to rent and buy, run by everyone. Free, with no company behind it.",
|
||||
"status.line": "{listings} listings · {peers} connected nodes · regions: {regions}",
|
||||
"status.unreachable": "This node is not reachable.",
|
||||
"filter.kind": "Offer",
|
||||
"filter.category": "Type",
|
||||
"filter.region": "Area (geohash)",
|
||||
"filter.regionHint": "e.g. u1x for the Hamburg area, more precise: u1xj",
|
||||
"filter.maxPrice": "Price up to (€)",
|
||||
"filter.minArea": "Area from (m²)",
|
||||
"filter.minRooms": "Rooms from",
|
||||
"filter.any": "Any",
|
||||
"filter.search": "Search",
|
||||
"filter.reset": "Reset",
|
||||
"kind.rent": "Rent",
|
||||
"kind.sale": "Buy",
|
||||
"cat.apartment": "Apartment",
|
||||
"cat.house": "House",
|
||||
"cat.room": "Room",
|
||||
"cat.commercial": "Commercial",
|
||||
"results.none": "No listings found.",
|
||||
"results.loading": "Loading …",
|
||||
"results.more": "Load more",
|
||||
"results.hidden": "{n} result(s) hidden because their signature could not be verified.",
|
||||
"results.error": "The search failed.",
|
||||
"card.perMonth": "/ month",
|
||||
"card.rooms": "{n} rooms",
|
||||
"card.area": "{n} m²",
|
||||
"badge.ok": "Signature verified",
|
||||
"badge.bad": "Not verified",
|
||||
"detail.back": "← Back to search",
|
||||
"detail.notFound": "This listing does not exist (any more).",
|
||||
"detail.unverified":
|
||||
"This listing could not be verified and is therefore not shown. It may be forged or altered.",
|
||||
"detail.features": "Features",
|
||||
"detail.facts": "Key facts",
|
||||
"detail.kind": "Offer",
|
||||
"detail.category": "Type",
|
||||
"detail.area": "Area",
|
||||
"detail.rooms": "Rooms",
|
||||
"detail.published": "Published",
|
||||
"detail.expires": "Expires",
|
||||
"detail.version": "Version",
|
||||
"detail.location": "Location (approximate, about 1 km)",
|
||||
"detail.map": "View on OpenStreetMap (external site)",
|
||||
"detail.contact": "Contact",
|
||||
"detail.contactSoon":
|
||||
"Contact goes through the owner's own node and is not available yet. The exact address is never distributed publicly.",
|
||||
"verify.title": "Checked in your browser",
|
||||
"verify.intro":
|
||||
"This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
|
||||
"verify.limit":
|
||||
"Cannot be checked: whether the owner has since revoked their device. Only the network knows that; your node has the current state.",
|
||||
"verify.format": "Structure of the listing",
|
||||
"verify.certificate": "Owner's device certificate is valid",
|
||||
"verify.binding": "Certificate belongs to this owner and device",
|
||||
"verify.validity": "Time windows (certificate, listing) are right",
|
||||
"verify.signature": "Signature matches the content",
|
||||
"verify.pow": "Anti-spam work (proof-of-work)",
|
||||
"verify.owner": "Owner (identity)",
|
||||
"verify.device": "Device",
|
||||
"verify.raw": "Raw data (as signed)",
|
||||
"footer.text": "Allmende is free software (AGPL-3.0). There is no operator and there are no fees.",
|
||||
};
|
||||
|
||||
export type Key = keyof typeof de;
|
||||
|
||||
function detect(): "de" | "en" {
|
||||
const q = new URLSearchParams(location.search).get("lang");
|
||||
if (q === "de" || q === "en") return q;
|
||||
return navigator.language?.toLowerCase().startsWith("de") ? "de" : "en";
|
||||
}
|
||||
|
||||
export const lang = detect();
|
||||
const dict: Record<Key, string> = lang === "de" ? de : en;
|
||||
|
||||
export function t(key: Key, vars: Record<string, string | number> = {}): string {
|
||||
return dict[key].replace(/\{(\w+)\}/g, (_, name: string) => String(vars[name] ?? ""));
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Canonical JSON (RFC 8785), restricted to what Allmende uses: numbers must be
|
||||
// safe integers. This must produce byte-for-byte what internal/jcs produces in
|
||||
// Go; test/verify.test.ts checks it against a fixture written by Go.
|
||||
|
||||
export function canonicalize(value: unknown): string {
|
||||
if (value === null) return "null";
|
||||
switch (typeof value) {
|
||||
case "boolean":
|
||||
return value ? "true" : "false";
|
||||
case "number":
|
||||
if (!Number.isSafeInteger(value)) {
|
||||
throw new Error("jcs: only safe integers are supported");
|
||||
}
|
||||
return String(value);
|
||||
case "string":
|
||||
// JSON.stringify escapes exactly what RFC 8785 requires: quote,
|
||||
// backslash, \b \f \n \r \t, and other control characters as \u00xx.
|
||||
return JSON.stringify(value);
|
||||
case "object": {
|
||||
if (Array.isArray(value)) {
|
||||
return "[" + value.map(canonicalize).join(",") + "]";
|
||||
}
|
||||
const obj = value as Record<string, unknown>;
|
||||
// Default sort compares UTF-16 code units, which is what RFC 8785 wants.
|
||||
const keys = Object.keys(obj).sort();
|
||||
return (
|
||||
"{" +
|
||||
keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") +
|
||||
"}"
|
||||
);
|
||||
}
|
||||
default:
|
||||
throw new Error("jcs: unsupported value");
|
||||
}
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
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();
|
||||
@@ -0,0 +1,219 @@
|
||||
// In-browser verification of a listing. The gateway that served it is not
|
||||
// trusted: everything here is checked locally, mirroring Check in
|
||||
// internal/listing and Cert.Check in internal/identity.
|
||||
//
|
||||
// What this cannot know: whether the owner has since revoked the device. Only
|
||||
// nodes that saw the revocation know that, so freshness still rests on the
|
||||
// gateway.
|
||||
|
||||
import { ed25519 } from "@noble/curves/ed25519.js";
|
||||
import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import { canonicalize } from "./jcs.ts";
|
||||
|
||||
const LISTING_CONTEXT = "allmende-listing-v1\n";
|
||||
const CERT_CONTEXT = "allmende-cert-v1\n";
|
||||
|
||||
const DAY = 86_400;
|
||||
const MAX_CERT_LIFETIME = 366 * DAY;
|
||||
const MAX_LISTING_LIFETIME = 30 * DAY;
|
||||
const MAX_CLOCK_SKEW = 10 * 60;
|
||||
|
||||
export interface Cert {
|
||||
v: number;
|
||||
author: string;
|
||||
device: string;
|
||||
issued_at: number;
|
||||
expires_at: number;
|
||||
sig: string;
|
||||
}
|
||||
|
||||
export interface Price {
|
||||
amount_cents: number;
|
||||
currency: string;
|
||||
period: string;
|
||||
}
|
||||
|
||||
export interface Listing {
|
||||
v: number;
|
||||
id: string;
|
||||
author: string;
|
||||
device: string;
|
||||
seq: number;
|
||||
created_at: number;
|
||||
expires_at: number;
|
||||
tombstone?: boolean;
|
||||
kind?: string;
|
||||
category?: string;
|
||||
geohash: string;
|
||||
price?: Price;
|
||||
area_m2?: number;
|
||||
rooms_x2?: number;
|
||||
features?: string[];
|
||||
title?: string;
|
||||
description?: string;
|
||||
delegate?: string;
|
||||
pow: number;
|
||||
cert: Cert;
|
||||
sig: string;
|
||||
}
|
||||
|
||||
export type CheckId =
|
||||
| "format"
|
||||
| "certificate"
|
||||
| "binding"
|
||||
| "validity"
|
||||
| "signature"
|
||||
| "pow";
|
||||
|
||||
export interface Check {
|
||||
id: CheckId;
|
||||
ok: boolean;
|
||||
/** Short technical reason; shown as-is, not translated. */
|
||||
info: string;
|
||||
}
|
||||
|
||||
export interface Verdict {
|
||||
ok: boolean;
|
||||
checks: Check[];
|
||||
powBits: number;
|
||||
}
|
||||
|
||||
export interface Options {
|
||||
/** Current time in unix seconds. */
|
||||
now: number;
|
||||
/** Proof-of-work bits the network requires. */
|
||||
minPowBits: number;
|
||||
}
|
||||
|
||||
const enc = new TextEncoder();
|
||||
|
||||
function hexBytes(s: unknown, bytes: number): Uint8Array | null {
|
||||
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
|
||||
return null;
|
||||
}
|
||||
const out = new Uint8Array(bytes);
|
||||
for (let i = 0; i < bytes; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
||||
return out;
|
||||
}
|
||||
|
||||
export function leadingZeroBits(bytes: Uint8Array): number {
|
||||
let n = 0;
|
||||
for (const b of bytes) {
|
||||
if (b === 0) {
|
||||
n += 8;
|
||||
continue;
|
||||
}
|
||||
return n + Math.clz32(b) - 24;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function without(o: object, key: string): Record<string, unknown> {
|
||||
const copy = { ...(o as Record<string, unknown>) };
|
||||
delete copy[key];
|
||||
return copy;
|
||||
}
|
||||
|
||||
function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function safeInt(v: unknown): v is number {
|
||||
return typeof v === "number" && Number.isSafeInteger(v);
|
||||
}
|
||||
|
||||
function signedBy(
|
||||
context: string,
|
||||
signed: unknown,
|
||||
sigHex: unknown,
|
||||
pubHex: unknown,
|
||||
): boolean {
|
||||
const sig = hexBytes(sigHex, 64);
|
||||
const pub = hexBytes(pubHex, 32);
|
||||
if (!sig || !pub) return false;
|
||||
try {
|
||||
const msg = enc.encode(context + canonicalize(signed));
|
||||
return ed25519.verify(sig, msg, pub);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Verifies a listing as received from a gateway. Never throws. */
|
||||
export function verifyListing(input: unknown, opts: Options): Verdict {
|
||||
const checks: Check[] = [];
|
||||
const add = (id: CheckId, ok: boolean, info = "") => checks.push({ id, ok, info });
|
||||
let powBits = 0;
|
||||
|
||||
const finish = (): Verdict => ({ ok: checks.every((c) => c.ok), checks, powBits });
|
||||
|
||||
// 1. Shape.
|
||||
if (!isObject(input) || !isObject(input.cert)) {
|
||||
add("format", false, "not a listing object");
|
||||
return finish();
|
||||
}
|
||||
const l = input as unknown as Listing;
|
||||
const c = l.cert;
|
||||
const shapeOk =
|
||||
l.v === 1 &&
|
||||
hexBytes(l.id, 16) !== null &&
|
||||
hexBytes(l.author, 32) !== null &&
|
||||
hexBytes(l.device, 32) !== null &&
|
||||
hexBytes(l.sig, 64) !== null &&
|
||||
safeInt(l.seq) &&
|
||||
safeInt(l.created_at) &&
|
||||
safeInt(l.expires_at) &&
|
||||
safeInt(l.pow) &&
|
||||
typeof l.geohash === "string";
|
||||
add("format", shapeOk, shapeOk ? "" : "malformed fields");
|
||||
if (!shapeOk) return finish();
|
||||
|
||||
// 2. Certificate: signed by the identity key, sane lifetime.
|
||||
const certShape =
|
||||
c.v === 1 &&
|
||||
hexBytes(c.author, 32) !== null &&
|
||||
hexBytes(c.device, 32) !== null &&
|
||||
safeInt(c.issued_at) &&
|
||||
safeInt(c.expires_at) &&
|
||||
c.expires_at > c.issued_at &&
|
||||
c.expires_at - c.issued_at <= MAX_CERT_LIFETIME;
|
||||
const certSig = certShape && signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
|
||||
add(
|
||||
"certificate",
|
||||
certSig,
|
||||
!certShape ? "malformed certificate" : certSig ? "" : "bad certificate signature",
|
||||
);
|
||||
if (!certSig) return finish();
|
||||
|
||||
// 3. The certificate must be for this author and this device.
|
||||
const bound = c.author === l.author && c.device === l.device;
|
||||
add("binding", bound, bound ? "" : "certificate is for a different identity or device");
|
||||
|
||||
// 4. Time windows.
|
||||
const reasons: string[] = [];
|
||||
if (!(c.issued_at <= l.created_at && l.created_at < c.expires_at)) {
|
||||
reasons.push("created outside certificate validity");
|
||||
}
|
||||
if (opts.now >= c.expires_at) reasons.push("certificate expired");
|
||||
if (l.expires_at <= l.created_at) reasons.push("expires before it was created");
|
||||
if (l.expires_at - l.created_at > MAX_LISTING_LIFETIME) reasons.push("lifetime over 30 days");
|
||||
if (l.created_at > opts.now + MAX_CLOCK_SKEW) reasons.push("created in the future");
|
||||
if (l.expires_at <= opts.now) reasons.push("expired");
|
||||
add("validity", reasons.length === 0, reasons.join("; "));
|
||||
|
||||
// 5. Device signature over the canonical bytes.
|
||||
const unsigned = without(l, "sig");
|
||||
const sigOk = signedBy(LISTING_CONTEXT, unsigned, l.sig, l.device);
|
||||
add("signature", sigOk, sigOk ? "" : "signature does not match the content");
|
||||
|
||||
// 6. Proof-of-work over the same unsigned bytes.
|
||||
try {
|
||||
powBits = leadingZeroBits(sha256(enc.encode(canonicalize(unsigned))));
|
||||
} catch {
|
||||
powBits = 0;
|
||||
}
|
||||
const powOk = powBits >= opts.minPowBits;
|
||||
add("pow", powOk, `${powBits} bits (network requires ${opts.minPowBits})`);
|
||||
|
||||
return finish();
|
||||
}
|
||||
Reference in New Issue
Block a user