diff --git a/.gitignore b/.gitignore index 0d8e505..59cbac7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,3 @@ /bin/ *.key node_modules/ -web/dist/ diff --git a/README.md b/README.md index 43bc5a1..064e107 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,14 @@ server and no cost. See [docs/PROTOCOL.md](docs/PROTOCOL.md). ``` go build -o bin/node ./cmd/node bin/node init # shows your 12-word recovery phrase once -bin/node run --region u1x # u1x = Hamburg area; API on http://127.0.0.1:8080 +bin/node run --region u1x # u1x = Hamburg area; UI and API on http://127.0.0.1:8080 ``` +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 +(`cd web && npm ci && npm run build && npm test`). + A second node on the same network finds this one automatically (mDNS); across networks, pass `--bootstrap /ip4//tcp//p2p/`. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 3004d84..df6c228 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -147,7 +147,29 @@ token written to `admin.token` at init, mode 0600). | `DELETE /api/v1/listings/{id}` | token | publish a tombstone | Reads send `Access-Control-Allow-Origin: *` (the data is public). Writes are -not cross-origin. Images are not supported yet. +not cross-origin. Images are not supported yet. `status` also reports the +node's PoW `difficulty`, which the browser uses as its minimum. + +## Web UI (`web/`) + +Every node serves a search UI at `GET /`. It is vanilla TypeScript, bundled by +esbuild into `web/dist` (unminified, so it can be read) and **committed**, then +embedded with `go:embed`: `go build` is enough to run a node, Node.js is only +needed to change the UI (`cd web && npm ci && npm run build`). + +- **Verification in the browser.** Every listing is checked locally with + pure-JS ed25519/SHA-256 (works over plain http): format, device certificate, + certificate/listing binding, validity windows, signature, proof-of-work. + Failing results are hidden (with a count) and their content is never shown. + A gateway can therefore withhold listings but not forge them. What a browser + cannot know is whether a device was revoked since; the UI says so. +- **Canonical JSON** is reimplemented in TypeScript and tested against a + fixture signed by the Go code (`internal/listing/testdata/fixture.json`, + refresh with `UPDATE_FIXTURES=1 go test ./internal/listing -run Golden`). +- **Untrusted text.** Listing text is only ever inserted with `textContent`. + The CSP is `default-src 'none'; script-src 'self'; style-src 'self'; ...` + (no inline script or style), plus `nosniff` and `no-referrer`. +- Publishing is not in the UI yet; it stays on the token-protected API. ## Running a node (`cmd/node`) @@ -166,6 +188,6 @@ Proof-of-work per listing and per revocation, plus subscribable blocklists Buyer/seller messaging (E2E, store-and-forward), reciprocity rules, anti- discrimination (AGG) content rules, blocklists, peer scoring and rate limits, -incremental sync and anti-entropy, DHT discovery, web UI, image hosting, +incremental sync and anti-entropy, DHT discovery, UI publishing, image hosting, recovering listings onto a fresh machine with an empty database, a helper to turn a place name into a region. diff --git a/internal/api/api.go b/internal/api/api.go index 4097991..9ef3017 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -22,6 +22,7 @@ import ( "git.stinnesbeck.com/nils/allmende/internal/listing" "git.stinnesbeck.com/nils/allmende/internal/p2p" "git.stinnesbeck.com/nils/allmende/internal/store" + "git.stinnesbeck.com/nils/allmende/web" ) const ( @@ -57,7 +58,35 @@ func New(cfg Config) http.Handler { mux.HandleFunc("POST /api/v1/listings", s.admin(s.create)) mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update)) mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove)) - return mux + mux.Handle("GET /", s.ui()) + return secure(mux) +} + +// contentSecurityPolicy lets the UI load only its own script and styles and +// talk only to its own node. Listing text comes from strangers; the UI never +// inserts it as HTML, and this policy is the second line of defence. +const contentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; " + + "img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" + +// ui serves the embedded browser UI. +func (s *server) ui() http.Handler { + files := http.FileServerFS(web.Files()) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("Content-Security-Policy", contentSecurityPolicy) + h.Set("Referrer-Policy", "no-referrer") + h.Set("Cross-Origin-Opener-Policy", "same-origin") + h.Set("Cache-Control", "no-cache") // revalidate, so upgrades reach users + files.ServeHTTP(w, r) + }) +} + +// secure adds headers every response should carry. +func secure(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + next.ServeHTTP(w, r) + }) } // --- reading -------------------------------------------------------------- @@ -76,6 +105,8 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) { "regions": s.Regions, "peers": s.Node.PeerCount(), "listings": n, + // Lets the browser report how much anti-spam work a listing carries. + "difficulty": s.Difficulty, }) } diff --git a/internal/api/api_test.go b/internal/api/api_test.go index 3db7f0c..1a04953 100644 --- a/internal/api/api_test.go +++ b/internal/api/api_test.go @@ -209,6 +209,72 @@ func TestSearchParameterValidation(t *testing.T) { } } +func TestServesTheWebUIWithStrictHeaders(t *testing.T) { + f := newFixture(t, token) + + get := func(path string) (*http.Response, string) { + resp, err := http.Get(f.srv.URL + path) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, _ := io.ReadAll(resp.Body) + return resp, string(b) + } + + resp, body := get("/") + if resp.StatusCode != 200 || !strings.Contains(body, ` + + diff --git a/web/dist/style.css b/web/dist/style.css new file mode 100644 index 0000000..9ed36f3 --- /dev/null +++ b/web/dist/style.css @@ -0,0 +1,214 @@ +:root { + --bg: #f7f6f2; + --surface: #ffffff; + --text: #1d2420; + --muted: #5f6b64; + --line: #dcdcd2; + --accent: #2f6b4f; + --accent-text: #ffffff; + --ok: #1f7a4d; + --ok-bg: #e3f3ea; + --bad: #b3261e; + --bad-bg: #fbe7e5; + --warn: #8a5a00; + --warn-bg: #fdf1d6; + --radius: 10px; + --maxw: 60rem; + color-scheme: light dark; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #14181a; + --surface: #1c2224; + --text: #e8ece9; + --muted: #9aa7a0; + --line: #2f3a3d; + --accent: #6fbf97; + --accent-text: #0e1a14; + --ok: #6fd6a0; + --ok-bg: #173325; + --bad: #ff8a80; + --bad-bg: #3a1c1a; + --warn: #f2c15b; + --warn-bg: #3a2e12; + } +} + +* { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +a { color: var(--accent); } + +.top, main, .foot { + max-width: var(--maxw); + margin: 0 auto; + padding-left: 16px; + padding-right: 16px; +} + +.top { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 16px; + padding-top: 20px; + padding-bottom: 8px; +} + +.brand { + font-size: 1.6rem; + font-weight: 700; + letter-spacing: -0.02em; + color: var(--text); + text-decoration: none; +} + +.status, .muted, .hint { color: var(--muted); font-size: 0.9rem; } +.info { margin-left: 0.5rem; } +.tagline { color: var(--muted); margin: 4px 0 20px; } +.pad { padding: 16px; } + +h1 { font-size: 1.6rem; line-height: 1.25; margin: 0; } +h2 { font-size: 1.05rem; margin: 0 0 8px; } +h3 { font-size: 1.05rem; line-height: 1.3; margin: 0; } + +/* Search form */ +.filters { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); + gap: 12px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; +} + +.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.field-label { font-size: 0.85rem; font-weight: 600; } + +input, select { + width: 100%; + min-height: 2.5rem; + padding: 6px 10px; + font: inherit; + color: var(--text); + background: var(--bg); + border: 1px solid var(--line); + border-radius: 8px; +} + +input:focus-visible, select:focus-visible, .btn:focus-visible, a:focus-visible, summary:focus-visible { + outline: 3px solid var(--accent); + outline-offset: 2px; +} + +.actions { display: flex; gap: 8px; align-items: end; grid-column: 1 / -1; } + +.btn { + min-height: 2.5rem; + padding: 6px 16px; + font: inherit; + font-weight: 600; + color: var(--text); + background: var(--surface); + border: 1px solid var(--line); + border-radius: 8px; + cursor: pointer; +} +.btn.primary { color: var(--accent-text); background: var(--accent); border-color: var(--accent); } + +/* Results */ +.results { margin-top: 20px; } + +.cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(17rem, 1fr)); + gap: 12px; +} + +.card { + display: block; + padding: 14px 16px; + color: inherit; + text-decoration: none; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); +} +.card:hover { border-color: var(--accent); } +.card p { margin: 4px 0 0; } +.card-top { display: flex; gap: 8px; justify-content: space-between; align-items: flex-start; } +.price { font-size: 1.15rem; font-weight: 700; } +.price.big { font-size: 1.5rem; margin: 6px 0 16px; } +.facts { color: var(--muted); } + +.results-foot { margin: 16px 0 32px; } +.error { color: var(--bad); } +.warn { color: var(--warn); background: var(--warn-bg); padding: 8px 12px; border-radius: 8px; } + +.badge { + flex: none; + padding: 1px 8px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; + border-radius: 999px; +} +.badge.ok { color: var(--ok); background: var(--ok-bg); } +.badge.bad { color: var(--bad); background: var(--bad-bg); } + +/* Detail */ +.back { display: inline-block; margin: 8px 0 16px; } +.detail-head { display: flex; gap: 12px; justify-content: space-between; align-items: flex-start; } + +.panel { + margin: 0 0 12px; + padding: 14px 16px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); +} +.panel p { margin: 0 0 8px; } + +.desc { white-space: pre-wrap; overflow-wrap: anywhere; } + +.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0 0 8px; } +.kv dt { color: var(--muted); } +.kv dd { margin: 0; overflow-wrap: anywhere; } +.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.9rem; } + +.chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0; margin: 0; list-style: none; } +.chips li { padding: 2px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 999px; } + +.checks { list-style: none; margin: 8px 0; padding: 0; } +.checks li { display: flex; flex-wrap: wrap; gap: 0 8px; padding: 2px 0; } +.checks .mark { font-weight: 700; } +.checks .ok .mark { color: var(--ok); } +.checks .bad { color: var(--bad); } + +details { margin-top: 8px; } +summary { cursor: pointer; } +pre { + overflow-x: auto; + padding: 12px; + font-size: 0.8rem; + background: var(--bg); + border: 1px solid var(--line); + border-radius: 8px; +} + +.foot { padding-top: 24px; padding-bottom: 32px; color: var(--muted); font-size: 0.85rem; } + +@media (max-width: 30rem) { + .detail-head { flex-direction: column; } + .kv { grid-template-columns: 1fr; } +} diff --git a/web/embed.go b/web/embed.go new file mode 100644 index 0000000..4ffc4de --- /dev/null +++ b/web/embed.go @@ -0,0 +1,21 @@ +// Package web embeds the browser UI. The UI is built from web/src with +// `npm run build` (see build.mjs) and the output in dist/ is committed, so a +// plain `go build` yields a node that serves its own UI. +package web + +import ( + "embed" + "io/fs" +) + +//go:embed dist +var dist embed.FS + +// Files returns the built UI, rooted at its index.html. +func Files() fs.FS { + sub, err := fs.Sub(dist, "dist") + if err != nil { + panic(err) // dist is embedded at compile time; this cannot fail + } + return sub +} diff --git a/web/package-lock.json b/web/package-lock.json new file mode 100644 index 0000000..3ef64f3 --- /dev/null +++ b/web/package-lock.json @@ -0,0 +1,1299 @@ +{ + "name": "allmende-web", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "allmende-web", + "license": "AGPL-3.0-only", + "dependencies": { + "@noble/curves": "2.4.0", + "@noble/hashes": "2.4.0" + }, + "devDependencies": { + "@types/jsdom": "30.0.0", + "@types/node": "26.6.6", + "esbuild": "0.28.2", + "jsdom": "31.0.1", + "typescript": "7.0.2" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, + "node_modules/@noble/curves": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz", + "integrity": "sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.4.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@types/jsdom": { + "version": "30.0.0", + "resolved": "https://registry.npmjs.org/@types/jsdom/-/jsdom-30.0.0.tgz", + "integrity": "sha512-uAHGxujGE0cDaKGdK28zgDotFtNA7MKq5DXl8LrfdxdCI8VHcg15oJz+amHTChPNI5JpgEPQWc2xFdrw3em/nQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "@types/tough-cookie": "*", + "parse5": "^8.0.0", + "undici-types": "^8.9.0" + } + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/tough-cookie": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-4.0.5.tgz", + "integrity": "sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/data-urls": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-8.0.0.tgz", + "integrity": "sha512-JQUCCK+/CAGbGGx618PlFZMXH81Jtj7t73CHv9dd/zVWvxgGT2zLFRjnKb+Ng46GIwcy+f7f88qd4duqllK+WQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.1.2" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, + "node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/html-encoding-sniffer": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-7.0.0.tgz", + "integrity": "sha512-UikN5yr7xsCDAq87Or5or0PAlD3HJJOKVzM05az588WnpDJ4Ux7a2A53Qi6gofGg2/EtvF/H4hCi/TXfCW4Y6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.15.1" + }, + "engines": { + "node": "^22.13.0 || >=24.0.0" + } + }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsdom": { + "version": "31.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.1.tgz", + "integrity": "sha512-CbhJL8ZQg3eKswxSZth4QO9tW0jPIhmR0vtSXQSbKSfWbwIT6hoRc17wdHIVTQ43KI0mdV5iTJr3281IDgVZ5g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", + "data-urls": "^8.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^7.0.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.5.3", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", + "saxes": "^6.0.0", + "tough-cookie": "^6.0.2", + "undici": "^8.12.3", + "w3c-xmlserializer": "^6.0.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^17.3.0", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + }, + "peerDependencies": { + "@napi-rs/canvas": "^1.0.13" + }, + "peerDependenciesMeta": { + "@napi-rs/canvas": { + "optional": true + } + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.1.tgz", + "integrity": "sha512-hMcVbbUJcQmP8rURWUdYrT1flRiBiBVjq/RYGguJpDUgIXSqdYKlE0CxthmdMWoSlBAuL5bUBa73g0pttSy7Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.1.1" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/tldts": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.4.tgz", + "integrity": "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.5.4" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.4.tgz", + "integrity": "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA==", + "dev": true, + "license": "MIT" + }, + "node_modules/tough-cookie": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz", + "integrity": "sha512-BcDSDW+SIGWVOns1Zm6Yg91q9AEj7eaID0QDY9oIqJD1A8dscNwMcl9Sms2DeuWCNov1X0/oXanHGYQBSLwZsg==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici": { + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", + "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=22.19.0" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + }, + "node_modules/w3c-xmlserializer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-6.0.0.tgz", + "integrity": "sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^22.22.2 || ^24.15.0 || >=26.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-url": { + "version": "17.3.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-17.3.0.tgz", + "integrity": "sha512-KwOAJrpf+GTgBvcBQJcP38sMF0DsQKdwtG+TxM2pW44P6E5k0hDbWrDmyuJDIF0Uef0aQq0ZoJs+5oI+k8ddhg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.16.0", + "tr46": "^7.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^22.14.0 || >=24.0.0" + } + }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..dd3230f --- /dev/null +++ b/web/package.json @@ -0,0 +1,22 @@ +{ + "name": "allmende-web", + "private": true, + "type": "module", + "license": "AGPL-3.0-only", + "scripts": { + "build": "node build.mjs", + "typecheck": "tsc --noEmit", + "test": "node --test test/*.test.ts" + }, + "dependencies": { + "@noble/curves": "2.4.0", + "@noble/hashes": "2.4.0" + }, + "devDependencies": { + "@types/jsdom": "30.0.0", + "@types/node": "26.6.6", + "esbuild": "0.28.2", + "jsdom": "31.0.1", + "typescript": "7.0.2" + } +} diff --git a/web/src/api.ts b/web/src/api.ts new file mode 100644 index 0000000..396af75 --- /dev/null +++ b/web/src/api.ts @@ -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 { + 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 { + return (await getJSON("/api/v1/status")) as Status; +} + +/** Returns raw, unverified listing objects. */ +export async function search(params: URLSearchParams): Promise { + 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 { + return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`); +} diff --git a/web/src/dom.ts b/web/src/dom.ts new file mode 100644 index 0000000..78a4163 --- /dev/null +++ b/web/src/dom.ts @@ -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 void) | undefined>; + +export function h( + 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); +} diff --git a/web/src/format.ts b/web/src/format.ts new file mode 100644 index 0000000..242eee5 --- /dev/null +++ b/web/src/format.ts @@ -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; +} diff --git a/web/src/geohash.ts b/web/src/geohash.ts new file mode 100644 index 0000000..8a7d5f2 --- /dev/null +++ b/web/src/geohash.ts @@ -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, + }; +} diff --git a/web/src/i18n.ts b/web/src/i18n.ts new file mode 100644 index 0000000..ff29867 --- /dev/null +++ b/web/src/i18n.ts @@ -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 = { + "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 = lang === "de" ? de : en; + +export function t(key: Key, vars: Record = {}): string { + return dict[key].replace(/\{(\w+)\}/g, (_, name: string) => String(vars[name] ?? "")); +} diff --git a/web/src/jcs.ts b/web/src/jcs.ts new file mode 100644 index 0000000..cb2cef6 --- /dev/null +++ b/web/src/jcs.ts @@ -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; + // 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"); + } +} diff --git a/web/src/main.ts b/web/src/main.ts new file mode 100644 index 0000000..662890f --- /dev/null +++ b/web/src/main.ts @@ -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 { + 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 => { + 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 => + 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 { + 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 { + 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(); diff --git a/web/src/verify.ts b/web/src/verify.ts new file mode 100644 index 0000000..ca7d17b --- /dev/null +++ b/web/src/verify.ts @@ -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 { + const copy = { ...(o as Record) }; + delete copy[key]; + return copy; +} + +function isObject(v: unknown): v is Record { + 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(); +} diff --git a/web/static/index.html b/web/static/index.html new file mode 100644 index 0000000..2e73511 --- /dev/null +++ b/web/static/index.html @@ -0,0 +1,22 @@ + + + + + + + + Allmende + + + + +
+ Allmende + +
+
+
+ + + + diff --git a/web/static/style.css b/web/static/style.css new file mode 100644 index 0000000..9ed36f3 --- /dev/null +++ b/web/static/style.css @@ -0,0 +1,214 @@ +:root { + --bg: #f7f6f2; + --surface: #ffffff; + --text: #1d2420; + --muted: #5f6b64; + --line: #dcdcd2; + --accent: #2f6b4f; + --accent-text: #ffffff; + --ok: #1f7a4d; + --ok-bg: #e3f3ea; + --bad: #b3261e; + --bad-bg: #fbe7e5; + --warn: #8a5a00; + --warn-bg: #fdf1d6; + --radius: 10px; + --maxw: 60rem; + color-scheme: light dark; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #14181a; + --surface: #1c2224; + --text: #e8ece9; + --muted: #9aa7a0; + --line: #2f3a3d; + --accent: #6fbf97; + --accent-text: #0e1a14; + --ok: #6fd6a0; + --ok-bg: #173325; + --bad: #ff8a80; + --bad-bg: #3a1c1a; + --warn: #f2c15b; + --warn-bg: #3a2e12; + } +} + +* { box-sizing: border-box; } + +html { -webkit-text-size-adjust: 100%; } + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +a { color: var(--accent); } + +.top, main, .foot { + max-width: var(--maxw); + margin: 0 auto; + padding-left: 16px; + padding-right: 16px; +} + +.top { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 16px; + padding-top: 20px; + padding-bottom: 8px; +} + +.brand { + font-size: 1.6rem; + font-weight: 700; + letter-spacing: -0.02em; + color: var(--text); + text-decoration: none; +} + +.status, .muted, .hint { color: var(--muted); font-size: 0.9rem; } +.info { margin-left: 0.5rem; } +.tagline { color: var(--muted); margin: 4px 0 20px; } +.pad { padding: 16px; } + +h1 { font-size: 1.6rem; line-height: 1.25; margin: 0; } +h2 { font-size: 1.05rem; margin: 0 0 8px; } +h3 { font-size: 1.05rem; line-height: 1.3; margin: 0; } + +/* Search form */ +.filters { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr)); + gap: 12px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 16px; +} + +.field { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.field-label { font-size: 0.85rem; font-weight: 600; } + +input, select { + width: 100%; + min-height: 2.5rem; + padding: 6px 10px; + font: inherit; + color: var(--text); + background: var(--bg); + border: 1px solid var(--line); + border-radius: 8px; +} + +input:focus-visible, select:focus-visible, .btn:focus-visible, a:focus-visible, summary:focus-visible { + outline: 3px solid var(--accent); + outline-offset: 2px; +} + +.actions { display: flex; gap: 8px; align-items: end; grid-column: 1 / -1; } + +.btn { + min-height: 2.5rem; + padding: 6px 16px; + font: inherit; + font-weight: 600; + color: var(--text); + background: var(--surface); + border: 1px solid var(--line); + border-radius: 8px; + cursor: pointer; +} +.btn.primary { color: var(--accent-text); background: var(--accent); border-color: var(--accent); } + +/* Results */ +.results { margin-top: 20px; } + +.cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(17rem, 1fr)); + gap: 12px; +} + +.card { + display: block; + padding: 14px 16px; + color: inherit; + text-decoration: none; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); +} +.card:hover { border-color: var(--accent); } +.card p { margin: 4px 0 0; } +.card-top { display: flex; gap: 8px; justify-content: space-between; align-items: flex-start; } +.price { font-size: 1.15rem; font-weight: 700; } +.price.big { font-size: 1.5rem; margin: 6px 0 16px; } +.facts { color: var(--muted); } + +.results-foot { margin: 16px 0 32px; } +.error { color: var(--bad); } +.warn { color: var(--warn); background: var(--warn-bg); padding: 8px 12px; border-radius: 8px; } + +.badge { + flex: none; + padding: 1px 8px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; + border-radius: 999px; +} +.badge.ok { color: var(--ok); background: var(--ok-bg); } +.badge.bad { color: var(--bad); background: var(--bad-bg); } + +/* Detail */ +.back { display: inline-block; margin: 8px 0 16px; } +.detail-head { display: flex; gap: 12px; justify-content: space-between; align-items: flex-start; } + +.panel { + margin: 0 0 12px; + padding: 14px 16px; + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); +} +.panel p { margin: 0 0 8px; } + +.desc { white-space: pre-wrap; overflow-wrap: anywhere; } + +.kv { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0 0 8px; } +.kv dt { color: var(--muted); } +.kv dd { margin: 0; overflow-wrap: anywhere; } +.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.9rem; } + +.chips { display: flex; flex-wrap: wrap; gap: 6px; padding: 0; margin: 0; list-style: none; } +.chips li { padding: 2px 10px; background: var(--bg); border: 1px solid var(--line); border-radius: 999px; } + +.checks { list-style: none; margin: 8px 0; padding: 0; } +.checks li { display: flex; flex-wrap: wrap; gap: 0 8px; padding: 2px 0; } +.checks .mark { font-weight: 700; } +.checks .ok .mark { color: var(--ok); } +.checks .bad { color: var(--bad); } + +details { margin-top: 8px; } +summary { cursor: pointer; } +pre { + overflow-x: auto; + padding: 12px; + font-size: 0.8rem; + background: var(--bg); + border: 1px solid var(--line); + border-radius: 8px; +} + +.foot { padding-top: 24px; padding-bottom: 32px; color: var(--muted); font-size: 0.85rem; } + +@media (max-width: 30rem) { + .detail-head { flex-direction: column; } + .kv { grid-template-columns: 1fr; } +} diff --git a/web/test/helpers.ts b/web/test/helpers.ts new file mode 100644 index 0000000..1ec55d4 --- /dev/null +++ b/web/test/helpers.ts @@ -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 = {}): Listing { + const idKey = ed25519.utils.randomSecretKey(); + const devKey = ed25519.utils.randomSecretKey(); + const cert: Record = { + 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 = { + 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; +} + +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 { + 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((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; + 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(), + }; +} diff --git a/web/test/jcs.test.ts b/web/test/jcs.test.ts new file mode 100644 index 0000000..8ac0c22 --- /dev/null +++ b/web/test/jcs.test.ts @@ -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\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"); +}); diff --git a/web/test/ui.test.ts b/web/test/ui.test.ts new file mode 100644 index 0000000..6f31a28 --- /dev/null +++ b/web/test/ui.test.ts @@ -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 = `Haus`; +const XSS_DESC = `\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: ["fett"] }); + +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 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(); + } +}); diff --git a/web/test/verify.test.ts b/web/test/verify.test.ts new file mode 100644 index 0000000..d21ec82 --- /dev/null +++ b/web/test/verify.test.ts @@ -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 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 = { + 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 = { + 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); +}); diff --git a/web/tsconfig.json b/web/tsconfig.json new file mode 100644 index 0000000..f6bdeb0 --- /dev/null +++ b/web/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "types": ["node"], + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "noEmit": true + }, + "include": ["src", "test"] +}