Let the owner change regions by place name, without a restart

The p2p node can now add and drop regions while running (SetRegions):
topics, validators, subscriptions and per-region peer discovery start and
stop with them, and a newly followed region catches up by sync.

PUT /api/v1/regions (owner token) applies a change and the node saves it in
regions.json, which wins over --region from then on. The owner's browser
gets a "Regions" page: search a place by name (GeoNames cities, offline,
CC BY 4.0), follow its cell plus any cell within about 40 km.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw
This commit is contained in:
2026-11-18 10:28:16 +01:00
co-authored by Claude Sonnet 5.5
parent e7bec4fb63
commit fd439710df
24 changed files with 70080 additions and 42 deletions
+54
View File
@@ -115,6 +115,33 @@ const de = {
"own.login": "Anmelden",
"own.loginBad": "Der Knoten hat den Token abgelehnt.",
"own.logout": "Abmelden",
"reg.title": "Regionen",
"reg.intro":
"Dein Knoten hält die Anzeigen dieser Regionen bereit und gibt sie an andere weiter. Suche einen Ort, zum Beispiel Bonn oder Hamburg. Die Änderung gilt sofort und bleibt nach einem Neustart erhalten.",
"reg.search": "Ort suchen",
"reg.placeholder": "z. B. Bonn, Köln, Hamburg",
"reg.results": "Gefundene Orte",
"reg.none": "Dazu habe ich keinen Ort gefunden. Prüfe die Schreibweise, oder gib unten ein Regionskürzel ein.",
"reg.noPlaces": "Die Ortsliste konnte nicht geladen werden. Du kannst unten Regionskürzel eingeben.",
"reg.cellsTitle": "Regionen rund um {place}",
"reg.cellsHelp":
"Eine Region ist ein Gebiet von etwa 100 bis 150 km Breite. Liegt der Ort nahe am Rand, kommt die Nachbarregion dazu, damit dir Anzeigen gleich hinter der Grenze nicht fehlen. Nimm den Haken heraus, was du nicht brauchst.",
"reg.here": "hier",
"reg.add": "Hinzufügen",
"reg.chosen": "Ausgewählte Regionen",
"reg.nothing": "Noch keine Region ausgewählt.",
"reg.remove": "{region} entfernen",
"reg.codes": "Oder Regionskürzel eingeben",
"reg.codesHelp": "Für alle, die sie kennen: drei Zeichen wie u1j, mehrere mit Komma getrennt.",
"reg.badCode": "„{code}“ ist keine Region: es müssen genau 3 Zeichen sein (Ziffern und Buchstaben außer a, i, l, o).",
"reg.needOne": "Wähle mindestens eine Region.",
"reg.tooMany": "Das sind zu viele Regionen (höchstens {max}).",
"reg.save": "Speichern",
"reg.saving": "Speichert …",
"reg.saved": "Gespeichert. Der Knoten folgt jetzt diesen Regionen.",
"reg.failed": "Das hat nicht geklappt.",
"reg.signedOut": "Du bist abgemeldet. Melde dich unter „Meine Anzeigen“ neu an.",
"reg.credit": "Ortsnamen: GeoNames (geonames.org), Lizenz CC BY 4.0.",
"own.listings": "Deine Anzeigen",
"own.none": "Dein Knoten hat keine aktiven Anzeigen.",
"own.perMonth": "/ Monat",
@@ -362,6 +389,33 @@ const en: Record<keyof typeof de, string> = {
"own.login": "Sign in",
"own.loginBad": "The node rejected the token.",
"own.logout": "Sign out",
"reg.title": "Regions",
"reg.intro":
"Your node keeps the listings of these regions and passes them on to others. Search for a place, for example Bonn or Hamburg. A change applies at once and survives a restart.",
"reg.search": "Search for a place",
"reg.placeholder": "e.g. Bonn, Cologne, Hamburg",
"reg.results": "Places found",
"reg.none": "I found no place for that. Check the spelling, or enter a region code below.",
"reg.noPlaces": "The list of places could not be loaded. You can enter region codes below.",
"reg.cellsTitle": "Regions around {place}",
"reg.cellsHelp":
"A region is an area roughly 100 to 150 km across. If the place is near an edge, the neighbouring region is included so you do not miss listings just across the border. Untick what you do not need.",
"reg.here": "here",
"reg.add": "Add",
"reg.chosen": "Chosen regions",
"reg.nothing": "No region chosen yet.",
"reg.remove": "Remove {region}",
"reg.codes": "Or enter region codes",
"reg.codesHelp": "For those who know them: three characters like u1j, several separated by commas.",
"reg.badCode": "“{code}” is not a region: it must be exactly 3 characters (digits and letters except a, i, l, o).",
"reg.needOne": "Choose at least one region.",
"reg.tooMany": "That is too many regions (at most {max}).",
"reg.save": "Save",
"reg.saving": "Saving …",
"reg.saved": "Saved. The node now follows these regions.",
"reg.failed": "That did not work.",
"reg.signedOut": "You are signed out. Sign in again under “My listings”.",
"reg.credit": "Place names: GeoNames (geonames.org), licence CC BY 4.0.",
"own.listings": "Your listings",
"own.none": "Your node has no active listings.",
"own.perMonth": "/ month",
+2
View File
@@ -7,6 +7,7 @@ import { contactPanel, showConversation, showInbox } from "./chat.ts";
import { showOwner } from "./owner.ts";
import { getToken, setToken } from "./ownerApi.ts";
import { showPublish } from "./publish.ts";
import { showRegions } from "./regions.ts";
import { state, verifyOpts } from "./state.ts";
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
@@ -357,6 +358,7 @@ function route(): void {
} else if (m) void showDetail(m[1]!, m[2]!);
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/new") void showPublish();
else if (edit) void showPublish(edit[1]);
else if (own) void showOwner(own[1], own[2]);
+1
View File
@@ -90,6 +90,7 @@ export async function showOwner(listingId?: string, thread?: string): Promise<vo
h("h2", { class: "pane-title" }, t("own.listings")),
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("button", { type: "button", class: "btn", onclick: logout }, t("own.logout"))),
);
+5
View File
@@ -176,6 +176,11 @@ export async function deleteAddress(listing: string): Promise<void> {
}
/** Publishes a new listing. The node signs it and mines its proof-of-work, which takes a few seconds. */
/** Makes the node follow exactly these regions, now and after a restart; returns what it follows. */
export async function setRegions(regions: string[]): Promise<string[]> {
return ((await call("PUT", "/api/v1/regions", { regions })) as { regions: string[] }).regions;
}
export async function createListing(d: Draft): Promise<Listing> {
return (await call("POST", "/api/v1/listings", d)) as Listing;
}
+138
View File
@@ -0,0 +1,138 @@
// Finding regions by place name, offline.
//
// A region is a 3-character geohash cell, about 150 km wide: right for the
// network, meaningless to a person. This turns "Bonn" or "Cologne" into the
// cell(s) to follow, using a list of cities shipped with the page
// (places.tsv, GeoNames, CC-BY 4.0; see scripts/places.mjs). Nothing about what
// a person looks for leaves the device.
import { encodeGeohash } from "./geohash.ts";
export interface Place {
name: string;
lat: number;
lon: number;
/** ISO country code. */
cc: string;
population: number;
/** Other names people use (Köln: Cologne). */
alts: string[];
/** Folded search keys for the name and every alternative, in that order. */
keys: string[];
}
export interface Match {
place: Place;
/** The name that matched, when it is not the place's main name. */
matched: string | null;
}
/** Lower case, no diacritics, ß as ss: "Zürich", "zurich" and "ZÜRICH" are one key. */
export function fold(s: string): string {
return s.normalize("NFD").replace(/\p{M}/gu, "").replace(/ß/g, "ss").toLowerCase();
}
/** How a German keyboard without umlauts writes them: "muenchen" → "munchen". */
function unTranslit(s: string): string {
return s.replace(/ae/g, "a").replace(/oe/g, "o").replace(/ue/g, "u");
}
/** Reads places.tsv: name, ASCII name, lat, lon, country, population, alternatives. */
export function parsePlaces(tsv: string): Place[] {
const out: Place[] = [];
for (const line of tsv.split("\n")) {
if (!line) continue;
const [name, ascii, lat, lon, cc, pop, alt] = line.split("\t");
if (!name || lat === undefined || lon === undefined) continue;
const alts = alt ? alt.split("|") : [];
const keys = [name, ...alts].map(fold);
if (ascii) keys.push(fold(ascii)); // "Koeln": searchable, but shown as "Köln"
out.push({ name, lat: Number(lat), lon: Number(lon), cc: cc ?? "", population: Number(pop) || 0, alts, keys });
}
return out;
}
function score(key: string, q: string): number {
if (key === q) return 0;
if (key.startsWith(q)) return 1;
if (key.split(/[\s-]+/).some((w) => w.startsWith(q))) return 2;
return q.length >= 3 && key.includes(q) ? 3 : 4;
}
/** The best matches for what the person typed: exact names first, then by size. */
export function searchPlaces(places: Place[], query: string, limit = 8): Match[] {
const q1 = fold(query.trim());
if (q1.length < 2) return [];
const qs = [...new Set([q1, unTranslit(q1)])];
const hits: { m: Match; s: number }[] = [];
for (const p of places) {
let best = 4;
let bestKey = 0;
for (let i = 0; i < p.keys.length; i++) {
for (const q of qs) {
const s = score(p.keys[i]!, q);
if (s < best) [best, bestKey] = [s, i];
}
}
if (best < 4) {
// Indexes past the alternatives are the ASCII spelling of the main name.
const matched = bestKey >= 1 && bestKey <= p.alts.length ? p.alts[bestKey - 1]! : null;
hits.push({ m: { place: p, matched }, s: best });
}
}
hits.sort((a, b) => a.s - b.s || b.m.place.population - a.m.place.population);
return hits.slice(0, limit).map((h) => h.m);
}
const KM_PER_DEGREE = 111.2;
/**
* The cells to follow for a place: the one it lies in, then any other cell
* within about `km` of it, so a city near a cell's edge does not miss the
* listings just across it. The place's own cell comes first.
*/
export function cellsNear(lat: number, lon: number, km = 40): string[] {
const cell = (la: number, lo: number) =>
encodeGeohash(Math.max(-89.999, Math.min(89.999, la)), ((((lo + 180) % 360) + 360) % 360) - 180, 3);
const out = [cell(lat, lon)];
const dLat = 1 / KM_PER_DEGREE;
const dLon = 1 / (KM_PER_DEGREE * Math.max(0.05, Math.cos((lat * Math.PI) / 180)));
// Two rings (half and full distance) in 16 directions: a cell clipping the
// circle anywhere is hit by one of them.
for (const r of [km / 2, km]) {
for (let i = 0; i < 16; i++) {
const a = (i / 16) * 2 * Math.PI;
const c = cell(lat + Math.sin(a) * r * dLat, lon + Math.cos(a) * r * dLon);
if (!out.includes(c)) out.push(c);
}
}
return out;
}
/** The largest known place of each cell, to label a code with a name a person knows. */
export function biggestPlaceByCell(places: Place[]): Map<string, Place> {
const by = new Map<string, Place>();
for (const p of places) {
const c = encodeGeohash(p.lat, p.lon, 3);
const cur = by.get(c);
if (!cur || p.population > cur.population) by.set(c, p);
}
return by;
}
let loaded: Promise<Place[]> | null = null;
/** Fetches places.tsv once. Failing is not fatal: region codes can still be typed. */
export function loadPlaces(): Promise<Place[]> {
loaded ??= fetch("places.tsv")
.then((r) => {
if (!r.ok) throw new Error(`${r.status}`);
return r.text();
})
.then(parsePlaces)
.catch((e) => {
loaded = null; // try again next time
throw e;
});
return loaded;
}
+258
View File
@@ -0,0 +1,258 @@
// Choosing the regions a node follows, by place name.
//
// The owner's "Regions" page. A person searches a place ("Bonn", "Cologne"),
// sees the cells around it (the one it lies in and any within about 40 km),
// unticks what they do not want, and adds them. Region codes can still be
// typed for those who know them. Saving changes what the node follows at once.
import { append, clear, h } from "./dom.ts";
import { lang, t } from "./i18n.ts";
import { Unauthorized, getToken, setRegions } from "./ownerApi.ts";
import { biggestPlaceByCell, cellsNear, loadPlaces, searchPlaces, type Match, type Place } from "./places.ts";
import { state } from "./state.ts";
const CODE = /^[0-9bcdefghjkmnpqrstuvwxyz]{3}$/;
const MAX_REGIONS = 20;
function countryName(cc: string): string {
try {
return new Intl.DisplayNames([lang], { type: "region" }).of(cc) ?? cc;
} catch {
return cc;
}
}
function errText(e: unknown): string {
if (e instanceof Unauthorized) return t("reg.signedOut");
if (e && typeof e === "object" && "message" in e) return String((e as { message: unknown }).message);
return typeof e === "string" ? e : t("reg.failed");
}
export interface PickerOptions {
/** Regions already followed. */
initial: string[];
submitLabel: string;
/** Saves the choice; a rejection is shown to the person and they can try again. */
onSubmit: (regions: string[]) => Promise<void>;
}
/** The whole picker: search, chosen regions, code entry and a save button. */
export function regionPicker(opts: PickerOptions): HTMLElement {
const chosen: string[] = [...opts.initial];
let places: Place[] = [];
let biggest = new Map<string, Place>();
const label = (code: string): string => {
const p = biggest.get(code);
return p ? `${code} · ${p.name}` : code;
};
const chips = h("ul", { class: "rp-chips", "aria-label": t("reg.chosen") });
const drawChips = () => {
clear(chips);
if (chosen.length === 0) append(chips, [h("li", { class: "muted" }, t("reg.nothing"))]);
for (const code of chosen) {
append(chips, [
h(
"li",
{ class: "rp-chip" },
h("span", null, label(code)),
h(
"button",
{
type: "button",
class: "rp-chip-x",
"aria-label": t("reg.remove", { region: label(code) }),
onclick: () => {
chosen.splice(chosen.indexOf(code), 1);
drawChips();
},
},
"×",
),
),
]);
}
};
// --- search ---
const results = h("ul", { class: "rp-results", role: "listbox", "aria-label": t("reg.results") });
const cellsBox = h("div", { class: "rp-cells" });
const hint = h("p", { class: "muted small", "aria-live": "polite" });
const showCells = (place: Place) => {
clear(cellsBox);
clear(results);
const cells = cellsNear(place.lat, place.lon);
const boxes = cells.map((code, i) => {
const box = h("input", { type: "checkbox", name: `cell-${code}`, checked: true, "aria-label": code });
return { code, box, row: h("label", { class: "rp-cell" }, box, h("span", null, `${label(code)}${i === 0 ? ` (${t("reg.here")})` : ""}`)) };
});
append(cellsBox, [
h("h2", null, t("reg.cellsTitle", { place: place.name })),
h("p", { class: "muted small" }, t("reg.cellsHelp")),
...boxes.map((b) => b.row),
h(
"div",
{ class: "actions" },
h(
"button",
{
type: "button",
class: "btn",
onclick: () => {
for (const b of boxes) if (b.box.checked && !chosen.includes(b.code)) chosen.push(b.code);
clear(cellsBox);
search.value = "";
drawChips();
},
},
t("reg.add"),
),
),
]);
};
const showMatches = (matches: Match[]) => {
clear(results);
for (const m of matches) {
const p = m.place;
append(results, [
h(
"li",
{ role: "option" },
h(
"button",
{ type: "button", class: "rp-result", onclick: () => showCells(p) },
h("strong", null, p.name),
m.matched ? ` (${m.matched})` : "",
h("span", { class: "muted" }, ` · ${countryName(p.cc)}`),
),
),
]);
}
};
const search = h("input", {
type: "search",
name: "place",
autocomplete: "off",
spellcheck: "false",
placeholder: t("reg.placeholder"),
"aria-label": t("reg.search"),
disabled: true, // until the list of places has loaded: an early search would find nothing
});
search.addEventListener("input", () => {
clear(cellsBox);
const q = search.value;
if (q.trim().length < 2) {
clear(results);
hint.textContent = "";
return;
}
const found = searchPlaces(places, q);
showMatches(found);
hint.textContent = found.length === 0 ? t("reg.none") : "";
});
void loadPlaces().then(
(p) => {
places = p;
biggest = biggestPlaceByCell(p);
search.disabled = false;
drawChips(); // names for the codes already chosen
},
() => {
hint.textContent = t("reg.noPlaces");
},
);
// --- codes and saving ---
const codes = h("input", { type: "text", name: "regions", placeholder: "u1j", autocomplete: "off", spellcheck: "false", "aria-label": t("reg.codes") });
const problem = h("p", { class: "error", role: "alert" });
const go = h("button", { type: "submit", class: "btn primary" }, opts.submitLabel);
const form = h(
"form",
{
class: "stack regions",
onsubmit: (ev) => {
ev.preventDefault();
problem.textContent = "";
for (const raw of codes.value.split(/[\s,;]+/).filter(Boolean)) {
const code = raw.toLowerCase();
if (!CODE.test(code)) {
problem.textContent = t("reg.badCode", { code: raw });
return;
}
if (!chosen.includes(code)) chosen.push(code);
}
codes.value = "";
drawChips();
if (chosen.length === 0) {
problem.textContent = t("reg.needOne");
return;
}
if (chosen.length > MAX_REGIONS) {
problem.textContent = t("reg.tooMany", { max: MAX_REGIONS });
return;
}
go.disabled = true;
const label = go.textContent;
go.textContent = t("reg.saving");
opts.onSubmit([...chosen]).catch((e) => {
problem.textContent = errText(e);
go.disabled = false;
go.textContent = label;
});
},
},
h("label", null, t("reg.search"), search),
hint,
results,
cellsBox,
h("h2", null, t("reg.chosen")),
chips,
h("label", null, t("reg.codes"), codes),
h("p", { class: "muted small" }, t("reg.codesHelp")),
problem,
h("div", { class: "actions" }, go),
h("p", { class: "muted small" }, t("reg.credit")),
);
drawChips();
return form;
}
/** The owner's "Regions" page: shows what the node follows and changes it. */
export function showRegions(message = ""): void {
const root = document.getElementById("app")!;
document.body.classList.remove("wide");
clear(root);
if (!getToken()) {
location.hash = "#/mine"; // the sign-in form
return;
}
const picker = regionPicker({
initial: state.node?.regions ?? [],
submitLabel: t("reg.save"),
onSubmit: async (regions) => {
const now = await setRegions(regions);
if (state.node) state.node.regions = now;
const statusEl = document.getElementById("status");
if (statusEl && state.node) {
statusEl.textContent = t("status.line", { listings: state.node.listings, peers: state.node.peers, regions: now.join(", ") });
}
showRegions(t("reg.saved")); // the page again, showing what is followed now
},
});
append(root, [
h(
"section",
{ class: "panel" },
h("h1", null, t("reg.title")),
h("p", { class: "muted" }, t("reg.intro")),
h("p", { class: "ok", role: "status" }, message),
picker,
),
]);
}