diff --git a/Dockerfile b/Dockerfile index 65e49f9..90c76fe 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,12 @@ # docker build -t allmende . # docker run --rm -it -v allmende-data:/data allmende init # once; shows the recovery phrase # docker run -d --name allmende -v allmende-data:/data \ -# -p 127.0.0.1:8080:8080 -p 4001:4001 -p 4001:4001/udp allmende # run (Bonn by default) +# -p 127.0.0.1:8080:8080 -p 4001:4001 -p 4001:4001/udp allmende # run +# docker logs allmende # the owner sign-in link; open it and choose your regions +# +# The node starts without a region: the owner picks one by place name in the +# browser ("My listings" > "Regions") and it applies at once. The choice is kept +# in the volume (/data/regions.json) and wins over --region from then on. # # The HTTP port also serves the owner API, which the admin token protects, so # publish it on 127.0.0.1 only and put a TLS proxy in front for public use. @@ -30,9 +35,9 @@ EXPOSE 8080 4001/tcp 4001/udp HEALTHCHECK --interval=30s --timeout=5s --start-period=20s \ CMD wget -qO- http://127.0.0.1:8080/api/v1/status >/dev/null || exit 1 ENTRYPOINT ["allmende"] -# Override the whole command to change regions or add peers, e.g. +# Override the whole command to start with regions or add peers, e.g. # docker run ... allmende run --http 0.0.0.0:8080 \ # --listen /ip4/0.0.0.0/tcp/4001 --listen /ip4/0.0.0.0/udp/4001/quic-v1 \ # --region u1j --region u1h --bootstrap /ip4/203.0.113.5/tcp/4001/p2p/ # A bootstrap node adds --public (and needs a public address). -CMD ["run", "--http", "0.0.0.0:8080", "--listen", "/ip4/0.0.0.0/tcp/4001", "--listen", "/ip4/0.0.0.0/udp/4001/quic-v1", "--region", "u1j"] +CMD ["run", "--http", "0.0.0.0:8080", "--listen", "/ip4/0.0.0.0/tcp/4001", "--listen", "/ip4/0.0.0.0/udp/4001/quic-v1"] diff --git a/README.md b/README.md index 758dd1f..d210790 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,13 @@ server and no cost. See [docs/PROTOCOL.md](docs/PROTOCOL.md). ``` go build -o bin/allmende ./cmd/allmende bin/allmende init # shows your 12-word recovery phrase once -bin/allmende run --region u1x # u1x = Hamburg area; UI and API on http://127.0.0.1:8080 +bin/allmende run # UI and API on http://127.0.0.1:8080 ``` +`run` prints a sign-in link. Open it and choose your region by place name +("My listings" > "Regions"). To start with a region instead, add `--region u1x` +(u1x = Hamburg area). + Open http://127.0.0.1:8080 to search. Your browser checks every listing's signature itself, so you don't have to trust the node it talks to. The UI is pre-built and embedded; Node.js is only needed to change it @@ -29,8 +33,9 @@ pasted coordinates (only a ~1 km area is published, never the address), and listings can be edited, renewed (30 days, manually) or deleted there. **Regions** are the areas a node keeps listings for (3-character geohash cells, -about 100 to 150 km wide). `--region` sets them the first time. After that the -owner changes them in the browser: "My listings", then "Regions". Search a place +about 100 to 150 km wide). A new node follows none: the owner chooses them in the +browser, "My listings", then "Regions" (or `--region` sets them at the first start). +Search a place by name (Bonn, Cologne, München, …); the page offers the place's own cell and any cell within about 40 km, and the change applies at once, without a restart. The choice is kept in `regions.json` in the data directory and wins over `--region` @@ -65,13 +70,13 @@ targets: `make build run test check e2e docker` (`make help` lists them). docker build -t allmende . # or: make docker docker run --rm -it -v allmende-data:/data allmende init # once; write down the phrase docker run -d --name allmende -v allmende-data:/data \ - -p 127.0.0.1:8080:8080 -p 4001:4001 -p 4001:4001/udp allmende # Bonn (u1j) by default + -p 127.0.0.1:8080:8080 -p 4001:4001 -p 4001:4001/udp allmende # then choose regions in the browser docker logs allmende | grep -A1 'Owner login' # the sign-in link ``` The image runs as a non-root user and keeps its data in the `/data` volume. -To change regions or add peers, replace the command (see the end of the -`Dockerfile`). Publish port 8080 on `127.0.0.1` only: it also serves the owner +Regions are chosen in the browser and kept in the volume. To start with some +or to add peers, replace the command (see the end of the `Dockerfile`). Publish port 8080 on `127.0.0.1` only: it also serves the owner API. For public use put a TLS reverse proxy in front. **NixOS** (flake) @@ -83,7 +88,7 @@ API. For public use put a TLS reverse proxy in front. nixosConfigurations.myhost = nixpkgs.lib.nixosSystem { modules = [ allmende.nixosModules.default - { services.allmende = { enable = true; regions = [ "u1j" ]; openFirewall = true; }; } + { services.allmende = { enable = true; openFirewall = true; }; } # regions: choose in the browser, or regions = [ "u1j" ] ]; }; }; diff --git a/cmd/allmende/init.go b/cmd/allmende/init.go index 0fb275e..71854d6 100644 --- a/cmd/allmende/init.go +++ b/cmd/allmende/init.go @@ -59,7 +59,7 @@ func cmdInit(args []string) error { fmt.Printf("\nDone. This machine is set up as a device of identity %s…\n", dev.Cert.Author[:12]) fmt.Printf("Your device certificate is valid until %s.\n\n", time.Unix(dev.Cert.ExpiresAt, 0).Format("2006-01-02")) - fmt.Printf("Next: allmende run --region --data %s\n", *data) + fmt.Printf("Next: allmende run --data %s\nThen open the sign-in link it prints and choose your region (or add --region to start with one).\n", *data) fmt.Printf("The admin token for publishing is in %s\n", filepath.Join(*data, tokenFile)) return nil } diff --git a/cmd/allmende/run.go b/cmd/allmende/run.go index cb86c46..4bbc6d8 100644 --- a/cmd/allmende/run.go +++ b/cmd/allmende/run.go @@ -66,10 +66,8 @@ func cmdRun(args []string) error { } regions = saved } - // A bootstrap node may follow no region: it then only helps others connect. - if len(regions) == 0 && !*public { - return errors.New("choose at least one region to replicate, e.g. --region u1x (a region is a 3-character geohash, about 150 km wide)") - } + // Without a region the node only helps others connect, until the owner + // chooses one in the browser (see the sign-in hint printed below). if !*noDefaultBootstrap { bootstrap = append(bootstrap, p2p.DefaultBootstrap) } @@ -186,6 +184,11 @@ func cmdRun(args []string) error { // log file. It sits in the URL fragment, which a browser never sends to // a server; the page moves it into sessionStorage and removes it. fmt.Fprintf(os.Stderr, "\nOwner login (answer your inbox in the browser):\n %s\n\n", loginURL(ln.Addr().String(), token)) + if len(regions) == 0 && !*public { + fmt.Fprint(os.Stderr, "This node follows no region yet. Open the link above and choose where you want\nlistings from (and to publish) under \"My listings\" > \"Regions\".\n\n") + } + } else if len(regions) == 0 && !*public { + log.Warn("this node follows no region and has no admin token, so nobody can choose one: pass --region") } go announce(ctx, log, node, st, dev.Cert.Author) diff --git a/internal/api/api.go b/internal/api/api.go index 89cf9cf..4adf218 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -65,11 +65,16 @@ type RegionKeeper interface { // in them, so this keeps "follow the world" from being one click. const MaxRegions = 20 +// regions is what the node follows now, never nil: the UI reads it as a list. func (s *server) regions() []string { + r := s.Regions if s.RegionKeeper != nil { - return s.RegionKeeper.Regions() + r = s.RegionKeeper.Regions() } - return s.Regions + if r == nil { + return []string{} + } + return r } type server struct { diff --git a/internal/api/api_test.go b/internal/api/api_test.go index ae44125..7bded68 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -373,3 +373,16 @@ func TestRegionsCannotBeChangedWithoutAKeeper(t *testing.T) { t.Fatal("regions changed on a node that has no keeper") } } + +type noRegions struct{} + +func (noRegions) Regions() []string { return nil } +func (noRegions) SetRegions([]string) error { return nil } + +func TestAStatusWithoutRegionsListsNone(t *testing.T) { + f := newFixture(t, token, func(c *Config) { c.Regions = nil; c.RegionKeeper = noRegions{} }) + _, body := f.do(t, "GET", "/api/v1/status", "", false) + if !strings.Contains(string(body), `"regions":[]`) { + t.Fatalf("regions must be an empty list the UI can read, not null: %s", body) + } +} diff --git a/internal/p2p/p2p_test.go b/internal/p2p/p2p_test.go index f04bc5f..1edf1a1 100644 --- a/internal/p2p/p2p_test.go +++ b/internal/p2p/p2p_test.go @@ -385,3 +385,24 @@ func TestRegionsChangeWhileRunning(t *testing.T) { t.Fatalf("regions changed to %v", got) } } + +func TestANodeWithoutRegionsFollowsTheFirstOneWhenChosen(t *testing.T) { + a := startNode(t, nil, "u1x") + b := startNode(t, nil) // no region yet + connect(t, b, a) + if got := b.Regions(); len(got) != 0 { + t.Fatalf("regions = %v", got) + } + l := a.listing(t, "u1xjhx") + if err := a.Publish(context.Background(), l); err != nil { + t.Fatal(err) + } + time.Sleep(300 * time.Millisecond) + if count(b) != 0 { + t.Fatal("a node without regions stored a listing") + } + if err := b.SetRegions([]string{"u1x"}); err != nil { + t.Fatal(err) + } + eventually(t, "the first region is followed and caught up", func() bool { return count(b) == 1 }) +} diff --git a/nix/module.nix b/nix/module.nix index a910dcb..fb1ab67 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -54,9 +54,12 @@ in default = [ ]; example = [ "u1j" ]; description = '' - Regions to replicate: 3-character geohashes, each about 150 km wide. - `u1j` is Bonn, `u1h` Cologne, `u1x` Hamburg. May be empty only for a - bootstrap node ({option}`public`). + Regions to start with: 3-character geohashes, each about 100 to 150 km + wide. `u1j` is Bonn, `u1h` Cologne, `u1x` Hamburg. Leave it empty and + the owner chooses by place name in the browser instead ("My listings" + > "Regions"); that choice is kept in `regions.json` in + {option}`dataDir` and wins over this list from then on (delete the file + to go back to it). ''; }; @@ -108,7 +111,7 @@ in dataDir = lib.mkOption { type = lib.types.path; default = "/var/lib/allmende"; - description = "Where keys, the admin token and the database live."; + description = "Where keys, the admin token, the chosen regions and the database live."; }; extraArgs = lib.mkOption { @@ -120,13 +123,6 @@ in }; config = lib.mkIf cfg.enable { - assertions = [ - { - assertion = cfg.regions != [ ] || cfg.public; - message = "services.allmende.regions needs at least one region, for example [ \"u1j\" ] (only a public bootstrap node may have none)."; - } - ]; - users.users.allmende = { isSystemUser = true; group = "allmende"; diff --git a/nix/test.nix b/nix/test.nix index 3bb34dd..af5e519 100644 --- a/nix/test.nix +++ b/nix/test.nix @@ -7,7 +7,7 @@ pkgs.testers.runNixOSTest { imports = [ module ]; services.allmende = { enable = true; - regions = [ "u1j" ]; + # No regions: the owner chooses the first one in the browser (see below). openFirewall = true; }; }; @@ -33,8 +33,21 @@ pkgs.testers.runNixOSTest { machine.wait_for_open_port(8080) machine.wait_for_open_port(4001) status = machine.succeed("curl -sf http://127.0.0.1:8080/api/v1/status") - assert '"regions":["u1j"]' in status, status + assert '"regions":[]' in status, status machine.succeed("curl -sf http://127.0.0.1:8080/ | grep -qi ' \u201ERegionen\u201C.", + "search.chooseRegions": "Regionen w\xE4hlen", "status.unreachable": "Dieser Knoten ist nicht erreichbar.", "filter.kind": "Angebot", "filter.category": "Art", @@ -359,6 +362,9 @@ var de = { var en = { "app.tagline": "Homes to rent and buy, run by everyone. Free, with no company behind it.", "status.line": "{listings} listings \xB7 {peers} connected nodes \xB7 regions: {regions}", + "status.noRegions": "none yet", + "search.noRegions": "This node follows no region yet, so it has no listings. Whoever runs it chooses regions under \u201CMy listings\u201D > \u201CRegions\u201D.", + "search.chooseRegions": "Choose regions", "status.unreachable": "This node is not reachable.", "filter.kind": "Offer", "filter.category": "Type", @@ -617,6 +623,13 @@ function t(key, vars = {}) { } // src/format.ts +function statusLine(n) { + return t("status.line", { + listings: n.listings, + peers: n.peers, + regions: n.regions.length ? n.regions.join(", ") : t("status.noRegions") + }); +} function money(cents) { return new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(cents / 100); } @@ -761,7 +774,7 @@ function keepFresh(alive, run, ms = FOREGROUND_MS, doc = document) { schedule(); } -// ../../web/node_modules/@noble/ciphers/utils.js +// node_modules/@noble/ciphers/utils.js /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; @@ -940,7 +953,7 @@ function copyBytes(bytes2) { return Uint8Array.from(abytes(bytes2)); } -// ../../web/node_modules/@noble/ciphers/_arx.js +// node_modules/@noble/ciphers/_arx.js var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0)); var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))(); var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))(); @@ -1070,7 +1083,7 @@ function createCipher(core, opts) { }; } -// ../../web/node_modules/@noble/ciphers/_poly1305.js +// node_modules/@noble/ciphers/_poly1305.js function u8to16(a, i) { return a[i++] & 255 | (a[i++] & 255) << 8; } @@ -1321,7 +1334,7 @@ var Poly1305 = class { }; var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); -// ../../web/node_modules/@noble/ciphers/chacha.js +// node_modules/@noble/ciphers/chacha.js function chachaCore(s, k, n, out, cnt, rounds = 20) { let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; @@ -1471,7 +1484,7 @@ var chacha20poly1305 = /* @__PURE__ */ wrapCipher( /* @__PURE__ */ _poly1305_aead(chacha20) ); -// ../../web/node_modules/@noble/hashes/_u64.js +// node_modules/@noble/hashes/_u64.js var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))(); var _32n = /* @__PURE__ */ BigInt(32); function fromBig(n, le = false) { @@ -1514,7 +1527,7 @@ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0 var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; -// ../../web/node_modules/@noble/hashes/utils.js +// node_modules/@noble/hashes/utils.js function isBytes2(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; } @@ -1679,7 +1692,7 @@ var oidNist = (suffix) => ({ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) }); -// ../../web/node_modules/@noble/hashes/_md.js +// node_modules/@noble/hashes/_md.js function Chi(a, b, c) { return a & b ^ ~a & c; } @@ -1810,7 +1823,7 @@ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([ 327033209 ]); -// ../../web/node_modules/@noble/hashes/sha2.js +// node_modules/@noble/hashes/sha2.js var SHA256_K = /* @__PURE__ */ Uint32Array.from([ 1116352408, 1899447441, @@ -2207,7 +2220,7 @@ var sha512 = /* @__PURE__ */ createHasher( /* @__PURE__ */ oidNist(3) ); -// ../../web/node_modules/@noble/curves/utils.js +// node_modules/@noble/curves/utils.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ function aarray(item, title, inner = () => { }) { @@ -2328,7 +2341,7 @@ function validateObject(object, fields = {}, optFields = {}, title = "object") { iter(optFields, true); } -// ../../web/node_modules/@noble/curves/abstract/modular.js +// node_modules/@noble/curves/abstract/modular.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n2 = /* @__PURE__ */ BigInt(0); var _1n2 = /* @__PURE__ */ BigInt(1); @@ -2758,7 +2771,7 @@ function Field(ORDER, opts = {}) { return new _Field(ORDER, opts); } -// ../../web/node_modules/@noble/curves/abstract/curve.js +// node_modules/@noble/curves/abstract/curve.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n3 = /* @__PURE__ */ BigInt(0); var _1n3 = /* @__PURE__ */ BigInt(1); @@ -3146,7 +3159,7 @@ function createKeygen(randomSecretKey, getPublicKey) { }; } -// ../../web/node_modules/@noble/curves/abstract/edwards.js +// node_modules/@noble/curves/abstract/edwards.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n4 = /* @__PURE__ */ BigInt(0); var _1n4 = /* @__PURE__ */ BigInt(1); @@ -3598,7 +3611,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) { }); } -// ../../web/node_modules/@noble/curves/abstract/montgomery.js +// node_modules/@noble/curves/abstract/montgomery.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n5 = /* @__PURE__ */ BigInt(0); var _1n5 = /* @__PURE__ */ BigInt(1); @@ -3746,7 +3759,7 @@ function montgomery(curveDef) { }); } -// ../../web/node_modules/@noble/curves/ed25519.js +// node_modules/@noble/curves/ed25519.js /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ var _0n6 = /* @__PURE__ */ BigInt(0); var _1n6 = /* @__PURE__ */ BigInt(1); @@ -3847,7 +3860,7 @@ var x25519 = /* @__PURE__ */ (() => { }); })(); -// ../../web/node_modules/@noble/hashes/hmac.js +// node_modules/@noble/hashes/hmac.js var _HMAC = class { oHash; iHash; @@ -3924,7 +3937,7 @@ var hmac = /* @__PURE__ */ (() => { return hmac_; })(); -// ../../web/node_modules/@noble/hashes/hkdf.js +// node_modules/@noble/hashes/hkdf.js var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); function expand(hash, prk, info, length = 32, _recycled) { @@ -6022,9 +6035,7 @@ function showRegions(message = "") { const now = await setRegions(regions); if (state.node) state.node.regions = now; const statusEl2 = document.getElementById("status"); - if (statusEl2 && state.node) { - statusEl2.textContent = t("status.line", { listings: state.node.listings, peers: state.node.peers, regions: now.join(", ") }); - } + if (statusEl2 && state.node) statusEl2.textContent = statusLine(state.node); showRegions(t("reg.saved")); } }); @@ -6200,7 +6211,19 @@ function showSearch(params) { const gen = state.generation; clear(app4); const results = h("div", { class: "results", "aria-live": "polite" }); - app4.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results); + app4.append(h("p", { class: "tagline" }, t("app.tagline"))); + if (state.node && state.node.regions.length === 0) { + app4.append( + h( + "p", + { class: "notice", role: "status" }, + t("search.noRegions"), + " ", + getToken() ? h("a", { href: "#/mine/regions" }, t("search.chooseRegions")) : null + ) + ); + } + app4.append(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"))); @@ -6336,8 +6359,13 @@ function route() { document.body.classList.remove("wide"); if (login) { setToken(login[1]); - history.replaceState(null, "", location.pathname + location.search + "#/mine"); - void showOwner(); + if (state.node && state.node.regions.length === 0) { + history.replaceState(null, "", location.pathname + location.search + "#/mine/regions"); + showRegions(); + } else { + history.replaceState(null, "", location.pathname + location.search + "#/mine"); + void showOwner(); + } } 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(); @@ -6354,11 +6382,7 @@ async function boot() { document.getElementById("foot").textContent = t("footer.text"); try { state.node = await getStatus(); - statusEl.textContent = t("status.line", { - listings: state.node.listings, - peers: state.node.peers, - regions: state.node.regions.join(", ") - }); + statusEl.textContent = statusLine(state.node); } catch { statusEl.textContent = t("status.unreachable"); } diff --git a/web/dist/style.css b/web/dist/style.css index 26b881e..81c2df8 100644 --- a/web/dist/style.css +++ b/web/dist/style.css @@ -75,6 +75,7 @@ a { color: var(--accent); } .status, .muted, .hint { color: var(--muted); font-size: 0.9rem; } .info { margin-left: 0.5rem; } .tagline { color: var(--muted); margin: 4px 0 20px; } +.notice { margin: 0 0 16px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); } .pad { padding: 16px; } h1 { font-size: 1.6rem; line-height: 1.25; margin: 0; } diff --git a/web/src/format.ts b/web/src/format.ts index 0f8b4b7..7a76e67 100644 --- a/web/src/format.ts +++ b/web/src/format.ts @@ -1,6 +1,15 @@ import { lang, t } from "./i18n.ts"; import type { Listing } from "./verify.ts"; +/** The line under the title: what the node holds and follows. */ +export function statusLine(n: { listings: number; peers: number; regions: string[] }): string { + return t("status.line", { + listings: n.listings, + peers: n.peers, + regions: n.regions.length ? n.regions.join(", ") : t("status.noRegions"), + }); +} + export function money(cents: number): string { return new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(cents / 100); } diff --git a/web/src/i18n.ts b/web/src/i18n.ts index 5652dcc..f0473cd 100644 --- a/web/src/i18n.ts +++ b/web/src/i18n.ts @@ -3,6 +3,9 @@ const de = { "app.tagline": "Wohnungen und Häuser, getragen von allen. Kostenlos, ohne Konzern.", "status.line": "{listings} Anzeigen · {peers} verbundene Knoten · Regionen: {regions}", + "status.noRegions": "noch keine", + "search.noRegions": "Dieser Knoten folgt noch keiner Region und hat deshalb keine Anzeigen. Wer ihn betreibt, wählt Regionen unter „Meine Anzeigen“ > „Regionen“.", + "search.chooseRegions": "Regionen wählen", "status.unreachable": "Dieser Knoten ist nicht erreichbar.", "filter.kind": "Angebot", "filter.category": "Art", @@ -277,6 +280,9 @@ const de = { const en: Record = { "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.noRegions": "none yet", + "search.noRegions": "This node follows no region yet, so it has no listings. Whoever runs it chooses regions under “My listings” > “Regions”.", + "search.chooseRegions": "Choose regions", "status.unreachable": "This node is not reachable.", "filter.kind": "Offer", "filter.category": "Type", diff --git a/web/src/main.ts b/web/src/main.ts index 44760dd..432da65 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -1,6 +1,6 @@ import { getListing, getStatus, search } from "./api.ts"; import { append, clear, h } from "./dom.ts"; -import { date, price, rooms, shortKey } from "./format.ts"; +import { date, price, rooms, shortKey, statusLine } from "./format.ts"; import { decodeGeohash } from "./geohash.ts"; import { lang, t, type Key } from "./i18n.ts"; import { contactPanel, showConversation, showInbox } from "./chat.ts"; @@ -191,7 +191,19 @@ function showSearch(params: URLSearchParams): void { const gen = state.generation; clear(app); const results = h("div", { class: "results", "aria-live": "polite" }); - app.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results); + app.append(h("p", { class: "tagline" }, t("app.tagline"))); + if (state.node && state.node.regions.length === 0) { + app.append( + h( + "p", + { class: "notice", role: "status" }, + t("search.noRegions"), + " ", + getToken() ? h("a", { href: "#/mine/regions" }, t("search.chooseRegions")) : null, + ), + ); + } + app.append(searchForm(params), results); const prefix = params.get("geohash")?.trim().toLowerCase(); if (prefix && !GEOHASH_PREFIX.test(prefix)) { @@ -353,8 +365,14 @@ function route(): void { if (login) { // The token came in the URL fragment: keep it for this tab and take it out of the address bar. setToken(login[1]!); - history.replaceState(null, "", location.pathname + location.search + "#/mine"); - void showOwner(); + if (state.node && state.node.regions.length === 0) { + // A node that follows nothing has nothing to show: the first thing to do is choose. + history.replaceState(null, "", location.pathname + location.search + "#/mine/regions"); + showRegions(); + } else { + history.replaceState(null, "", location.pathname + location.search + "#/mine"); + void showOwner(); + } } 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(); @@ -372,11 +390,7 @@ async function boot(): Promise { document.getElementById("foot")!.textContent = t("footer.text"); try { state.node = await getStatus(); - statusEl.textContent = t("status.line", { - listings: state.node.listings, - peers: state.node.peers, - regions: state.node.regions.join(", "), - }); + statusEl.textContent = statusLine(state.node); } catch { statusEl.textContent = t("status.unreachable"); } diff --git a/web/src/regions.ts b/web/src/regions.ts index 7dcc6a8..d59f0eb 100644 --- a/web/src/regions.ts +++ b/web/src/regions.ts @@ -6,6 +6,7 @@ // typed for those who know them. Saving changes what the node follows at once. import { append, clear, h } from "./dom.ts"; +import { statusLine } from "./format.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"; @@ -239,9 +240,7 @@ export function showRegions(message = ""): void { 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(", ") }); - } + if (statusEl && state.node) statusEl.textContent = statusLine(state.node); showRegions(t("reg.saved")); // the page again, showing what is followed now }, }); diff --git a/web/static/style.css b/web/static/style.css index 26b881e..81c2df8 100644 --- a/web/static/style.css +++ b/web/static/style.css @@ -75,6 +75,7 @@ a { color: var(--accent); } .status, .muted, .hint { color: var(--muted); font-size: 0.9rem; } .info { margin-left: 0.5rem; } .tagline { color: var(--muted); margin: 4px 0 20px; } +.notice { margin: 0 0 16px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); } .pad { padding: 16px; } h1 { font-size: 1.6rem; line-height: 1.25; margin: 0; } diff --git a/web/test/helpers.ts b/web/test/helpers.ts index 7ddbd33..b974c94 100644 --- a/web/test/helpers.ts +++ b/web/test/helpers.ts @@ -192,6 +192,8 @@ export interface GatewayOptions { /** For a requested listing id, answer with this other listing instead. */ swap?: unknown; statusFails?: boolean; + /** The regions the node reports; default ["u1x"]. */ + regions?: string[]; } export async function startGateway(opts: GatewayOptions): Promise { @@ -252,7 +254,7 @@ export async function startGateway(opts: GatewayOptions): Promise { peer_id: "12D3KooWTest", author: "a".repeat(64), device: "b".repeat(64), - regions: ["u1x"], + regions: opts.regions ?? ["u1x"], peers: 2, listings: opts.listings.length, difficulty: DIFFICULTY, diff --git a/web/test/owner.test.ts b/web/test/owner.test.ts index 98f48c9..ccf11ab 100644 --- a/web/test/owner.test.ts +++ b/web/test/owner.test.ts @@ -392,7 +392,7 @@ test("signing out forgets the token", async () => { test("the owner picks regions by place name and the node follows them at once", async () => { open(`#/login/${TOKEN}`); await page!.waitFor(() => qa(".pane-listings .ocard").length === 2, "the listings"); - qa(".pane-listings a").find((a) => a.textContent === "Regions")!.click(); + (qa(".pane-listings a").find((a) => a.textContent === "Regions") as HTMLElement).click(); await page!.waitFor(() => q('[name="place"]') !== null, "the regions page"); assert.ok(q(".rp-chips")!.textContent!.includes("u1x"), "what the node follows now"); const search = q('[name="place"]')!; @@ -437,3 +437,27 @@ test("without signing in the regions page leads to the sign-in", async () => { function location_(hash: string): void { page!.window.location.hash = hash; } + +test("a node without regions: visitors are told, and the owner's login leads to choosing the first region", async () => { + await gw.close(); + gw = await startGateway({ listings: [], regions: [] }); + gw.owner = node.handler; + + open("#/"); + await page!.waitFor(() => /follows no region yet/.test(text()), "the notice for visitors"); + assert.ok(text().includes("regions: none yet"), "the status line says so"); + assert.equal(q(".notice a"), null, "no link for someone who is not signed in"); + page!.close(); + + open(`#/login/${TOKEN}`); + await page!.waitFor(() => q('[name="place"]') !== null, "the regions page, straight after login"); + assert.equal(page!.window.location.hash, "#/mine/regions"); + assert.ok(q(".rp-chips")!.textContent!.includes("No region chosen yet")); + + q('[name="regions"]')!.value = "u1j"; + submit(q("form")!); + await page!.waitFor(() => /Saved/.test(text()), "saved"); + assert.ok(text().includes("regions: u1j"), "the status line shows the first region"); + const put = node.s.calls.find((c) => c.method === "PUT" && c.path === "/api/v1/regions")!; + assert.equal(put.body, '{"regions":["u1j"]}'); +});