Add browser UI with in-browser signature verification
Every node now serves a search and listing-detail UI at GET /. It is vanilla TypeScript, bundled unminified into web/dist (committed) and embedded with go:embed, so `go build` is enough to run a node. The browser verifies each listing itself (certificate, binding, validity, signature, proof-of-work) with pure-JS ed25519, so a gateway can withhold listings but not forge them. Unverifiable results are hidden and their content is never shown. Listing text is only inserted via textContent and the UI is served with a strict CSP. Canonical JSON is reimplemented in TypeScript and tested against a golden fixture signed by the Go code. /api/v1/status now reports difficulty. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,3 @@
|
|||||||
/bin/
|
/bin/
|
||||||
*.key
|
*.key
|
||||||
node_modules/
|
node_modules/
|
||||||
web/dist/
|
|
||||||
|
|||||||
@@ -9,9 +9,14 @@ server and no cost. See [docs/PROTOCOL.md](docs/PROTOCOL.md).
|
|||||||
```
|
```
|
||||||
go build -o bin/node ./cmd/node
|
go build -o bin/node ./cmd/node
|
||||||
bin/node init # shows your 12-word recovery phrase once
|
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
|
A second node on the same network finds this one automatically (mDNS); across
|
||||||
networks, pass `--bootstrap /ip4/<addr>/tcp/<port>/p2p/<peer id>`.
|
networks, pass `--bootstrap /ip4/<addr>/tcp/<port>/p2p/<peer id>`.
|
||||||
|
|
||||||
|
|||||||
+24
-2
@@ -147,7 +147,29 @@ token written to `admin.token` at init, mode 0600).
|
|||||||
| `DELETE /api/v1/listings/{id}` | token | publish a tombstone |
|
| `DELETE /api/v1/listings/{id}` | token | publish a tombstone |
|
||||||
|
|
||||||
Reads send `Access-Control-Allow-Origin: *` (the data is public). Writes are
|
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`)
|
## 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-
|
Buyer/seller messaging (E2E, store-and-forward), reciprocity rules, anti-
|
||||||
discrimination (AGG) content rules, blocklists, peer scoring and rate limits,
|
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
|
recovering listings onto a fresh machine with an empty database, a helper to
|
||||||
turn a place name into a region.
|
turn a place name into a region.
|
||||||
|
|||||||
+32
-1
@@ -22,6 +22,7 @@ import (
|
|||||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||||
|
"git.stinnesbeck.com/nils/allmende/web"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -57,7 +58,35 @@ func New(cfg Config) http.Handler {
|
|||||||
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
|
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
|
||||||
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
|
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
|
||||||
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
|
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 --------------------------------------------------------------
|
// --- reading --------------------------------------------------------------
|
||||||
@@ -76,6 +105,8 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
|||||||
"regions": s.Regions,
|
"regions": s.Regions,
|
||||||
"peers": s.Node.PeerCount(),
|
"peers": s.Node.PeerCount(),
|
||||||
"listings": n,
|
"listings": n,
|
||||||
|
// Lets the browser report how much anti-spam work a listing carries.
|
||||||
|
"difficulty": s.Difficulty,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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, `<script type="module" src="app.js">`) {
|
||||||
|
t.Fatalf("index: %d %.80s", resp.StatusCode, body)
|
||||||
|
}
|
||||||
|
csp := resp.Header.Get("Content-Security-Policy")
|
||||||
|
for _, want := range []string{"default-src 'none'", "script-src 'self'", "connect-src 'self'", "frame-ancestors 'none'"} {
|
||||||
|
if !strings.Contains(csp, want) {
|
||||||
|
t.Fatalf("CSP %q lacks %q", csp, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(csp, "unsafe-inline") || strings.Contains(csp, "unsafe-eval") {
|
||||||
|
t.Fatalf("CSP must not allow inline or eval: %q", csp)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, body = get("/app.js")
|
||||||
|
if resp.StatusCode != 200 || !strings.Contains(resp.Header.Get("Content-Type"), "javascript") {
|
||||||
|
t.Fatalf("app.js: %d %s", resp.StatusCode, resp.Header.Get("Content-Type"))
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, "allmende-listing-v1") {
|
||||||
|
t.Fatal("the embedded bundle does not contain the verifier; rebuild it with `npm run build` in web/")
|
||||||
|
}
|
||||||
|
if resp, _ = get("/style.css"); resp.StatusCode != 200 {
|
||||||
|
t.Fatalf("style.css: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if resp, _ = get("/nope.js"); resp.StatusCode != 404 {
|
||||||
|
t.Fatalf("unknown file: %d, want 404", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The API is untouched and also refuses content sniffing.
|
||||||
|
resp, _ = get("/api/v1/status")
|
||||||
|
if resp.StatusCode != 200 || resp.Header.Get("X-Content-Type-Options") != "nosniff" {
|
||||||
|
t.Fatalf("status: %d nosniff=%q", resp.StatusCode, resp.Header.Get("X-Content-Type-Options"))
|
||||||
|
}
|
||||||
|
if req, _ := http.NewRequest("POST", f.srv.URL+"/", nil); req != nil {
|
||||||
|
if r, err := http.DefaultClient.Do(req); err == nil {
|
||||||
|
r.Body.Close()
|
||||||
|
if r.StatusCode != 405 {
|
||||||
|
t.Fatalf("POST /: %d, want 405", r.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStatusReportsDifficultyForTheBrowserVerifier(t *testing.T) {
|
||||||
|
f := newFixture(t, token)
|
||||||
|
_, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||||
|
var st map[string]any
|
||||||
|
_ = json.Unmarshal(body, &st)
|
||||||
|
if st["difficulty"] != float64(difficulty) {
|
||||||
|
t.Fatalf("difficulty = %v, want %d", st["difficulty"], difficulty)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestStatus(t *testing.T) {
|
func TestStatus(t *testing.T) {
|
||||||
f := newFixture(t, token)
|
f := newFixture(t, token)
|
||||||
code, body := f.do(t, "GET", "/api/v1/status", "", false)
|
code, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||||
|
|||||||
@@ -27,6 +27,15 @@ func Generate() (*Identity, error) {
|
|||||||
return &Identity{priv: priv}, nil
|
return &Identity{priv: priv}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FromSeed builds an identity from a 32-byte ed25519 seed. It exists so tests
|
||||||
|
// and fixtures can use fixed keys; real keys come from Generate or a phrase.
|
||||||
|
func FromSeed(seed []byte) (*Identity, error) {
|
||||||
|
if len(seed) != ed25519.SeedSize {
|
||||||
|
return nil, fmt.Errorf("identity: seed must be %d bytes", ed25519.SeedSize)
|
||||||
|
}
|
||||||
|
return &Identity{priv: ed25519.NewKeyFromSeed(seed)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Load reads an identity previously written by Save.
|
// Load reads an identity previously written by Save.
|
||||||
func Load(path string) (*Identity, error) {
|
func Load(path string) (*Identity, error) {
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package listing
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.stinnesbeck.com/nils/allmende/internal/identity"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The browser re-implements canonicalization and verification. This golden
|
||||||
|
// file is produced by the Go implementation and consumed by the TypeScript
|
||||||
|
// tests (web/test), so the two can never drift apart unnoticed.
|
||||||
|
//
|
||||||
|
// Refresh it after an intentional format change with:
|
||||||
|
//
|
||||||
|
// UPDATE_FIXTURES=1 go test ./internal/listing -run TestGoldenFixture
|
||||||
|
const fixturePath = "testdata/fixture.json"
|
||||||
|
|
||||||
|
const (
|
||||||
|
fixtureNow = 1_800_000_000
|
||||||
|
fixtureDifficulty = 12
|
||||||
|
// Awkward text on purpose: newline, umlauts, an emoji, quotes, a
|
||||||
|
// backslash and U+2028 (legal in JSON, but a classic JavaScript trap).
|
||||||
|
fixtureDescription = "Zeile 1\nZeile 2 – Überraschung \U0001F3E0 \"quoted\" \\ back
end"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fixtureFile struct {
|
||||||
|
Now int64 `json:"now"`
|
||||||
|
Difficulty int `json:"difficulty"`
|
||||||
|
Canonical string `json:"canonical"` // the exact bytes Go signed
|
||||||
|
Listing json.RawMessage `json:"listing"` // the same record as plain JSON
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildFixture(t *testing.T) (*Listing, []byte) {
|
||||||
|
t.Helper()
|
||||||
|
root, err := identity.FromPhrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
seed := bytes.Repeat([]byte{7}, 32)
|
||||||
|
devKey, err := identity.FromSeed(seed)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
now := time.Unix(fixtureNow, 0)
|
||||||
|
cert, err := identity.IssueCert(root, devKey.PublicKeyHex(), now.Add(-time.Hour), now.Add(90*24*time.Hour))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l := &Listing{
|
||||||
|
Version: Version,
|
||||||
|
ID: "00112233445566778899aabbccddeeff",
|
||||||
|
Seq: 3,
|
||||||
|
CreatedAt: now.Unix(),
|
||||||
|
ExpiresAt: now.Add(14 * 24 * time.Hour).Unix(),
|
||||||
|
Kind: "rent",
|
||||||
|
Category: "apartment",
|
||||||
|
Geohash: "u1xjhx",
|
||||||
|
Price: &Price{AmountCents: 123450, Currency: "EUR", Period: "month"},
|
||||||
|
AreaM2: 62,
|
||||||
|
RoomsX2: 5,
|
||||||
|
Features: []string{"balcony", "Aufzug"},
|
||||||
|
Title: "Helle 2,5-Zimmer-Wohnung – Altbau",
|
||||||
|
Description: fixtureDescription,
|
||||||
|
}
|
||||||
|
if err := l.Seal(&identity.Device{Key: devKey, Cert: cert}, fixtureDifficulty); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
canon, err := l.Bytes()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return l, canon
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGoldenFixture(t *testing.T) {
|
||||||
|
l, canon := buildFixture(t)
|
||||||
|
|
||||||
|
// Go itself must accept what it signed.
|
||||||
|
if err := l.Check(time.Unix(fixtureNow, 0), fixtureDifficulty); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
plain, err := json.MarshalIndent(l, " ", " ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want, err := json.MarshalIndent(fixtureFile{
|
||||||
|
Now: fixtureNow, Difficulty: fixtureDifficulty,
|
||||||
|
Canonical: string(canon), Listing: plain,
|
||||||
|
}, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want = append(want, '\n')
|
||||||
|
|
||||||
|
if os.Getenv("UPDATE_FIXTURES") != "" {
|
||||||
|
if err := os.MkdirAll("testdata", 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(fixturePath, want, 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Log("fixture updated")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(fixturePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%v (run with UPDATE_FIXTURES=1 to create it)", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(got, want) {
|
||||||
|
t.Fatal("golden fixture is stale: the signed format changed. If intentional, run:\n" +
|
||||||
|
" UPDATE_FIXTURES=1 go test ./internal/listing -run TestGoldenFixture\n" +
|
||||||
|
"and make sure the web verifier (web/src/verify.ts) matches")
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"now": 1800000000,
|
||||||
|
"difficulty": 12,
|
||||||
|
"canonical": "{\"area_m2\":62,\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"category\":\"apartment\",\"cert\":{\"author\":\"381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803\",\"device\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"expires_at\":1807776000,\"issued_at\":1799996400,\"sig\":\"dab8cef621f829c47eaf5bfea7fcaa3dad144b718d322b4c4989ecc33931c925afcfb50f642ce0c692bc53ceb57f67ddd3c347ff95a496e4f6413ecb5b32ac0e\",\"v\":1},\"created_at\":1800000000,\"description\":\"Zeile 1\\nZeile 2 – Überraschung 🏠 \\\"quoted\\\" \\\\ back \u2028 end\",\"device\":\"ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\",\"expires_at\":1801209600,\"features\":[\"balcony\",\"Aufzug\"],\"geohash\":\"u1xjhx\",\"id\":\"00112233445566778899aabbccddeeff\",\"kind\":\"rent\",\"pow\":321,\"price\":{\"amount_cents\":123450,\"currency\":\"EUR\",\"period\":\"month\"},\"rooms_x2\":5,\"seq\":3,\"sig\":\"de48948903561fce01941e750eef07261acea3273fb7e88287cba98606ee852181cba2f9342aeb8c491e747676c2a299d09ce4aabf0968b5da2cb1351b24dc05\",\"title\":\"Helle 2,5-Zimmer-Wohnung – Altbau\",\"v\":1}",
|
||||||
|
"listing": {
|
||||||
|
"v": 1,
|
||||||
|
"id": "00112233445566778899aabbccddeeff",
|
||||||
|
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||||
|
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||||
|
"seq": 3,
|
||||||
|
"created_at": 1800000000,
|
||||||
|
"expires_at": 1801209600,
|
||||||
|
"kind": "rent",
|
||||||
|
"category": "apartment",
|
||||||
|
"geohash": "u1xjhx",
|
||||||
|
"price": {
|
||||||
|
"amount_cents": 123450,
|
||||||
|
"currency": "EUR",
|
||||||
|
"period": "month"
|
||||||
|
},
|
||||||
|
"area_m2": 62,
|
||||||
|
"rooms_x2": 5,
|
||||||
|
"features": [
|
||||||
|
"balcony",
|
||||||
|
"Aufzug"
|
||||||
|
],
|
||||||
|
"title": "Helle 2,5-Zimmer-Wohnung – Altbau",
|
||||||
|
"description": "Zeile 1\nZeile 2 – Überraschung 🏠 \"quoted\" \\ back \u2028 end",
|
||||||
|
"pow": 321,
|
||||||
|
"cert": {
|
||||||
|
"v": 1,
|
||||||
|
"author": "381a6cfff5b6ee2eacc48fbd6d3f3afcf1cb7d5042eadfce9804774834166803",
|
||||||
|
"device": "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c",
|
||||||
|
"issued_at": 1799996400,
|
||||||
|
"expires_at": 1807776000,
|
||||||
|
"sig": "dab8cef621f829c47eaf5bfea7fcaa3dad144b718d322b4c4989ecc33931c925afcfb50f642ce0c692bc53ceb57f67ddd3c347ff95a496e4f6413ecb5b32ac0e"
|
||||||
|
},
|
||||||
|
"sig": "de48948903561fce01941e750eef07261acea3273fb7e88287cba98606ee852181cba2f9342aeb8c491e747676c2a299d09ce4aabf0968b5da2cb1351b24dc05"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Bundles src/main.ts into dist/app.js and copies the static files next to it.
|
||||||
|
// The output is committed and embedded into the Go binary (see embed.go), so a
|
||||||
|
// plain `go build` produces a node with its UI and nobody needs Node to run
|
||||||
|
// one. The bundle is deliberately not minified: it is the code that decides
|
||||||
|
// whether a listing is genuine, so it should stay readable.
|
||||||
|
|
||||||
|
import { build } from "esbuild";
|
||||||
|
import { cp, mkdir, rm } from "node:fs/promises";
|
||||||
|
|
||||||
|
await rm("dist", { recursive: true, force: true });
|
||||||
|
await mkdir("dist", { recursive: true });
|
||||||
|
|
||||||
|
await build({
|
||||||
|
entryPoints: ["src/main.ts"],
|
||||||
|
bundle: true,
|
||||||
|
format: "esm",
|
||||||
|
target: "es2022",
|
||||||
|
outfile: "dist/app.js",
|
||||||
|
legalComments: "inline",
|
||||||
|
logLevel: "info",
|
||||||
|
});
|
||||||
|
|
||||||
|
await cp("static", "dist", { recursive: true });
|
||||||
Vendored
+2846
File diff suppressed because it is too large
Load Diff
Vendored
+22
@@ -0,0 +1,22 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light dark">
|
||||||
|
<meta name="referrer" content="no-referrer">
|
||||||
|
<title>Allmende</title>
|
||||||
|
<link rel="icon" href="data:,">
|
||||||
|
<link rel="stylesheet" href="style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="top">
|
||||||
|
<a class="brand" href="#/">Allmende</a>
|
||||||
|
<span id="status" class="status"></span>
|
||||||
|
</header>
|
||||||
|
<main id="app"></main>
|
||||||
|
<footer id="foot" class="foot"></footer>
|
||||||
|
<noscript><p class="error pad">Allmende braucht JavaScript, um Signaturen in deinem Browser zu prüfen. / Allmende needs JavaScript to verify signatures in your browser.</p></noscript>
|
||||||
|
<script type="module" src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Vendored
+214
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
Generated
+1299
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// Talks to the node that served this page. Everything it returns is untrusted
|
||||||
|
// until verify.ts has checked it.
|
||||||
|
|
||||||
|
export interface Status {
|
||||||
|
peer_id: string;
|
||||||
|
author: string;
|
||||||
|
device: string;
|
||||||
|
regions: string[];
|
||||||
|
peers: number;
|
||||||
|
listings: number;
|
||||||
|
difficulty: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getJSON(url: string): Promise<unknown> {
|
||||||
|
const res = await fetch(url, { headers: { Accept: "application/json" } });
|
||||||
|
if (res.status === 404) return null;
|
||||||
|
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getStatus(): Promise<Status> {
|
||||||
|
return (await getJSON("/api/v1/status")) as Status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns raw, unverified listing objects. */
|
||||||
|
export async function search(params: URLSearchParams): Promise<unknown[]> {
|
||||||
|
const data = await getJSON(`/api/v1/listings?${params}`);
|
||||||
|
if (!Array.isArray(data)) throw new Error("unexpected response");
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getListing(author: string, id: string): Promise<unknown | null> {
|
||||||
|
return getJSON(`/api/v1/listings/${encodeURIComponent(author)}/${encodeURIComponent(id)}`);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Tiny DOM builder. Listing content comes from strangers, so it is only ever
|
||||||
|
// inserted as text nodes or attribute values, never as HTML.
|
||||||
|
|
||||||
|
export type Child = Node | string | number | null | undefined | false;
|
||||||
|
export type Props = Record<string, string | number | boolean | ((e: Event) => void) | undefined>;
|
||||||
|
|
||||||
|
export function h<K extends keyof HTMLElementTagNameMap>(
|
||||||
|
tag: K,
|
||||||
|
props: Props | null = null,
|
||||||
|
...children: Child[]
|
||||||
|
): HTMLElementTagNameMap[K] {
|
||||||
|
const el = document.createElement(tag);
|
||||||
|
for (const [key, value] of Object.entries(props ?? {})) {
|
||||||
|
if (value === undefined || value === false) continue;
|
||||||
|
if (typeof value === "function") {
|
||||||
|
el.addEventListener(key.replace(/^on/, "").toLowerCase(), value);
|
||||||
|
} else if (value === true) {
|
||||||
|
el.setAttribute(key, "");
|
||||||
|
} else {
|
||||||
|
el.setAttribute(key, String(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
append(el, children);
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function append(parent: Node, children: Child[]): void {
|
||||||
|
for (const c of children) {
|
||||||
|
if (c === null || c === undefined || c === false) continue;
|
||||||
|
parent.appendChild(typeof c === "object" ? c : document.createTextNode(String(c)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clear(el: Element): void {
|
||||||
|
while (el.firstChild) el.removeChild(el.firstChild);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { lang, t } from "./i18n.ts";
|
||||||
|
import type { Listing } from "./verify.ts";
|
||||||
|
|
||||||
|
export function money(cents: number): string {
|
||||||
|
return new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(cents / 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** rooms_x2 stores rooms * 2, so 2.5 rooms are 5. */
|
||||||
|
export function rooms(x2: number): string {
|
||||||
|
return t("card.rooms", { n: (x2 / 2).toLocaleString(lang, { maximumFractionDigits: 1 }) });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function date(unix: number): string {
|
||||||
|
return new Date(unix * 1000).toLocaleDateString(lang, { dateStyle: "medium" });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function price(l: Listing): string {
|
||||||
|
if (!l.price) return "";
|
||||||
|
const base = money(l.price.amount_cents);
|
||||||
|
return l.price.period === "month" ? `${base} ${t("card.perMonth")}` : base;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A key shortened for display: abcd1234…9f2e */
|
||||||
|
export function shortKey(hex: string): string {
|
||||||
|
return hex.length > 16 ? `${hex.slice(0, 8)}…${hex.slice(-4)}` : hex;
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// Geohash decoding, only to show where a listing roughly is.
|
||||||
|
|
||||||
|
const ALPHABET = "0123456789bcdefghjkmnpqrstuvwxyz";
|
||||||
|
|
||||||
|
export interface Area {
|
||||||
|
lat: number;
|
||||||
|
lon: number;
|
||||||
|
/** Half the height and width of the cell, in degrees. */
|
||||||
|
latErr: number;
|
||||||
|
lonErr: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeGeohash(hash: string): Area | null {
|
||||||
|
let lat: [number, number] = [-90, 90];
|
||||||
|
let lon: [number, number] = [-180, 180];
|
||||||
|
let evenBit = true;
|
||||||
|
for (const ch of hash) {
|
||||||
|
const idx = ALPHABET.indexOf(ch);
|
||||||
|
if (idx < 0) return null;
|
||||||
|
for (let bit = 4; bit >= 0; bit--) {
|
||||||
|
const on = (idx >> bit) & 1;
|
||||||
|
const range = evenBit ? lon : lat;
|
||||||
|
const mid = (range[0] + range[1]) / 2;
|
||||||
|
if (on) range[0] = mid;
|
||||||
|
else range[1] = mid;
|
||||||
|
evenBit = !evenBit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
lat: (lat[0] + lat[1]) / 2,
|
||||||
|
lon: (lon[0] + lon[1]) / 2,
|
||||||
|
latErr: (lat[1] - lat[0]) / 2,
|
||||||
|
lonErr: (lon[1] - lon[0]) / 2,
|
||||||
|
};
|
||||||
|
}
|
||||||
+147
@@ -0,0 +1,147 @@
|
|||||||
|
// German first (the launch region is Germany), English as fallback.
|
||||||
|
|
||||||
|
const de = {
|
||||||
|
"app.tagline": "Wohnungen und Häuser, getragen von allen. Kostenlos, ohne Konzern.",
|
||||||
|
"status.line": "{listings} Anzeigen · {peers} verbundene Knoten · Regionen: {regions}",
|
||||||
|
"status.unreachable": "Dieser Knoten ist nicht erreichbar.",
|
||||||
|
"filter.kind": "Angebot",
|
||||||
|
"filter.category": "Art",
|
||||||
|
"filter.region": "Gebiet (Geohash)",
|
||||||
|
"filter.regionHint": "z. B. u1x für den Raum Hamburg, genauer: u1xj",
|
||||||
|
"filter.maxPrice": "Preis bis (€)",
|
||||||
|
"filter.minArea": "Fläche ab (m²)",
|
||||||
|
"filter.minRooms": "Zimmer ab",
|
||||||
|
"filter.any": "Alle",
|
||||||
|
"filter.search": "Suchen",
|
||||||
|
"filter.reset": "Zurücksetzen",
|
||||||
|
"kind.rent": "Miete",
|
||||||
|
"kind.sale": "Kauf",
|
||||||
|
"cat.apartment": "Wohnung",
|
||||||
|
"cat.house": "Haus",
|
||||||
|
"cat.room": "Zimmer",
|
||||||
|
"cat.commercial": "Gewerbe",
|
||||||
|
"results.none": "Keine Anzeigen gefunden.",
|
||||||
|
"results.loading": "Lädt …",
|
||||||
|
"results.more": "Mehr laden",
|
||||||
|
"results.hidden": "{n} Ergebnis(se) ausgeblendet, weil die Signatur nicht geprüft werden konnte.",
|
||||||
|
"results.error": "Die Suche ist fehlgeschlagen.",
|
||||||
|
"card.perMonth": "/ Monat",
|
||||||
|
"card.rooms": "{n} Zimmer",
|
||||||
|
"card.area": "{n} m²",
|
||||||
|
"badge.ok": "Signatur geprüft",
|
||||||
|
"badge.bad": "Nicht verifiziert",
|
||||||
|
"detail.back": "← Zurück zur Suche",
|
||||||
|
"detail.notFound": "Diese Anzeige gibt es nicht (mehr).",
|
||||||
|
"detail.unverified":
|
||||||
|
"Diese Anzeige konnte nicht verifiziert werden und wird deshalb nicht angezeigt. Sie könnte gefälscht oder verändert sein.",
|
||||||
|
"detail.features": "Ausstattung",
|
||||||
|
"detail.facts": "Eckdaten",
|
||||||
|
"detail.kind": "Angebot",
|
||||||
|
"detail.category": "Art",
|
||||||
|
"detail.area": "Fläche",
|
||||||
|
"detail.rooms": "Zimmer",
|
||||||
|
"detail.published": "Veröffentlicht",
|
||||||
|
"detail.expires": "Läuft ab",
|
||||||
|
"detail.version": "Version",
|
||||||
|
"detail.location": "Lage (ungefähr, ca. 1 km)",
|
||||||
|
"detail.map": "Auf OpenStreetMap ansehen (externe Seite)",
|
||||||
|
"detail.contact": "Kontakt",
|
||||||
|
"detail.contactSoon":
|
||||||
|
"Der Kontakt zum Anbieter läuft über dessen eigenen Knoten und ist noch nicht verfügbar. Die genaue Adresse wird nie öffentlich verteilt.",
|
||||||
|
"verify.title": "Prüfung in deinem Browser",
|
||||||
|
"verify.intro":
|
||||||
|
"Diese Prüfung läuft lokal, nicht auf dem Server. Ein Knoten kann Anzeigen also nicht unbemerkt fälschen.",
|
||||||
|
"verify.limit":
|
||||||
|
"Nicht prüfbar: ob der Anbieter sein Gerät inzwischen gesperrt hat. Das weiß nur das Netzwerk; dein Knoten kennt den aktuellen Stand.",
|
||||||
|
"verify.format": "Aufbau der Anzeige",
|
||||||
|
"verify.certificate": "Gerätezertifikat des Anbieters ist gültig",
|
||||||
|
"verify.binding": "Zertifikat gehört zu diesem Anbieter und Gerät",
|
||||||
|
"verify.validity": "Zeiträume (Zertifikat, Anzeige) stimmen",
|
||||||
|
"verify.signature": "Signatur passt zum Inhalt",
|
||||||
|
"verify.pow": "Rechenaufwand gegen Spam (Proof-of-Work)",
|
||||||
|
"verify.owner": "Anbieter (Identität)",
|
||||||
|
"verify.device": "Gerät",
|
||||||
|
"verify.raw": "Rohdaten (so signiert)",
|
||||||
|
"footer.text":
|
||||||
|
"Allmende ist freie Software (AGPL-3.0). Es gibt keinen Betreiber und keine Gebühren.",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const en: Record<keyof typeof de, string> = {
|
||||||
|
"app.tagline": "Homes to rent and buy, run by everyone. Free, with no company behind it.",
|
||||||
|
"status.line": "{listings} listings · {peers} connected nodes · regions: {regions}",
|
||||||
|
"status.unreachable": "This node is not reachable.",
|
||||||
|
"filter.kind": "Offer",
|
||||||
|
"filter.category": "Type",
|
||||||
|
"filter.region": "Area (geohash)",
|
||||||
|
"filter.regionHint": "e.g. u1x for the Hamburg area, more precise: u1xj",
|
||||||
|
"filter.maxPrice": "Price up to (€)",
|
||||||
|
"filter.minArea": "Area from (m²)",
|
||||||
|
"filter.minRooms": "Rooms from",
|
||||||
|
"filter.any": "Any",
|
||||||
|
"filter.search": "Search",
|
||||||
|
"filter.reset": "Reset",
|
||||||
|
"kind.rent": "Rent",
|
||||||
|
"kind.sale": "Buy",
|
||||||
|
"cat.apartment": "Apartment",
|
||||||
|
"cat.house": "House",
|
||||||
|
"cat.room": "Room",
|
||||||
|
"cat.commercial": "Commercial",
|
||||||
|
"results.none": "No listings found.",
|
||||||
|
"results.loading": "Loading …",
|
||||||
|
"results.more": "Load more",
|
||||||
|
"results.hidden": "{n} result(s) hidden because their signature could not be verified.",
|
||||||
|
"results.error": "The search failed.",
|
||||||
|
"card.perMonth": "/ month",
|
||||||
|
"card.rooms": "{n} rooms",
|
||||||
|
"card.area": "{n} m²",
|
||||||
|
"badge.ok": "Signature verified",
|
||||||
|
"badge.bad": "Not verified",
|
||||||
|
"detail.back": "← Back to search",
|
||||||
|
"detail.notFound": "This listing does not exist (any more).",
|
||||||
|
"detail.unverified":
|
||||||
|
"This listing could not be verified and is therefore not shown. It may be forged or altered.",
|
||||||
|
"detail.features": "Features",
|
||||||
|
"detail.facts": "Key facts",
|
||||||
|
"detail.kind": "Offer",
|
||||||
|
"detail.category": "Type",
|
||||||
|
"detail.area": "Area",
|
||||||
|
"detail.rooms": "Rooms",
|
||||||
|
"detail.published": "Published",
|
||||||
|
"detail.expires": "Expires",
|
||||||
|
"detail.version": "Version",
|
||||||
|
"detail.location": "Location (approximate, about 1 km)",
|
||||||
|
"detail.map": "View on OpenStreetMap (external site)",
|
||||||
|
"detail.contact": "Contact",
|
||||||
|
"detail.contactSoon":
|
||||||
|
"Contact goes through the owner's own node and is not available yet. The exact address is never distributed publicly.",
|
||||||
|
"verify.title": "Checked in your browser",
|
||||||
|
"verify.intro":
|
||||||
|
"This check runs locally, not on the server, so a node cannot forge listings unnoticed.",
|
||||||
|
"verify.limit":
|
||||||
|
"Cannot be checked: whether the owner has since revoked their device. Only the network knows that; your node has the current state.",
|
||||||
|
"verify.format": "Structure of the listing",
|
||||||
|
"verify.certificate": "Owner's device certificate is valid",
|
||||||
|
"verify.binding": "Certificate belongs to this owner and device",
|
||||||
|
"verify.validity": "Time windows (certificate, listing) are right",
|
||||||
|
"verify.signature": "Signature matches the content",
|
||||||
|
"verify.pow": "Anti-spam work (proof-of-work)",
|
||||||
|
"verify.owner": "Owner (identity)",
|
||||||
|
"verify.device": "Device",
|
||||||
|
"verify.raw": "Raw data (as signed)",
|
||||||
|
"footer.text": "Allmende is free software (AGPL-3.0). There is no operator and there are no fees.",
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Key = keyof typeof de;
|
||||||
|
|
||||||
|
function detect(): "de" | "en" {
|
||||||
|
const q = new URLSearchParams(location.search).get("lang");
|
||||||
|
if (q === "de" || q === "en") return q;
|
||||||
|
return navigator.language?.toLowerCase().startsWith("de") ? "de" : "en";
|
||||||
|
}
|
||||||
|
|
||||||
|
export const lang = detect();
|
||||||
|
const dict: Record<Key, string> = lang === "de" ? de : en;
|
||||||
|
|
||||||
|
export function t(key: Key, vars: Record<string, string | number> = {}): string {
|
||||||
|
return dict[key].replace(/\{(\w+)\}/g, (_, name: string) => String(vars[name] ?? ""));
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// Canonical JSON (RFC 8785), restricted to what Allmende uses: numbers must be
|
||||||
|
// safe integers. This must produce byte-for-byte what internal/jcs produces in
|
||||||
|
// Go; test/verify.test.ts checks it against a fixture written by Go.
|
||||||
|
|
||||||
|
export function canonicalize(value: unknown): string {
|
||||||
|
if (value === null) return "null";
|
||||||
|
switch (typeof value) {
|
||||||
|
case "boolean":
|
||||||
|
return value ? "true" : "false";
|
||||||
|
case "number":
|
||||||
|
if (!Number.isSafeInteger(value)) {
|
||||||
|
throw new Error("jcs: only safe integers are supported");
|
||||||
|
}
|
||||||
|
return String(value);
|
||||||
|
case "string":
|
||||||
|
// JSON.stringify escapes exactly what RFC 8785 requires: quote,
|
||||||
|
// backslash, \b \f \n \r \t, and other control characters as \u00xx.
|
||||||
|
return JSON.stringify(value);
|
||||||
|
case "object": {
|
||||||
|
if (Array.isArray(value)) {
|
||||||
|
return "[" + value.map(canonicalize).join(",") + "]";
|
||||||
|
}
|
||||||
|
const obj = value as Record<string, unknown>;
|
||||||
|
// Default sort compares UTF-16 code units, which is what RFC 8785 wants.
|
||||||
|
const keys = Object.keys(obj).sort();
|
||||||
|
return (
|
||||||
|
"{" +
|
||||||
|
keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") +
|
||||||
|
"}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new Error("jcs: unsupported value");
|
||||||
|
}
|
||||||
|
}
|
||||||
+362
@@ -0,0 +1,362 @@
|
|||||||
|
import { getListing, getStatus, search, type Status } from "./api.ts";
|
||||||
|
import { append, clear, h } from "./dom.ts";
|
||||||
|
import { date, price, rooms, shortKey } from "./format.ts";
|
||||||
|
import { decodeGeohash } from "./geohash.ts";
|
||||||
|
import { lang, t, type Key } from "./i18n.ts";
|
||||||
|
import { verifyListing, type Listing, type Verdict } from "./verify.ts";
|
||||||
|
|
||||||
|
const PAGE = 20;
|
||||||
|
const GEOHASH_PREFIX = /^[0-9bcdefghjkmnpqrstuvwxyz]{1,6}$/;
|
||||||
|
|
||||||
|
const app = document.getElementById("app")!;
|
||||||
|
const statusEl = document.getElementById("status")!;
|
||||||
|
// Not called `status`: that would collide with the built-in window.status.
|
||||||
|
let nodeInfo: Status | null = null;
|
||||||
|
/** Bumped on every navigation so late responses for an old view are dropped. */
|
||||||
|
let generation = 0;
|
||||||
|
|
||||||
|
// --- helpers --------------------------------------------------------------
|
||||||
|
|
||||||
|
function verifyOpts() {
|
||||||
|
return { now: Math.floor(Date.now() / 1000), minPowBits: nodeInfo?.difficulty ?? 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Translates a value from a listing if it is a known one; unknown values are shown as plain text. */
|
||||||
|
function label(prefix: "kind" | "cat", value: string | undefined): string {
|
||||||
|
if (!value) return "";
|
||||||
|
const key = `${prefix}.${value}` as Key;
|
||||||
|
const known = ["kind.rent", "kind.sale", "cat.apartment", "cat.house", "cat.room", "cat.commercial"];
|
||||||
|
return known.includes(key) ? t(key) : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function where(geohash: string): string {
|
||||||
|
const a = decodeGeohash(geohash);
|
||||||
|
if (!a) return geohash;
|
||||||
|
const ns = a.lat >= 0 ? "N" : "S";
|
||||||
|
const ew = a.lon >= 0 ? (lang === "de" ? "O" : "E") : lang === "de" ? "W" : "W";
|
||||||
|
return `${Math.abs(a.lat).toFixed(2)}° ${ns}, ${Math.abs(a.lon).toFixed(2)}° ${ew}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function badge(ok: boolean): HTMLElement {
|
||||||
|
return h("span", { class: ok ? "badge ok" : "badge bad" }, (ok ? "✓ " : "✗ ") + t(ok ? "badge.ok" : "badge.bad"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(v: string | null): number {
|
||||||
|
const n = Number((v ?? "").replace(",", "."));
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Converts the human-friendly URL parameters into the API's units. */
|
||||||
|
function toApi(p: URLSearchParams): URLSearchParams {
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
for (const k of ["kind", "category", "geohash"]) {
|
||||||
|
const v = p.get(k)?.trim().toLowerCase();
|
||||||
|
if (v) q.set(k, v);
|
||||||
|
}
|
||||||
|
const eur = num(p.get("max_price"));
|
||||||
|
if (eur) q.set("max_price", String(Math.round(eur * 100)));
|
||||||
|
const area = num(p.get("min_area"));
|
||||||
|
if (area) q.set("min_area", String(Math.ceil(area)));
|
||||||
|
const r = num(p.get("min_rooms"));
|
||||||
|
if (r) q.set("min_rooms", String(Math.ceil(r * 2)));
|
||||||
|
return q;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- search view ----------------------------------------------------------
|
||||||
|
|
||||||
|
function field(text: string, input: HTMLElement, hint?: string): HTMLElement {
|
||||||
|
return h("label", { class: "field" }, h("span", { class: "field-label" }, text), input, hint && h("span", { class: "hint" }, hint));
|
||||||
|
}
|
||||||
|
|
||||||
|
function select(name: string, current: string, options: [string, string][]): HTMLSelectElement {
|
||||||
|
const el = h("select", { name });
|
||||||
|
for (const [value, text] of options) {
|
||||||
|
el.append(h("option", { value, selected: value === current }, text));
|
||||||
|
}
|
||||||
|
return el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function searchForm(params: URLSearchParams): HTMLFormElement {
|
||||||
|
const get = (k: string) => params.get(k) ?? "";
|
||||||
|
const regions = h("datalist", { id: "regions" }, ...(nodeInfo?.regions ?? []).map((r) => h("option", { value: r })));
|
||||||
|
const form = h(
|
||||||
|
"form",
|
||||||
|
{ class: "filters" },
|
||||||
|
field(t("filter.kind"), select("kind", get("kind"), [["", t("filter.any")], ["rent", t("kind.rent")], ["sale", t("kind.sale")]])),
|
||||||
|
field(
|
||||||
|
t("filter.category"),
|
||||||
|
select("category", get("category"), [
|
||||||
|
["", t("filter.any")],
|
||||||
|
["apartment", t("cat.apartment")],
|
||||||
|
["house", t("cat.house")],
|
||||||
|
["room", t("cat.room")],
|
||||||
|
["commercial", t("cat.commercial")],
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
field(
|
||||||
|
t("filter.region"),
|
||||||
|
h("input", { name: "geohash", value: get("geohash"), list: "regions", autocomplete: "off", spellcheck: "false", maxlength: 6, placeholder: nodeInfo?.regions[0] ?? "u1x" }),
|
||||||
|
t("filter.regionHint"),
|
||||||
|
),
|
||||||
|
field(t("filter.maxPrice"), h("input", { name: "max_price", type: "number", min: 0, step: 50, inputmode: "decimal", value: get("max_price") })),
|
||||||
|
field(t("filter.minArea"), h("input", { name: "min_area", type: "number", min: 0, step: 5, value: get("min_area") })),
|
||||||
|
field(t("filter.minRooms"), h("input", { name: "min_rooms", type: "number", min: 0, step: 0.5, value: get("min_rooms") })),
|
||||||
|
h(
|
||||||
|
"div",
|
||||||
|
{ class: "actions" },
|
||||||
|
h("button", { type: "submit", class: "btn primary" }, t("filter.search")),
|
||||||
|
h("button", { type: "button", class: "btn", onclick: () => navigate("#/") }, t("filter.reset")),
|
||||||
|
),
|
||||||
|
regions,
|
||||||
|
);
|
||||||
|
form.addEventListener("submit", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const q = new URLSearchParams();
|
||||||
|
for (const [k, v] of new FormData(form)) {
|
||||||
|
if (typeof v === "string" && v.trim() !== "") q.set(k, v.trim());
|
||||||
|
}
|
||||||
|
const s = q.toString();
|
||||||
|
navigate(s ? `#/?${s}` : "#/");
|
||||||
|
});
|
||||||
|
return form;
|
||||||
|
}
|
||||||
|
|
||||||
|
function navigate(hash: string): void {
|
||||||
|
if (location.hash === hash || (hash === "#/" && location.hash === "")) route();
|
||||||
|
else location.hash = hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
function card(l: Listing): HTMLElement {
|
||||||
|
const facts = [
|
||||||
|
label("cat", l.category),
|
||||||
|
l.area_m2 ? t("card.area", { n: l.area_m2 }) : "",
|
||||||
|
l.rooms_x2 ? rooms(l.rooms_x2) : "",
|
||||||
|
].filter(Boolean);
|
||||||
|
return h(
|
||||||
|
"a",
|
||||||
|
{ class: "card", href: `#/l/${l.author}/${l.id}` }, // author and id were verified to be hex
|
||||||
|
h("div", { class: "card-top" }, h("h3", null, l.title ?? ""), badge(true)),
|
||||||
|
h("p", { class: "price" }, price(l)),
|
||||||
|
h("p", { class: "facts" }, facts.join(" · ")),
|
||||||
|
h("p", { class: "muted" }, where(l.geohash)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadResults(gen: number, q: URLSearchParams, root: HTMLElement): Promise<void> {
|
||||||
|
const cards = h("div", { class: "cards" });
|
||||||
|
const foot = h("div", { class: "results-foot" });
|
||||||
|
append(root, [cards, foot]);
|
||||||
|
let offset = 0;
|
||||||
|
let shown = 0;
|
||||||
|
let hidden = 0;
|
||||||
|
|
||||||
|
const more = async (): Promise<void> => {
|
||||||
|
clear(foot);
|
||||||
|
foot.append(h("p", { class: "muted" }, t("results.loading")));
|
||||||
|
let items: unknown[];
|
||||||
|
try {
|
||||||
|
const paged = new URLSearchParams(q);
|
||||||
|
paged.set("limit", String(PAGE));
|
||||||
|
paged.set("offset", String(offset));
|
||||||
|
items = await search(paged);
|
||||||
|
} catch {
|
||||||
|
if (gen !== generation) return;
|
||||||
|
clear(foot);
|
||||||
|
foot.append(h("p", { class: "error" }, t("results.error")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (gen !== generation) return;
|
||||||
|
|
||||||
|
const opts = verifyOpts();
|
||||||
|
for (const raw of items) {
|
||||||
|
const verdict = verifyListing(raw, opts);
|
||||||
|
if (verdict.ok) {
|
||||||
|
cards.append(card(raw as Listing));
|
||||||
|
shown++;
|
||||||
|
} else {
|
||||||
|
hidden++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offset += items.length;
|
||||||
|
|
||||||
|
clear(foot);
|
||||||
|
if (hidden > 0) foot.append(h("p", { class: "warn" }, t("results.hidden", { n: hidden })));
|
||||||
|
if (shown === 0 && items.length < PAGE) foot.append(h("p", { class: "muted" }, t("results.none")));
|
||||||
|
if (items.length === PAGE) {
|
||||||
|
foot.append(h("button", { type: "button", class: "btn", onclick: () => void more() }, t("results.more")));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
await more();
|
||||||
|
}
|
||||||
|
|
||||||
|
function showSearch(params: URLSearchParams): void {
|
||||||
|
const gen = generation;
|
||||||
|
clear(app);
|
||||||
|
const results = h("div", { class: "results", "aria-live": "polite" });
|
||||||
|
app.append(h("p", { class: "tagline" }, t("app.tagline")), searchForm(params), results);
|
||||||
|
|
||||||
|
const prefix = params.get("geohash")?.trim().toLowerCase();
|
||||||
|
if (prefix && !GEOHASH_PREFIX.test(prefix)) {
|
||||||
|
results.append(h("p", { class: "error" }, t("filter.regionHint")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void loadResults(gen, toApi(params), results);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- detail view ----------------------------------------------------------
|
||||||
|
|
||||||
|
function checkList(v: Verdict): HTMLElement {
|
||||||
|
return h(
|
||||||
|
"ul",
|
||||||
|
{ class: "checks" },
|
||||||
|
...v.checks.map((c) =>
|
||||||
|
h(
|
||||||
|
"li",
|
||||||
|
{ class: c.ok ? "ok" : "bad" },
|
||||||
|
h("span", { class: "mark", "aria-hidden": "true" }, c.ok ? "✓" : "✗"),
|
||||||
|
h("span", null, t(`verify.${c.id}` as Key)),
|
||||||
|
c.info && h("span", { class: "muted info" }, c.info),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function verification(raw: unknown, l: Listing, v: Verdict): HTMLElement {
|
||||||
|
return h(
|
||||||
|
"section",
|
||||||
|
{ class: "panel" },
|
||||||
|
h("h2", null, t("verify.title")),
|
||||||
|
h("p", { class: "muted" }, t("verify.intro")),
|
||||||
|
checkList(v),
|
||||||
|
v.ok &&
|
||||||
|
h(
|
||||||
|
"dl",
|
||||||
|
{ class: "kv" },
|
||||||
|
h("dt", null, t("verify.owner")),
|
||||||
|
h("dd", { class: "mono" }, shortKey(l.author)),
|
||||||
|
h("dt", null, t("verify.device")),
|
||||||
|
h("dd", { class: "mono" }, shortKey(l.device)),
|
||||||
|
),
|
||||||
|
h("p", { class: "muted" }, t("verify.limit")),
|
||||||
|
// Never echo the content of a listing that failed verification, not even as raw data.
|
||||||
|
v.ok && h("details", null, h("summary", null, t("verify.raw")), h("pre", null, JSON.stringify(raw, null, 2))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function listingBody(l: Listing): HTMLElement[] {
|
||||||
|
const area = decodeGeohash(l.geohash);
|
||||||
|
const fact = (k: Key, v: string): Array<HTMLElement | false> =>
|
||||||
|
v ? [h("dt", null, t(k)), h("dd", null, v)] : [false];
|
||||||
|
const map =
|
||||||
|
area &&
|
||||||
|
h(
|
||||||
|
"a",
|
||||||
|
{
|
||||||
|
href: `https://www.openstreetmap.org/?mlat=${area.lat.toFixed(5)}&mlon=${area.lon.toFixed(5)}#map=14/${area.lat.toFixed(5)}/${area.lon.toFixed(5)}`,
|
||||||
|
target: "_blank",
|
||||||
|
rel: "noopener noreferrer",
|
||||||
|
},
|
||||||
|
t("detail.map"),
|
||||||
|
);
|
||||||
|
|
||||||
|
return [
|
||||||
|
h("div", { class: "detail-head" }, h("h1", null, l.title ?? ""), badge(true)),
|
||||||
|
h("p", { class: "price big" }, price(l)),
|
||||||
|
h(
|
||||||
|
"section",
|
||||||
|
{ class: "panel" },
|
||||||
|
h("h2", null, t("detail.facts")),
|
||||||
|
h(
|
||||||
|
"dl",
|
||||||
|
{ class: "kv" },
|
||||||
|
...(
|
||||||
|
[
|
||||||
|
...fact("detail.kind", label("kind", l.kind)),
|
||||||
|
...fact("detail.category", label("cat", l.category)),
|
||||||
|
...fact("detail.area", l.area_m2 ? t("card.area", { n: l.area_m2 }) : ""),
|
||||||
|
...fact("detail.rooms", l.rooms_x2 ? rooms(l.rooms_x2) : ""),
|
||||||
|
...fact("detail.published", date(l.created_at)),
|
||||||
|
...fact("detail.expires", date(l.expires_at)),
|
||||||
|
...fact("detail.version", String(l.seq)),
|
||||||
|
...fact("detail.location", where(l.geohash)),
|
||||||
|
].filter(Boolean) as HTMLElement[]
|
||||||
|
),
|
||||||
|
),
|
||||||
|
map && h("p", null, map),
|
||||||
|
),
|
||||||
|
l.description ? h("section", { class: "panel" }, h("p", { class: "desc" }, l.description)) : h("span"),
|
||||||
|
l.features?.length
|
||||||
|
? h("section", { class: "panel" }, h("h2", null, t("detail.features")), h("ul", { class: "chips" }, ...l.features.map((f) => h("li", null, f))))
|
||||||
|
: h("span"),
|
||||||
|
h("section", { class: "panel contact" }, h("h2", null, t("detail.contact")), h("p", null, t("detail.contactSoon"))),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function showDetail(author: string, id: string): Promise<void> {
|
||||||
|
const gen = generation;
|
||||||
|
clear(app);
|
||||||
|
const body = h("div", null, h("p", { class: "muted" }, t("results.loading")));
|
||||||
|
app.append(h("a", { class: "back", href: "#/" }, t("detail.back")), body);
|
||||||
|
|
||||||
|
let raw: unknown;
|
||||||
|
try {
|
||||||
|
raw = await getListing(author, id);
|
||||||
|
} catch {
|
||||||
|
if (gen !== generation) return;
|
||||||
|
clear(body);
|
||||||
|
body.append(h("p", { class: "error" }, t("results.error")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (gen !== generation) return;
|
||||||
|
clear(body);
|
||||||
|
|
||||||
|
if (raw === null) {
|
||||||
|
body.append(h("p", { class: "muted" }, t("detail.notFound")));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const l = raw as Listing;
|
||||||
|
let v = verifyListing(raw, verifyOpts());
|
||||||
|
// A gateway could answer with a different, validly signed listing.
|
||||||
|
if (v.ok && (l.author !== author || l.id !== id)) {
|
||||||
|
v = { ...v, ok: false, checks: [...v.checks, { id: "binding", ok: false, info: "not the listing that was requested" }] };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!v.ok) {
|
||||||
|
body.append(h("p", { class: "error" }, t("detail.unverified")), verification(raw, l, v));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
append(body, [...listingBody(l), verification(raw, l, v)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- boot -----------------------------------------------------------------
|
||||||
|
|
||||||
|
function route(): void {
|
||||||
|
generation++;
|
||||||
|
const hash = location.hash.replace(/^#/, "") || "/";
|
||||||
|
const q = hash.indexOf("?");
|
||||||
|
const path = q < 0 ? hash : hash.slice(0, q);
|
||||||
|
const params = new URLSearchParams(q < 0 ? "" : hash.slice(q + 1));
|
||||||
|
const m = /^\/l\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(path);
|
||||||
|
if (m) void showDetail(m[1]!, m[2]!);
|
||||||
|
else showSearch(params);
|
||||||
|
window.scrollTo(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function boot(): Promise<void> {
|
||||||
|
document.documentElement.lang = lang;
|
||||||
|
document.getElementById("foot")!.textContent = t("footer.text");
|
||||||
|
try {
|
||||||
|
nodeInfo = await getStatus();
|
||||||
|
statusEl.textContent = t("status.line", {
|
||||||
|
listings: nodeInfo.listings,
|
||||||
|
peers: nodeInfo.peers,
|
||||||
|
regions: nodeInfo.regions.join(", "),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
statusEl.textContent = t("status.unreachable");
|
||||||
|
}
|
||||||
|
window.addEventListener("hashchange", route);
|
||||||
|
route();
|
||||||
|
}
|
||||||
|
|
||||||
|
void boot();
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
// In-browser verification of a listing. The gateway that served it is not
|
||||||
|
// trusted: everything here is checked locally, mirroring Check in
|
||||||
|
// internal/listing and Cert.Check in internal/identity.
|
||||||
|
//
|
||||||
|
// What this cannot know: whether the owner has since revoked the device. Only
|
||||||
|
// nodes that saw the revocation know that, so freshness still rests on the
|
||||||
|
// gateway.
|
||||||
|
|
||||||
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
||||||
|
import { sha256 } from "@noble/hashes/sha2.js";
|
||||||
|
import { canonicalize } from "./jcs.ts";
|
||||||
|
|
||||||
|
const LISTING_CONTEXT = "allmende-listing-v1\n";
|
||||||
|
const CERT_CONTEXT = "allmende-cert-v1\n";
|
||||||
|
|
||||||
|
const DAY = 86_400;
|
||||||
|
const MAX_CERT_LIFETIME = 366 * DAY;
|
||||||
|
const MAX_LISTING_LIFETIME = 30 * DAY;
|
||||||
|
const MAX_CLOCK_SKEW = 10 * 60;
|
||||||
|
|
||||||
|
export interface Cert {
|
||||||
|
v: number;
|
||||||
|
author: string;
|
||||||
|
device: string;
|
||||||
|
issued_at: number;
|
||||||
|
expires_at: number;
|
||||||
|
sig: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Price {
|
||||||
|
amount_cents: number;
|
||||||
|
currency: string;
|
||||||
|
period: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Listing {
|
||||||
|
v: number;
|
||||||
|
id: string;
|
||||||
|
author: string;
|
||||||
|
device: string;
|
||||||
|
seq: number;
|
||||||
|
created_at: number;
|
||||||
|
expires_at: number;
|
||||||
|
tombstone?: boolean;
|
||||||
|
kind?: string;
|
||||||
|
category?: string;
|
||||||
|
geohash: string;
|
||||||
|
price?: Price;
|
||||||
|
area_m2?: number;
|
||||||
|
rooms_x2?: number;
|
||||||
|
features?: string[];
|
||||||
|
title?: string;
|
||||||
|
description?: string;
|
||||||
|
delegate?: string;
|
||||||
|
pow: number;
|
||||||
|
cert: Cert;
|
||||||
|
sig: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CheckId =
|
||||||
|
| "format"
|
||||||
|
| "certificate"
|
||||||
|
| "binding"
|
||||||
|
| "validity"
|
||||||
|
| "signature"
|
||||||
|
| "pow";
|
||||||
|
|
||||||
|
export interface Check {
|
||||||
|
id: CheckId;
|
||||||
|
ok: boolean;
|
||||||
|
/** Short technical reason; shown as-is, not translated. */
|
||||||
|
info: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Verdict {
|
||||||
|
ok: boolean;
|
||||||
|
checks: Check[];
|
||||||
|
powBits: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Options {
|
||||||
|
/** Current time in unix seconds. */
|
||||||
|
now: number;
|
||||||
|
/** Proof-of-work bits the network requires. */
|
||||||
|
minPowBits: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
|
||||||
|
function hexBytes(s: unknown, bytes: number): Uint8Array | null {
|
||||||
|
if (typeof s !== "string" || s.length !== bytes * 2 || !/^[0-9a-f]+$/.test(s)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const out = new Uint8Array(bytes);
|
||||||
|
for (let i = 0; i < bytes; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function leadingZeroBits(bytes: Uint8Array): number {
|
||||||
|
let n = 0;
|
||||||
|
for (const b of bytes) {
|
||||||
|
if (b === 0) {
|
||||||
|
n += 8;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return n + Math.clz32(b) - 24;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
function without(o: object, key: string): Record<string, unknown> {
|
||||||
|
const copy = { ...(o as Record<string, unknown>) };
|
||||||
|
delete copy[key];
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObject(v: unknown): v is Record<string, unknown> {
|
||||||
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeInt(v: unknown): v is number {
|
||||||
|
return typeof v === "number" && Number.isSafeInteger(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
function signedBy(
|
||||||
|
context: string,
|
||||||
|
signed: unknown,
|
||||||
|
sigHex: unknown,
|
||||||
|
pubHex: unknown,
|
||||||
|
): boolean {
|
||||||
|
const sig = hexBytes(sigHex, 64);
|
||||||
|
const pub = hexBytes(pubHex, 32);
|
||||||
|
if (!sig || !pub) return false;
|
||||||
|
try {
|
||||||
|
const msg = enc.encode(context + canonicalize(signed));
|
||||||
|
return ed25519.verify(sig, msg, pub);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Verifies a listing as received from a gateway. Never throws. */
|
||||||
|
export function verifyListing(input: unknown, opts: Options): Verdict {
|
||||||
|
const checks: Check[] = [];
|
||||||
|
const add = (id: CheckId, ok: boolean, info = "") => checks.push({ id, ok, info });
|
||||||
|
let powBits = 0;
|
||||||
|
|
||||||
|
const finish = (): Verdict => ({ ok: checks.every((c) => c.ok), checks, powBits });
|
||||||
|
|
||||||
|
// 1. Shape.
|
||||||
|
if (!isObject(input) || !isObject(input.cert)) {
|
||||||
|
add("format", false, "not a listing object");
|
||||||
|
return finish();
|
||||||
|
}
|
||||||
|
const l = input as unknown as Listing;
|
||||||
|
const c = l.cert;
|
||||||
|
const shapeOk =
|
||||||
|
l.v === 1 &&
|
||||||
|
hexBytes(l.id, 16) !== null &&
|
||||||
|
hexBytes(l.author, 32) !== null &&
|
||||||
|
hexBytes(l.device, 32) !== null &&
|
||||||
|
hexBytes(l.sig, 64) !== null &&
|
||||||
|
safeInt(l.seq) &&
|
||||||
|
safeInt(l.created_at) &&
|
||||||
|
safeInt(l.expires_at) &&
|
||||||
|
safeInt(l.pow) &&
|
||||||
|
typeof l.geohash === "string";
|
||||||
|
add("format", shapeOk, shapeOk ? "" : "malformed fields");
|
||||||
|
if (!shapeOk) return finish();
|
||||||
|
|
||||||
|
// 2. Certificate: signed by the identity key, sane lifetime.
|
||||||
|
const certShape =
|
||||||
|
c.v === 1 &&
|
||||||
|
hexBytes(c.author, 32) !== null &&
|
||||||
|
hexBytes(c.device, 32) !== null &&
|
||||||
|
safeInt(c.issued_at) &&
|
||||||
|
safeInt(c.expires_at) &&
|
||||||
|
c.expires_at > c.issued_at &&
|
||||||
|
c.expires_at - c.issued_at <= MAX_CERT_LIFETIME;
|
||||||
|
const certSig = certShape && signedBy(CERT_CONTEXT, without(c, "sig"), c.sig, c.author);
|
||||||
|
add(
|
||||||
|
"certificate",
|
||||||
|
certSig,
|
||||||
|
!certShape ? "malformed certificate" : certSig ? "" : "bad certificate signature",
|
||||||
|
);
|
||||||
|
if (!certSig) return finish();
|
||||||
|
|
||||||
|
// 3. The certificate must be for this author and this device.
|
||||||
|
const bound = c.author === l.author && c.device === l.device;
|
||||||
|
add("binding", bound, bound ? "" : "certificate is for a different identity or device");
|
||||||
|
|
||||||
|
// 4. Time windows.
|
||||||
|
const reasons: string[] = [];
|
||||||
|
if (!(c.issued_at <= l.created_at && l.created_at < c.expires_at)) {
|
||||||
|
reasons.push("created outside certificate validity");
|
||||||
|
}
|
||||||
|
if (opts.now >= c.expires_at) reasons.push("certificate expired");
|
||||||
|
if (l.expires_at <= l.created_at) reasons.push("expires before it was created");
|
||||||
|
if (l.expires_at - l.created_at > MAX_LISTING_LIFETIME) reasons.push("lifetime over 30 days");
|
||||||
|
if (l.created_at > opts.now + MAX_CLOCK_SKEW) reasons.push("created in the future");
|
||||||
|
if (l.expires_at <= opts.now) reasons.push("expired");
|
||||||
|
add("validity", reasons.length === 0, reasons.join("; "));
|
||||||
|
|
||||||
|
// 5. Device signature over the canonical bytes.
|
||||||
|
const unsigned = without(l, "sig");
|
||||||
|
const sigOk = signedBy(LISTING_CONTEXT, unsigned, l.sig, l.device);
|
||||||
|
add("signature", sigOk, sigOk ? "" : "signature does not match the content");
|
||||||
|
|
||||||
|
// 6. Proof-of-work over the same unsigned bytes.
|
||||||
|
try {
|
||||||
|
powBits = leadingZeroBits(sha256(enc.encode(canonicalize(unsigned))));
|
||||||
|
} catch {
|
||||||
|
powBits = 0;
|
||||||
|
}
|
||||||
|
const powOk = powBits >= opts.minPowBits;
|
||||||
|
add("pow", powOk, `${powBits} bits (network requires ${opts.minPowBits})`);
|
||||||
|
|
||||||
|
return finish();
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light dark">
|
||||||
|
<meta name="referrer" content="no-referrer">
|
||||||
|
<title>Allmende</title>
|
||||||
|
<link rel="icon" href="data:,">
|
||||||
|
<link rel="stylesheet" href="style.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header class="top">
|
||||||
|
<a class="brand" href="#/">Allmende</a>
|
||||||
|
<span id="status" class="status"></span>
|
||||||
|
</header>
|
||||||
|
<main id="app"></main>
|
||||||
|
<footer id="foot" class="foot"></footer>
|
||||||
|
<noscript><p class="error pad">Allmende braucht JavaScript, um Signaturen in deinem Browser zu prüfen. / Allmende needs JavaScript to verify signatures in your browser.</p></noscript>
|
||||||
|
<script type="module" src="app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { createServer, type Server } from "node:http";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
||||||
|
import { sha256 } from "@noble/hashes/sha2.js";
|
||||||
|
import { JSDOM, type DOMWindow } from "jsdom";
|
||||||
|
|
||||||
|
import { canonicalize } from "../src/jcs.ts";
|
||||||
|
import { leadingZeroBits, type Listing } from "../src/verify.ts";
|
||||||
|
|
||||||
|
/** The clock the browser sees in these tests (unix seconds). */
|
||||||
|
export const NOW = 1_800_000_000;
|
||||||
|
export const DIFFICULTY = 8;
|
||||||
|
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");
|
||||||
|
|
||||||
|
/** Creates a validly signed listing under a brand-new identity and device. */
|
||||||
|
export function signListing(fields: Record<string, unknown> = {}): Listing {
|
||||||
|
const idKey = ed25519.utils.randomSecretKey();
|
||||||
|
const devKey = ed25519.utils.randomSecretKey();
|
||||||
|
const cert: Record<string, unknown> = {
|
||||||
|
v: 1,
|
||||||
|
author: hex(ed25519.getPublicKey(idKey)),
|
||||||
|
device: hex(ed25519.getPublicKey(devKey)),
|
||||||
|
issued_at: NOW - 3600,
|
||||||
|
expires_at: NOW + 90 * 86_400,
|
||||||
|
};
|
||||||
|
cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey));
|
||||||
|
|
||||||
|
const l: Record<string, unknown> = {
|
||||||
|
v: 1,
|
||||||
|
id: hex(ed25519.utils.randomSecretKey()).slice(0, 32),
|
||||||
|
author: cert.author,
|
||||||
|
device: cert.device,
|
||||||
|
seq: 1,
|
||||||
|
created_at: NOW,
|
||||||
|
expires_at: NOW + 10 * 86_400,
|
||||||
|
kind: "rent",
|
||||||
|
category: "apartment",
|
||||||
|
geohash: "u1xjhx",
|
||||||
|
price: { amount_cents: 90_000, currency: "EUR", period: "month" },
|
||||||
|
area_m2: 40,
|
||||||
|
rooms_x2: 4,
|
||||||
|
title: "Wohnung",
|
||||||
|
pow: 0,
|
||||||
|
cert,
|
||||||
|
...fields,
|
||||||
|
};
|
||||||
|
for (let pow = 0; ; pow++) {
|
||||||
|
l.pow = pow;
|
||||||
|
if (leadingZeroBits(sha256(enc.encode(canonicalize(l)))) >= DIFFICULTY) break;
|
||||||
|
}
|
||||||
|
l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey));
|
||||||
|
return l as unknown as Listing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- a stand-in for a node's HTTP API -------------------------------------
|
||||||
|
|
||||||
|
export interface Gateway {
|
||||||
|
url: string;
|
||||||
|
/** Query strings of every /api/v1/listings search received. */
|
||||||
|
queries: string[];
|
||||||
|
close(): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GatewayOptions {
|
||||||
|
listings: unknown[];
|
||||||
|
/** For a requested listing id, answer with this other listing instead. */
|
||||||
|
swap?: unknown;
|
||||||
|
statusFails?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function startGateway(opts: GatewayOptions): Promise<Gateway> {
|
||||||
|
const queries: string[] = [];
|
||||||
|
const server: Server = createServer((req, res) => {
|
||||||
|
const url = new URL(req.url ?? "/", "http://x");
|
||||||
|
const json = (code: number, body: unknown) => {
|
||||||
|
res.writeHead(code, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify(body));
|
||||||
|
};
|
||||||
|
if (url.pathname === "/api/v1/status") {
|
||||||
|
if (opts.statusFails) return json(500, { error: "down" });
|
||||||
|
return json(200, {
|
||||||
|
peer_id: "12D3KooWTest",
|
||||||
|
author: "a".repeat(64),
|
||||||
|
device: "b".repeat(64),
|
||||||
|
regions: ["u1x"],
|
||||||
|
peers: 2,
|
||||||
|
listings: opts.listings.length,
|
||||||
|
difficulty: DIFFICULTY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (url.pathname === "/api/v1/listings") {
|
||||||
|
queries.push(url.search);
|
||||||
|
return json(200, opts.listings);
|
||||||
|
}
|
||||||
|
const m = /^\/api\/v1\/listings\/([0-9a-f]{64})\/([0-9a-f]{32})$/.exec(url.pathname);
|
||||||
|
if (m) {
|
||||||
|
if (opts.swap) return json(200, opts.swap);
|
||||||
|
const hit = (opts.listings as Listing[]).find((l) => l.author === m[1] && l.id === m[2]);
|
||||||
|
return hit ? json(200, hit) : json(404, { error: "not found" });
|
||||||
|
}
|
||||||
|
json(404, { error: "not found" });
|
||||||
|
});
|
||||||
|
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
|
||||||
|
const { port } = server.address() as AddressInfo;
|
||||||
|
return {
|
||||||
|
url: `http://127.0.0.1:${port}`,
|
||||||
|
queries,
|
||||||
|
close: () => new Promise((ok) => server.close(() => ok())),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- running the real built UI --------------------------------------------
|
||||||
|
|
||||||
|
export interface Page {
|
||||||
|
window: DOMWindow;
|
||||||
|
document: Document;
|
||||||
|
waitFor(pred: () => boolean, what: string, ms?: number): Promise<void>;
|
||||||
|
close(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Loads web/dist/index.html in jsdom and runs the built bundle against `gateway`. */
|
||||||
|
export function openPage(gateway: string, hash = "", lang = "en"): Page {
|
||||||
|
const dist = new URL("../dist/", import.meta.url);
|
||||||
|
const html = readFileSync(new URL("index.html", dist), "utf8");
|
||||||
|
const bundle = readFileSync(new URL("app.js", dist), "utf8");
|
||||||
|
|
||||||
|
const dom = new JSDOM(html, {
|
||||||
|
url: `${gateway}/?lang=${lang}${hash}`,
|
||||||
|
runScripts: "outside-only",
|
||||||
|
pretendToBeVisual: true,
|
||||||
|
});
|
||||||
|
const w = dom.window;
|
||||||
|
w.fetch = ((input: string | URL, init?: RequestInit) =>
|
||||||
|
fetch(new URL(String(input), gateway), init)) as unknown as typeof w.fetch;
|
||||||
|
w.scrollTo = () => {};
|
||||||
|
w.Date.now = () => NOW * 1000;
|
||||||
|
w.eval(bundle);
|
||||||
|
|
||||||
|
return {
|
||||||
|
window: w,
|
||||||
|
document: w.document,
|
||||||
|
async waitFor(pred, what, ms = 4000) {
|
||||||
|
const end = Date.now() + ms;
|
||||||
|
while (Date.now() < end) {
|
||||||
|
if (pred()) return;
|
||||||
|
await new Promise((r) => setTimeout(r, 10));
|
||||||
|
}
|
||||||
|
throw new Error(`timed out waiting for: ${what}\n${w.document.body.textContent?.slice(0, 600)}`);
|
||||||
|
},
|
||||||
|
close: () => w.close(),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
|
||||||
|
import { canonicalize } from "../src/jcs.ts";
|
||||||
|
import { decodeGeohash } from "../src/geohash.ts";
|
||||||
|
|
||||||
|
// These mirror internal/jcs/jcs_test.go.
|
||||||
|
test("canonical JSON matches the Go test vectors", () => {
|
||||||
|
const cases: [unknown, string][] = [
|
||||||
|
[{ b: 1, a: 2, c: [3, 1] }, `{"a":2,"b":1,"c":[3,1]}`],
|
||||||
|
[{ z: { y: true, x: null } }, `{"z":{"x":null,"y":true}}`],
|
||||||
|
[`<a href="x">&</a>`, `"<a href=\\"x\\">&</a>"`],
|
||||||
|
["a\tb\nc\u0001", `"a\\tb\\nc\\u0001"`],
|
||||||
|
["ä€😀
", `"ä€😀
"`],
|
||||||
|
["\u007f", `"\u007f"`],
|
||||||
|
[{ "😀": 1, "": 2 }, `{"😀":1,"":2}`], // UTF-16 order: surrogates sort first
|
||||||
|
[-42, "-42"],
|
||||||
|
];
|
||||||
|
for (const [input, want] of cases) assert.equal(canonicalize(input), want);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("floats and non-JSON values are rejected", () => {
|
||||||
|
for (const bad of [1.5, NaN, Infinity, 2 ** 60, undefined, () => 1, 10n]) {
|
||||||
|
assert.throws(() => canonicalize(bad));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("geohash decoding", () => {
|
||||||
|
const a = decodeGeohash("ezs42")!; // the classic example: 42.605, -5.603
|
||||||
|
assert.ok(Math.abs(a.lat - 42.605) < 0.03 && Math.abs(a.lon + 5.603) < 0.03);
|
||||||
|
|
||||||
|
const kiel = decodeGeohash("u1xjhx")!; // near Kiel: 54.36 N, 10.05 E
|
||||||
|
assert.ok(Math.abs(kiel.lat - 54.358) < 0.01 && Math.abs(kiel.lon - 10.047) < 0.01);
|
||||||
|
assert.ok(kiel.latErr < 0.003 && kiel.lonErr < 0.006, "precision 6 is about a kilometre");
|
||||||
|
|
||||||
|
// Hamburg (53.55 N, 9.99 E) lies inside the 3-character region cell u1x.
|
||||||
|
const region = decodeGeohash("u1x")!;
|
||||||
|
assert.ok(Math.abs(53.55 - region.lat) < region.latErr && Math.abs(9.99 - region.lon) < region.lonErr);
|
||||||
|
|
||||||
|
assert.equal(decodeGeohash("u1xja"), null, "'a' is not in the geohash alphabet");
|
||||||
|
});
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { after, before, test } from "node:test";
|
||||||
|
|
||||||
|
import type { Listing } from "../src/verify.ts";
|
||||||
|
import { DIFFICULTY, openPage, signListing, startGateway, type Gateway } from "./helpers.ts";
|
||||||
|
|
||||||
|
// Produced by the Go implementation; verifies at NOW-equivalent time.
|
||||||
|
const fixture = JSON.parse(
|
||||||
|
readFileSync(new URL("../../internal/listing/testdata/fixture.json", import.meta.url), "utf8"),
|
||||||
|
) as { listing: Listing };
|
||||||
|
const goSigned = fixture.listing;
|
||||||
|
|
||||||
|
const XSS_TITLE = `<img src=x onerror="window.__pwned=1">Haus`;
|
||||||
|
const XSS_DESC = `<script>window.__pwned=2</script>\nZweite Zeile`;
|
||||||
|
|
||||||
|
const tampered = { ...structuredClone(goSigned), id: "ff".repeat(16) } as Listing;
|
||||||
|
tampered.title = "Gefälschter Titel";
|
||||||
|
const hostile = signListing({ title: XSS_TITLE, description: XSS_DESC, features: ["<b>fett</b>"] });
|
||||||
|
|
||||||
|
let gw: Gateway;
|
||||||
|
before(async () => {
|
||||||
|
gw = await startGateway({ listings: [goSigned, tampered, hostile] });
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
await gw.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
const cardTitles = (doc: Document) =>
|
||||||
|
[...doc.querySelectorAll(".card h3")].map((e) => e.textContent);
|
||||||
|
|
||||||
|
test("search shows verified listings and hides forged ones", async () => {
|
||||||
|
const page = openPage(gw.url);
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => page.document.querySelectorAll(".card").length === 2, "two cards");
|
||||||
|
const titles = cardTitles(page.document);
|
||||||
|
assert.ok(titles.includes(goSigned.title!), "the Go-signed listing is shown");
|
||||||
|
assert.ok(!titles.includes("Gefälschter Titel"), "the forged listing must not be shown");
|
||||||
|
assert.match(page.document.querySelector(".warn")!.textContent!, /1 result\(s\) hidden/);
|
||||||
|
assert.match(page.document.querySelector(".card .badge.ok")!.textContent!, /Signature verified/);
|
||||||
|
assert.match(page.document.body.textContent!, /€1,234\.50 \/ month/);
|
||||||
|
assert.match(page.document.getElementById("status")!.textContent!, /2 connected nodes/);
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hostile listing text is rendered as text, never as HTML", async () => {
|
||||||
|
const page = openPage(gw.url);
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => page.document.querySelectorAll(".card").length === 2, "cards");
|
||||||
|
const titles = cardTitles(page.document);
|
||||||
|
assert.ok(titles.includes(XSS_TITLE), "the markup is shown literally");
|
||||||
|
assert.equal(page.document.querySelector("img"), null, "no <img> may be created from listing text");
|
||||||
|
assert.equal((page.window as unknown as { __pwned?: number }).__pwned, undefined);
|
||||||
|
|
||||||
|
page.window.location.hash = `#/l/${hostile.author}/${hostile.id}`;
|
||||||
|
await page.waitFor(() => page.document.querySelector("h1") !== null, "detail view");
|
||||||
|
assert.equal(page.document.querySelector("h1")!.textContent, XSS_TITLE);
|
||||||
|
assert.equal(page.document.querySelector("img"), null);
|
||||||
|
assert.equal(page.document.querySelectorAll("main script").length, 0);
|
||||||
|
assert.equal(page.document.querySelector(".chips b"), null, "feature markup must stay text");
|
||||||
|
assert.equal(page.document.querySelector(".desc")!.textContent, XSS_DESC);
|
||||||
|
assert.equal((page.window as unknown as { __pwned?: number }).__pwned, undefined);
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("detail view shows the content and a passing verification report", async () => {
|
||||||
|
const page = openPage(gw.url, `#/l/${goSigned.author}/${goSigned.id}`);
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => page.document.querySelector("h1") !== null, "detail");
|
||||||
|
const text = page.document.body.textContent!;
|
||||||
|
assert.equal(page.document.querySelector("h1")!.textContent, goSigned.title);
|
||||||
|
assert.ok(text.includes("Zeile 2 – Überraschung \u{1F3E0}"), "unicode survives");
|
||||||
|
assert.equal(page.document.querySelector(".desc")!.textContent, goSigned.description);
|
||||||
|
assert.equal(page.document.querySelectorAll(".checks li.ok").length, 6);
|
||||||
|
assert.equal(page.document.querySelectorAll(".checks li.bad").length, 0);
|
||||||
|
assert.ok(page.document.querySelector("a[href^='https://www.openstreetmap.org/']")!.getAttribute("rel")!.includes("noopener"));
|
||||||
|
assert.match(text, /not available yet/);
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("detail view refuses to show a forged listing", async () => {
|
||||||
|
const page = openPage(gw.url, `#/l/${tampered.author}/${tampered.id}`);
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => page.document.querySelector("#app .error") !== null, "warning");
|
||||||
|
const text = page.document.body.textContent!;
|
||||||
|
assert.match(text, /could not be verified/);
|
||||||
|
assert.ok(!text.includes("Gefälschter Titel"), "forged content must not be displayed");
|
||||||
|
assert.equal(page.document.querySelector("h1"), null);
|
||||||
|
assert.ok(page.document.querySelectorAll(".checks li.bad").length >= 1);
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a gateway answering with a different valid listing is caught", async () => {
|
||||||
|
const other = signListing({ title: "Andere Anzeige" });
|
||||||
|
const liar = await startGateway({ listings: [], swap: other });
|
||||||
|
try {
|
||||||
|
// Ask for goSigned, but the gateway returns `other`, which is validly signed.
|
||||||
|
const page = openPage(liar.url, `#/l/${goSigned.author}/${goSigned.id}`);
|
||||||
|
await page.waitFor(() => page.document.querySelector("#app .error") !== null, "warning");
|
||||||
|
assert.match(page.document.body.textContent!, /could not be verified/);
|
||||||
|
assert.ok(!page.document.body.textContent!.includes("Andere Anzeige"));
|
||||||
|
page.close();
|
||||||
|
} finally {
|
||||||
|
await liar.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a missing listing says so", async () => {
|
||||||
|
const page = openPage(gw.url, `#/l/${"a".repeat(64)}/${"b".repeat(32)}`);
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => /does not exist/.test(page.document.body.textContent!), "not found text");
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("filters are translated into the API's units", async () => {
|
||||||
|
const page = openPage(gw.url);
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => page.document.querySelectorAll(".card").length > 0, "initial results");
|
||||||
|
const set = (name: string, value: string) =>
|
||||||
|
((page.document.querySelector(`[name=${name}]`) as HTMLInputElement).value = value);
|
||||||
|
set("kind", "rent");
|
||||||
|
set("geohash", "U1X");
|
||||||
|
set("max_price", "1000");
|
||||||
|
set("min_area", "42.5");
|
||||||
|
set("min_rooms", "2.5"); // browsers normalise a typed "2,5" to this for type=number
|
||||||
|
gw.queries.length = 0;
|
||||||
|
page.document.querySelector("form")!.dispatchEvent(new page.window.Event("submit", { cancelable: true }));
|
||||||
|
await page.waitFor(() => gw.queries.length > 0, "a search request");
|
||||||
|
|
||||||
|
const q = new URLSearchParams(gw.queries.at(-1));
|
||||||
|
assert.equal(q.get("kind"), "rent");
|
||||||
|
assert.equal(q.get("geohash"), "u1x", "lower-cased");
|
||||||
|
assert.equal(q.get("max_price"), "100000", "euros become cents");
|
||||||
|
assert.equal(q.get("min_area"), "43", "rounded up");
|
||||||
|
assert.equal(q.get("min_rooms"), "5", "2.5 rooms is stored as 5");
|
||||||
|
assert.equal(q.get("limit"), "20");
|
||||||
|
assert.match(page.window.location.hash, /geohash=U1X|geohash=u1x/i);
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an invalid area is reported without calling the API", async () => {
|
||||||
|
const before = gw.queries.length;
|
||||||
|
const page = openPage(gw.url, "#/?geohash=u1xa'%20OR%201=1");
|
||||||
|
try {
|
||||||
|
await page.waitFor(() => page.document.querySelector("#app .error") !== null, "hint");
|
||||||
|
assert.equal(gw.queries.length, before, "no request should be sent for an invalid prefix");
|
||||||
|
} finally {
|
||||||
|
page.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the page still works when the node's status is unavailable", async () => {
|
||||||
|
const down = await startGateway({ listings: [goSigned], statusFails: true });
|
||||||
|
try {
|
||||||
|
const page = openPage(down.url, "", "de");
|
||||||
|
await page.waitFor(() => /nicht erreichbar/.test(page.document.getElementById("status")!.textContent!), "status error (German)");
|
||||||
|
// With no difficulty known the verifier still checks everything else.
|
||||||
|
await page.waitFor(() => page.document.querySelectorAll(".card").length === 1, "card");
|
||||||
|
assert.match(page.document.querySelector(".badge")!.textContent!, /Signatur geprüft/);
|
||||||
|
assert.equal(page.document.documentElement.lang, "de");
|
||||||
|
page.close();
|
||||||
|
} finally {
|
||||||
|
await down.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the difficulty reported by the node is enforced as a minimum", async () => {
|
||||||
|
// A listing without any proof-of-work, from a gateway claiming difficulty 8.
|
||||||
|
const lazy = signListing({ title: "Ohne Arbeit" });
|
||||||
|
const weak = structuredClone(lazy);
|
||||||
|
assert.ok(DIFFICULTY > 0);
|
||||||
|
// Re-signing is impossible here, so simply check the real one passes and a forged PoW fails.
|
||||||
|
weak.pow += 1;
|
||||||
|
const g = await startGateway({ listings: [lazy, weak] });
|
||||||
|
try {
|
||||||
|
const page = openPage(g.url);
|
||||||
|
await page.waitFor(() => page.document.querySelectorAll(".card").length >= 1, "cards");
|
||||||
|
assert.equal(page.document.querySelectorAll(".card").length, 1, "the altered one is hidden");
|
||||||
|
page.close();
|
||||||
|
} finally {
|
||||||
|
await g.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
||||||
|
|
||||||
|
import { canonicalize } from "../src/jcs.ts";
|
||||||
|
import { verifyListing, type Listing } from "../src/verify.ts";
|
||||||
|
|
||||||
|
// Written by the Go implementation (internal/listing/fixture_test.go).
|
||||||
|
const fixture = JSON.parse(
|
||||||
|
readFileSync(new URL("../../internal/listing/testdata/fixture.json", import.meta.url), "utf8"),
|
||||||
|
) as { now: number; difficulty: number; canonical: string; listing: Listing };
|
||||||
|
|
||||||
|
const opts = { now: fixture.now, minPowBits: fixture.difficulty };
|
||||||
|
const fresh = (): Listing => structuredClone(fixture.listing);
|
||||||
|
const failing = (l: unknown, o = opts) =>
|
||||||
|
verifyListing(l, o).checks.filter((c) => !c.ok).map((c) => c.id);
|
||||||
|
|
||||||
|
test("canonicalization is byte-identical to Go", () => {
|
||||||
|
assert.equal(canonicalize(fixture.listing), fixture.canonical);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a listing signed by Go verifies in the browser", () => {
|
||||||
|
const v = verifyListing(fixture.listing, opts);
|
||||||
|
assert.deepEqual(failing(fixture.listing), []);
|
||||||
|
assert.equal(v.ok, true);
|
||||||
|
assert.ok(v.powBits >= fixture.difficulty);
|
||||||
|
assert.equal(v.checks.length, 6);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tampering with any signed field is detected", () => {
|
||||||
|
const edits: Record<string, (l: Listing) => void> = {
|
||||||
|
price: (l) => (l.price!.amount_cents = 1),
|
||||||
|
title: (l) => (l.title = "Betrug"),
|
||||||
|
description: (l) => (l.description += "!"),
|
||||||
|
geohash: (l) => (l.geohash = "u30000"),
|
||||||
|
seq: (l) => (l.seq += 1),
|
||||||
|
expires_at: (l) => (l.expires_at += 1),
|
||||||
|
feature: (l) => l.features!.push("pool"),
|
||||||
|
};
|
||||||
|
for (const [name, edit] of Object.entries(edits)) {
|
||||||
|
const l = fresh();
|
||||||
|
edit(l);
|
||||||
|
assert.ok(failing(l).includes("signature"), `${name} change not detected`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tampering with the certificate is detected", () => {
|
||||||
|
const l = fresh();
|
||||||
|
l.cert.expires_at += 86_400;
|
||||||
|
assert.deepEqual(failing(l), ["certificate"]);
|
||||||
|
|
||||||
|
const m = fresh();
|
||||||
|
m.cert.device = "00".repeat(32);
|
||||||
|
assert.ok(failing(m).includes("certificate"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a certificate for another identity or device is rejected", () => {
|
||||||
|
const l = fresh();
|
||||||
|
l.author = "ab".repeat(32);
|
||||||
|
assert.ok(failing(l).includes("binding"));
|
||||||
|
assert.ok(failing(l).includes("signature"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a self-signed listing from a new identity is internally consistent", () => {
|
||||||
|
// Verification proves integrity and the identity -> device chain. It does
|
||||||
|
// not make an unknown identity trustworthy; that is a separate question.
|
||||||
|
const idKey = ed25519.utils.randomSecretKey();
|
||||||
|
const devKey = ed25519.utils.randomSecretKey();
|
||||||
|
const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
|
||||||
|
const cert: Record<string, unknown> = {
|
||||||
|
v: 1,
|
||||||
|
author: hex(ed25519.getPublicKey(idKey)),
|
||||||
|
device: hex(ed25519.getPublicKey(devKey)),
|
||||||
|
issued_at: fixture.now - 3600,
|
||||||
|
expires_at: fixture.now + 30 * 86_400,
|
||||||
|
};
|
||||||
|
cert.sig = hex(ed25519.sign(enc.encode("allmende-cert-v1\n" + canonicalize(cert)), idKey));
|
||||||
|
|
||||||
|
const l: Record<string, unknown> = {
|
||||||
|
v: 1,
|
||||||
|
id: "11".repeat(16),
|
||||||
|
author: cert.author,
|
||||||
|
device: cert.device,
|
||||||
|
seq: 1,
|
||||||
|
created_at: fixture.now,
|
||||||
|
expires_at: fixture.now + 86_400,
|
||||||
|
geohash: "u1xjhx",
|
||||||
|
pow: 0,
|
||||||
|
cert,
|
||||||
|
};
|
||||||
|
// Mine a little proof-of-work so it also passes the PoW check.
|
||||||
|
for (let pow = 0; ; pow++) {
|
||||||
|
l.pow = pow;
|
||||||
|
const v = verifyListing({ ...l, sig: "00".repeat(64) }, { ...opts, minPowBits: 8 });
|
||||||
|
if (v.powBits >= 8) break;
|
||||||
|
}
|
||||||
|
l.sig = hex(ed25519.sign(enc.encode("allmende-listing-v1\n" + canonicalize(l)), devKey));
|
||||||
|
|
||||||
|
assert.deepEqual(failing(l, { ...opts, minPowBits: 8 }), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a signature made for another purpose does not verify (domain separation)", () => {
|
||||||
|
// Sign the listing bytes with the certificate context instead of the listing one.
|
||||||
|
const l = fresh();
|
||||||
|
assert.ok(failing({ ...l, sig: l.cert.sig }).includes("signature"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("time windows", () => {
|
||||||
|
const day = 86_400;
|
||||||
|
assert.ok(failing(fixture.listing, { ...opts, now: fixture.now + 20 * day }).includes("validity"), "expired listing");
|
||||||
|
assert.ok(failing(fixture.listing, { ...opts, now: fixture.now - 3600 }).includes("validity"), "created in the future");
|
||||||
|
assert.ok(failing(fixture.listing, { ...opts, now: fixture.listing.cert.expires_at + 1 }).includes("validity"), "expired certificate");
|
||||||
|
|
||||||
|
const l = fresh();
|
||||||
|
l.created_at = l.cert.issued_at - 10; // before the certificate existed
|
||||||
|
assert.ok(failing(l).includes("validity"));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("insufficient proof-of-work is reported", () => {
|
||||||
|
const v = verifyListing(fixture.listing, { ...opts, minPowBits: 40 });
|
||||||
|
assert.deepEqual(
|
||||||
|
v.checks.filter((c) => !c.ok).map((c) => c.id),
|
||||||
|
["pow"],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("garbage never throws and never verifies", () => {
|
||||||
|
for (const junk of [null, undefined, 5, "x", [], {}, { cert: 5 }, { cert: {} }, { v: 1, cert: [] }]) {
|
||||||
|
assert.equal(verifyListing(junk, opts).ok, false);
|
||||||
|
}
|
||||||
|
const floaty = fresh();
|
||||||
|
floaty.price!.amount_cents = 1.5;
|
||||||
|
assert.equal(verifyListing(floaty, opts).ok, false);
|
||||||
|
});
|
||||||
@@ -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"]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user