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:
+32
-1
@@ -22,6 +22,7 @@ import (
|
||||
"git.stinnesbeck.com/nils/allmende/internal/listing"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/p2p"
|
||||
"git.stinnesbeck.com/nils/allmende/internal/store"
|
||||
"git.stinnesbeck.com/nils/allmende/web"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -57,7 +58,35 @@ func New(cfg Config) http.Handler {
|
||||
mux.HandleFunc("POST /api/v1/listings", s.admin(s.create))
|
||||
mux.HandleFunc("PUT /api/v1/listings/{id}", s.admin(s.update))
|
||||
mux.HandleFunc("DELETE /api/v1/listings/{id}", s.admin(s.remove))
|
||||
return mux
|
||||
mux.Handle("GET /", s.ui())
|
||||
return secure(mux)
|
||||
}
|
||||
|
||||
// contentSecurityPolicy lets the UI load only its own script and styles and
|
||||
// talk only to its own node. Listing text comes from strangers; the UI never
|
||||
// inserts it as HTML, and this policy is the second line of defence.
|
||||
const contentSecurityPolicy = "default-src 'none'; script-src 'self'; style-src 'self'; " +
|
||||
"img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"
|
||||
|
||||
// ui serves the embedded browser UI.
|
||||
func (s *server) ui() http.Handler {
|
||||
files := http.FileServerFS(web.Files())
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Security-Policy", contentSecurityPolicy)
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
h.Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
h.Set("Cache-Control", "no-cache") // revalidate, so upgrades reach users
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// secure adds headers every response should carry.
|
||||
func secure(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// --- reading --------------------------------------------------------------
|
||||
@@ -76,6 +105,8 @@ func (s *server) status(w http.ResponseWriter, r *http.Request) {
|
||||
"regions": s.Regions,
|
||||
"peers": s.Node.PeerCount(),
|
||||
"listings": n,
|
||||
// Lets the browser report how much anti-spam work a listing carries.
|
||||
"difficulty": s.Difficulty,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
f := newFixture(t, token)
|
||||
code, body := f.do(t, "GET", "/api/v1/status", "", false)
|
||||
|
||||
@@ -27,6 +27,15 @@ func Generate() (*Identity, error) {
|
||||
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.
|
||||
func Load(path string) (*Identity, error) {
|
||||
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"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user