diff --git a/.ciagent/CHECKPOINT.json b/.ciagent/CHECKPOINT.json index 85620cc..0e5acaa 100644 --- a/.ciagent/CHECKPOINT.json +++ b/.ciagent/CHECKPOINT.json @@ -1,14 +1,13 @@ { - "phase": 0, + "phase": 1, "stage": "complete", "milestone": "v0.6", "milestone_type": "feature", "tag_base": "v0.5.x", - "phase_role": "pre_execution", + "phase_role": "execution", "project": "oy", "attempts": 0, - "updated_at": "2026-08-18T12:12:00Z", + "updated_at": "2026-08-18T13:55:00Z", "milestone_complete": false, - "milestone_release_tag": "v0.5.0", - "release_id": 770 + "requirements_covered": ["REQ-040", "REQ-045"] } \ No newline at end of file diff --git a/README.md b/README.md index a2fadd0..287e226 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,14 @@ Loaf → Batch → Cake → Bakery → Granary → Mill → Harvest → Earth.** ## Status -**v0.3 (Bearers & Documentation) — in progress.** The codebase is a skeleton + -tests layer (Go types + keeper stubs + invariant tests, zero external Go deps) -matching the v0.1/v0.2 pre-MVP pattern. See `.ciagent/oy/ROADMAP.md` for the -phase plan and `.ciagent/oy/PROJECT.md` for governance. +**v0.6 (Nomad Web UI) — in progress.** v0.5 shipped the Bearers Runtime +(simtest-grade keeper handlers for 8 x/ modules). v0.6 adds the project's +first UI: a Go `html/template` + HTMX prototype Web UI in `web/` where a +visitor can sign up to be a Nomad (create a Reach + open a Stash) and +exercise basic functionality around Reach, Stash, Window, Standing, and +Bloom. All data is generated test fixtures — no real chain. See +`.ciagent/oy/ROADMAP.md` for the phase plan and `.ciagent/oy/PROJECT.md` +for governance. ## Build & test @@ -40,6 +44,29 @@ go build ./... go test ./... ``` +## Web UI + +The Nomad Web UI (v0.6) is a Go `html/template` server with HTMX progressive +enhancement, served by a mock HTTP server in `web/` that instantiates the +real `x/*/types` structs from in-memory fixtures. No node, no build step, +no real chain. To run it: + +```sh +go run ./web +# opens on http://localhost:8080 (PORT env var overridable) +``` + +Five screens, all reachable from the home nav: + +- `/reach` — create a Reach (sign up to be a Nomad) + Reach list/detail +- `/stash/{holderID}` — Stash dashboard (Grain balance + Bread scale + 90-day maturity) +- `/window` — Window authorization (open/lifecycle/audit log) +- `/standing/{reachID}` — Standing + Freeholder signals progress +- `/bloom/{stashID}` — Bloom accrual view + +HTMX is a single vendored JS file (`web/static/htmx.min.js`), NOT a Go +dependency — `go.mod` stays unchanged (G-006). + ## Docs The docs site is [MkDocs Material](https://squidfunk.github.io/mkdocs-material/) @@ -58,17 +85,19 @@ deferred to v0.4 (D-046); v0.3 ships the source. ## Lexicon firewall OpenYield bans 10 financial terms as standalone words (REQ-012) across all Go -source (`x/**/*.go`) and all docs (`README.md` + `docs/**/*.md`). The banned -terms are the words you would expect a legacy financial institution to use; -this README and the docs describe them only by their **safe replacements**, so -the firewall itself never trips. The firewall is enforced in code by two -sibling Go tests: +source (`x/**/*.go`), all docs (`README.md` + `docs/**/*.md`), and all web UI +files (`web/**/*.{html,js,go}`). The banned terms are the words you would +expect a legacy financial institution to use; this README and the docs describe +them only by their **safe replacements**, so the firewall itself never trips. +The firewall is enforced in code by three sibling Go tests: - `lexicon_meta_test.go` (v0.2) — scans `x/**/*.go`. - `lexicon_meta_docs/lexicon_meta_docs_test.go` (v0.3) — scans `README.md` + `docs/**/*.md`. +- `lexicon_meta_web/lexicon_meta_web_test.go` (v0.6) — scans + `web/templates/**` + `web/static/**` + `web/**/*.go`. -Both use `lexicon.FindBannedTerm` (word-boundary, case-insensitive), so +All three use `lexicon.FindBannedTerm` (word-boundary, case-insensitive), so "OpenYield" is safe (word-boundary does not match the banned term inside an identifier) but the standalone banned term is not — docs say **"real production"** / **"real return"**, and a Holder's identity is **Holder** / diff --git a/lexicon_meta_web/lexicon_meta_web_test.go b/lexicon_meta_web/lexicon_meta_web_test.go new file mode 100644 index 0000000..dfd9357 --- /dev/null +++ b/lexicon_meta_web/lexicon_meta_web_test.go @@ -0,0 +1,307 @@ +// Package lexicon_meta_web holds the web lexicon firewall (REQ-045, D-069). +// +// It is a NEW sibling meta-test created in v0.6 P1 Wave 1 that MIRRORS the +// v0.3 docs firewall (lexicon_meta_docs/lexicon_meta_docs_test.go, package +// lexicon_meta_docs) but scans the web surface (web/templates/**/*.html + +// web/static/**/*.js + web/**/*.go) instead of README.md + docs/**/*.md. It +// uses the SAME lexicon.FindBannedTerm (word-boundary, case-insensitive) — +// NO detection reimplementation — so the three firewalls (x/*.go, docs, web) +// share a single source of truth for the 10 banned terms (bank, deposit, +// interest, yield, currency, dollar, euro, account, savings, depositor). +// +// Placement: this file lives in lexicon_meta_web/ (a subdirectory of the +// repo root) because Go does not permit two distinct packages in the same +// directory; the v0.2 firewall is package lexicon_meta at the repo root and +// the v0.3 firewall is package lexicon_meta_docs in lexicon_meta_docs/. The +// invocation `go test ./lexicon_meta_web/...` (PLANS P1-01-01) resolves to +// this package. Run via `go test ./...` from the repo root as well. +// +// G-013 walk-coverage: TestLexiconMetaWebWalkCoverage injects a synthetic +// banned-term .html into a temp web/templates/ subtree and asserts the walk +// FINDS it. This closes the "silently scans nothing and reports green" +// failure mode that the G-009 self-test table (detection) alone does not +// cover. +// +// G-014 self-test drift: the self-test table and banned-term count assertion +// reuse lexicon.BannedTerms() (the single source). A cross-reference comment +// keeps this file's table in lockstep with lexicon_meta_test.go's table and +// lexicon_meta_docs_test.go's table; if a banned term is added, all three +// firewalls update from one place. +package lexicon_meta_web + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/oy/openyield/lexicon" +) + +// repoRoot returns the absolute path to the repo root by walking up from +// this test file (the test lives at /lexicon_meta_web/). +func repoRoot(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("runtime.Caller failed") + } + // file = .../oy/lexicon_meta_web/lexicon_meta_web_test.go + // repo root = filepath.Dir(filepath.Dir(file)) + return filepath.Dir(filepath.Dir(file)) +} + +// thisFile returns the absolute path of this meta-test file (to exclude it +// from its own scan — it references banned terms via the lexicon package, +// whose source assembles terms from fragments, so no banned-term literal +// appears in the firewall's own code). +func thisFile(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("runtime.Caller failed") + } + return file +} + +// isWebTarget reports whether path (relative to repo root) is a file the web +// firewall scans: web/templates/**/*.html, web/static/**/*.js, and +// web/**/*.go (production + test). Non-{html,js,go} files under web/ (e.g. +// vendored binary assets) are skipped. +func isWebTarget(rel string) bool { + if !strings.HasPrefix(rel, "web"+string(filepath.Separator)) { + return false + } + return strings.HasSuffix(rel, ".html") || strings.HasSuffix(rel, ".js") || strings.HasSuffix(rel, ".go") +} + +// TestLexiconMetaWebNoBannedTermsInWeb is the web firewall (D-069). It walks +// the repo root, targets web/templates/**/*.html + web/static/**/*.js + +// web/**/*.go (production + test), reads each file's source, and asserts no +// banned term is present (word-boundary, case-insensitive). Excludes +// .ciagent/ (firewall meta-files discuss banned terms by name for +// governance; not user-facing), .git/ (VCS), and this test file itself +// (self-exclusion via runtime.Caller(0)). +// +// Passes at P1 Wave 1 with zero web content (a walk that scans nothing +// reports green on zero hits — closed by TestLexiconMetaWebWalkCoverage +// below). With the Wave 2..4 web content present (templates, static assets, +// handlers, store), all are lexicon-clean by construction. +func TestLexiconMetaWebNoBannedTermsInWeb(t *testing.T) { + root := repoRoot(t) + this := thisFile(t) + hits := []string{} + err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() { + base := filepath.Base(path) + if base == ".ciagent" || base == ".git" { + return filepath.SkipDir + } + return nil + } + // Self-exclusion: skip this meta-test file. + if path == this { + return nil + } + rel, rerr := filepath.Rel(root, path) + if rerr != nil { + return rerr + } + if !isWebTarget(rel) { + return nil + } + bz, rerr := os.ReadFile(path) + if rerr != nil { + return rerr + } + if found, ok := lexicon.FindBannedTerm(string(bz)); ok { + hits = append(hits, rel+" contains banned term "+found) + } + return nil + }) + if err != nil { + t.Fatalf("walk: %v", err) + } + if len(hits) > 0 { + t.Errorf("REQ-045 web lexicon firewall violations:\n %s", + strings.Join(hits, "\n ")) + } +} + +// TestLexiconMetaWebSelfTestTable (G-009 for web) is the firewall's own +// detection-coverage guard. Each synthetic string embeds exactly one banned +// term in a plausible sentence context and is asserted to trigger detection, +// so the firewall's detection logic is durably verified — if detection ever +// breaks, this test fails before the firewall silently passes a real +// violation in a web template or handler. +// +// REQ-029 (GRILL G-014): the synthetic strings are sourced from +// lexicon.SyntheticBannedStrings(), the single source of truth shared with +// lexicon_meta_test.go :: TestLexiconMetaSelfTestTable and +// lexicon_meta_docs_test.go :: TestLexiconMetaDocsSelfTestTable. Before +// REQ-029, each meta-test DUPLICATED its own 10-string table (byte-identical), +// creating a drift risk; the shared helper closes it. This file no longer +// builds its own synthetic table — all three meta-tests consume the same +// helper, so a future banned-term addition updates all firewalls from one +// place. +func TestLexiconMetaWebSelfTestTable(t *testing.T) { + terms := lexicon.BannedTerms() + // The spec lists 10 banned terms (plan docs say "9", counting dollar/euro + // as a pair): bank, deposit, interest, yield, currency, dollar, euro, + // account, savings, depositor. + if len(terms) != 10 { + t.Fatalf("BannedTerms() len = %d, want 10", len(terms)) + } + // REQ-029: consume the shared synthetic-string helper (G-014 single source). + synthetic := lexicon.SyntheticBannedStrings() + if len(synthetic) != len(terms) { + t.Fatalf("SyntheticBannedStrings() len = %d, want %d (must match BannedTerms())", len(synthetic), len(terms)) + } + for i, s := range synthetic { + found, ok := lexicon.FindBannedTerm(s) + if !ok { + t.Errorf("G-009 web self-test [%d]: synthetic string did not trigger detection: %q", i, s) + continue + } + if found != terms[i] { + t.Errorf("G-009 web self-test [%d]: detected %q, want %q (in %q)", i, found, terms[i], s) + } + } +} + +// TestLexiconMetaWebBannedTermsCount asserts exactly 10 banned terms are +// configured (locked-const for the firewall's scope; spec lists 10, plan docs +// say "9" counting dollar/euro as a pair). Derived from lexicon.BannedTerms() +// — the single source — so a count change breaks all three firewalls (x/*.go, +// docs, web) (G-014 drift prevention). +func TestLexiconMetaWebBannedTermsCount(t *testing.T) { + terms := lexicon.BannedTerms() + if len(terms) != 10 { + t.Errorf("BannedTerms() len = %d, want 10 (REQ-012/REQ-045)", len(terms)) + } + seen := map[string]bool{} + for _, tr := range terms { + if seen[tr] { + t.Errorf("duplicate banned term %q", tr) + } + seen[tr] = true + } +} + +// TestLexiconMetaWebNoFalsePositiveOnOpenYield asserts the module name +// "openyield" does NOT trigger the "yield" banned term and "european" does +// NOT trigger the "euro" banned term (word-boundary matching must not match +// substrings of identifiers). This is the regression firewall for the +// word-boundary detection design — mirrors the v0.2 +// TestLexiconMetaNoFalsePositiveOnOpenYield and the v0.3 +// TestLexiconMetaDocsNoFalsePositiveOnOpenYield. +func TestLexiconMetaWebNoFalsePositiveOnOpenYield(t *testing.T) { + cases := []string{ + "github.com/oy/openyield/x/window/types", + "package openyield", + "openyield is the module", + "european resident", + "# OpenYield web", + "the OpenYield mesh", + } + for _, s := range cases { + if _, ok := lexicon.FindBannedTerm(s); ok { + t.Errorf("false positive: %q triggered a banned term (word-boundary must avoid this)", s) + } + } +} + +// TestLexiconMetaWebWalkCoverage (G-013) is the walk-coverage firewall. The +// G-009 self-test table (above) verifies DETECTION (FindBannedTerm on +// synthetic strings) but NOT the WALK (which files are scanned). A walk bug +// — e.g. wrong path prefix, missing web/ recursion, a typo in the .html +// suffix check — would silently scan nothing and report green on zero +// files. This test closes that gap by injecting a synthetic banned-term +// .html into a fixture dir under the real web/templates/ path the walk scans +// and asserting the walk FINDS it. +// +// The fixture is created under web/templates/.lexicon_fixture/ (a real +// web/templates/ subtree the walk reaches) and removed via defer so it never +// leaks into the repo. If the walk logic misses the fixture, this test fails +// loudly instead of letting a broken walk pass the firewall green on zero +// files scanned. +func TestLexiconMetaWebWalkCoverage(t *testing.T) { + root := repoRoot(t) + this := thisFile(t) + + // Build a synthetic banned term from fragments so THIS file does not + // contain a banned-term literal (it is excluded from its own scan, but + // the synthetic stays clean for readability/searchability). + terms := lexicon.BannedTerms() + if len(terms) == 0 { + t.Fatal("BannedTerms() returned no terms — cannot run walk-coverage") + } + // Use the first banned term ("bank") assembled from two halves. + syntheticTerm := terms[0][:2] + terms[0][2:] // reassemble (no literal in source) + badContent := []byte("\nthis file contains a banned term: " + syntheticTerm + "\n") + + fixtureDir := filepath.Join(root, "web", "templates", ".lexicon_fixture") + fixtureFile := filepath.Join(fixtureDir, "bad_fixture.html") + if err := os.MkdirAll(fixtureDir, 0o755); err != nil { + t.Fatalf("mkdir fixture: %v", err) + } + defer os.RemoveAll(fixtureDir) + if err := os.WriteFile(fixtureFile, badContent, 0o644); err != nil { + t.Fatalf("write fixture: %v", err) + } + + // Run the SAME walk logic as TestLexiconMetaWebNoBannedTermsInWeb and + // assert it FINDS the fixture's banned term. A walk that returns zero + // hits here proves the walk logic is broken (the fixture is a known-bad + // file inside web/templates/ that MUST be detected). + hits := []string{} + err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() { + base := filepath.Base(path) + if base == ".ciagent" || base == ".git" { + return filepath.SkipDir + } + return nil + } + if path == this { + return nil + } + rel, rerr := filepath.Rel(root, path) + if rerr != nil { + return rerr + } + if !isWebTarget(rel) { + return nil + } + bz, rerr := os.ReadFile(path) + if rerr != nil { + return rerr + } + if found, ok := lexicon.FindBannedTerm(string(bz)); ok { + hits = append(hits, rel+" contains banned term "+found) + } + return nil + }) + if err != nil { + t.Fatalf("walk: %v", err) + } + // Assert the fixture was found. The rel path uses OS-specific separator; + // match on the suffix so the test is portable. + foundFixture := false + for _, h := range hits { + if strings.Contains(h, "bad_fixture.html") && strings.Contains(h, syntheticTerm) { + foundFixture = true + break + } + } + if !foundFixture { + t.Errorf("G-013 walk-coverage: the walk did NOT find the synthetic banned-term fixture at %s — the web firewall walk logic is broken (it would silently scan nothing and report green). hits=%v", fixtureFile, hits) + } +} diff --git a/web/handlers/reach.go b/web/handlers/reach.go new file mode 100644 index 0000000..e6065fc --- /dev/null +++ b/web/handlers/reach.go @@ -0,0 +1,90 @@ +package handlers + +import ( + "net/http" + + identitytypes "github.com/oy/openyield/x/identity/types" + stashtypes "github.com/oy/openyield/x/stash/types" +) + +// registerReach wires the Reach signup routes (REQ-040) into the mux. +// Go 1.22 method-pattern routing: GET /reach (list), GET /reach/new (form), +// POST /reach (atomic create + redirect per D-071), GET /reach/{id} (detail). +func (s *Server) registerReach(mux *http.ServeMux) { + mux.HandleFunc("GET /reach", s.handleReachList) + mux.HandleFunc("GET /reach/new", s.handleReachNew) + mux.HandleFunc("POST /reach", s.handleReachCreate) + mux.HandleFunc("GET /reach/{id}", s.handleReachDetail) +} + +// handleReachList renders all Reaches (seeded + created). +func (s *Server) handleReachList(w http.ResponseWriter, r *http.Request) { + reaches := s.Store.ListReaches() + s.render(w, "reach_list.html", map[string]any{"Reaches": reaches}) +} + +// handleReachNew renders the "Create a Reach" form. Lexicon-clean: "Create a +// Reach", NOT a legacy custodial-position label (REQ-012 bans that word). +func (s *Server) handleReachNew(w http.ResponseWriter, r *http.Request) { + s.render(w, "reach_new.html", nil) +} + +// handleReachCreate handles the POST from the "Create a Reach" form. Calls +// store.CreateReach (atomic Reach + Stash per D-071). On validation error +// (G-027) returns 400 with a lexicon-clean message; on duplicate returns 409. +// On success redirects (302) to the new Reach detail page. +func (s *Server) handleReachCreate(w http.ResponseWriter, r *http.Request) { + holderID := r.FormValue("holder_id") + publicKey := r.FormValue("public_key") + reach, _, err := s.Store.CreateReach(holderID, publicKey) + if err != nil { + // G-026: rendered-HTML lexicon check scans error response bodies too; + // keep the error message lexicon-clean (no banned terms). + status := http.StatusBadRequest + if isDuplicate(err) { + status = http.StatusConflict + } + http.Error(w, "Could not create a Reach: "+err.Error(), status) + return + } + http.Redirect(w, r, "/reach/"+reach.HolderID, http.StatusFound) +} + +// handleReachDetail renders one Reach + its associated Stash (BalanceGrain). +func (s *Server) handleReachDetail(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + reach, ok := s.Store.GetReach(id) + if !ok { + http.NotFound(w, r) + return + } + stash, _ := s.Store.GetStash(id) + s.render(w, "reach_detail.html", map[string]any{ + "Reach": reach, + "Stash": stash, + }) +} + +// isDuplicate reports whether err is a duplicate-holder error from +// store.CreateReach. Kept as a string match to avoid exporting store errors. +func isDuplicate(err error) bool { + return err != nil && contains(err.Error(), "already has a Reach") +} + +func contains(s, sub string) bool { + return len(s) >= len(sub) && (s == sub || indexOf(s, sub) >= 0) +} + +func indexOf(s, sub string) int { + for i := 0; i+len(sub) <= len(s); i++ { + if s[i:i+len(sub)] == sub { + return i + } + } + return -1 +} + +// Compile-time assertions that the handlers use the real x/*/types structs +// (D-067: the UI grounds in the real Go type definitions). +var _ identitytypes.Reach +var _ stashtypes.Stash diff --git a/web/handlers/reach_test.go b/web/handlers/reach_test.go new file mode 100644 index 0000000..c188a4f --- /dev/null +++ b/web/handlers/reach_test.go @@ -0,0 +1,185 @@ +package handlers + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/oy/openyield/lexicon" + "github.com/oy/openyield/web/store" +) + +// newTestServer builds a Server with a fresh store + templates parsed from +// web/templates (relative to repo root via the handlers test working dir). +func newTestServer(t *testing.T) *Server { + t.Helper() + srv, err := New(store.NewStore(), "../../web/templates") + if err != nil { + t.Fatalf("new handlers server: %v", err) + } + return srv +} + +// assertNoBannedTerms checks the rendered response body for banned terms +// (G-026: applies to BOTH 200 happy-path AND error response bodies). +func assertNoBannedTerms(t *testing.T, body string) { + t.Helper() + if term, ok := lexicon.FindBannedTerm(body); ok { + t.Errorf("rendered HTML contains banned term %q (REQ-012/G-026)", term) + } +} + +func TestReachListReturnsSeededReaches(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/reach", nil) + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /reach: status %d, want 200", rec.Code) + } + body := rec.Body.String() + if !strings.Contains(body, "holder-alia") { + t.Errorf("GET /reach: body missing seeded reach holder-alia") + } + if !strings.Contains(body, "holder-bryn") { + t.Errorf("GET /reach: body missing seeded reach holder-bryn") + } + assertNoBannedTerms(t, body) +} + +func TestReachNewReturnsForm(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/reach/new", nil) + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /reach/new: status %d, want 200", rec.Code) + } + body := rec.Body.String() + if !strings.Contains(body, "Create a Reach") { + t.Errorf("GET /reach/new: body missing 'Create a Reach' label") + } + // The legacy custodial-position word is BANNED (REQ-012) — must not appear. + // Check the full banned-terms list via the lexicon package (no literals in + // source); FindBannedTerm does word-boundary matching so this is stricter + // than a naive substring check. + if term, ok := lexicon.FindBannedTerm(body); ok { + t.Errorf("GET /reach/new: body contains banned word %q", term) + } + assertNoBannedTerms(t, body) +} + +func TestReachCreateValidRedirectsAndAtomicallyCreates(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/reach", strings.NewReader("holder_id=holder-new&public_key=pk-new")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusFound { + t.Fatalf("POST /reach valid: status %d, want 302 (Found)", rec.Code) + } + loc := rec.Header().Get("Location") + if !strings.Contains(loc, "/reach/holder-new") { + t.Errorf("POST /reach: Location %q, want redirect to /reach/holder-new", loc) + } + // D-071: atomic creation — both Reach + Stash must be present. + reach, ok := srv.Store.GetReach("holder-new") + if !ok { + t.Fatalf("POST /reach: GetReach miss after create (atomicity broken)") + } + if !reach.IsNomad { + t.Errorf("POST /reach: created Reach IsNomad=false, want true (D-071)") + } + stash, ok := srv.Store.GetStash("holder-new") + if !ok { + t.Fatalf("POST /reach: GetStash miss after create (atomicity broken — D-071)") + } + if stash.HolderID != reach.HolderID { + t.Errorf("POST /reach: stash.HolderID %q != reach.HolderID %q (D-071)", stash.HolderID, reach.HolderID) + } +} + +func TestReachCreateEmptyHolderIDReturns400(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/reach", strings.NewReader("holder_id=&public_key=pk")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("POST /reach empty holder: status %d, want 400", rec.Code) + } + // G-026: rendered-HTML lexicon check scans the ERROR response body too. + assertNoBannedTerms(t, rec.Body.String()) +} + +func TestReachCreatePathSeparatorReturns400(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/reach", strings.NewReader("holder_id=h/x&public_key=pk")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("POST /reach path separator: status %d, want 400", rec.Code) + } + assertNoBannedTerms(t, rec.Body.String()) +} + +func TestReachCreateDuplicateReturns409(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/reach", strings.NewReader("holder_id=holder-alia&public_key=pk")) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusConflict { + t.Fatalf("POST /reach duplicate: status %d, want 409", rec.Code) + } + assertNoBannedTerms(t, rec.Body.String()) +} + +func TestReachDetailSeededReturnsReachAndStash(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/reach/holder-alia", nil) + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("GET /reach/holder-alia: status %d, want 200", rec.Code) + } + body := rec.Body.String() + if !strings.Contains(body, "reach-holder-alia") { + t.Errorf("GET /reach/holder-alia: body missing reach-holder-alia") + } + if !strings.Contains(body, "stash-holder-alia") { + t.Errorf("GET /reach/holder-alia: body missing associated stash-holder-alia") + } + if !strings.Contains(body, "Grain") { + t.Errorf("GET /reach/holder-alia: body missing Stash balance in Grain") + } + assertNoBannedTerms(t, body) +} + +func TestReachDetailMissingReturns404(t *testing.T) { + srv := newTestServer(t) + mux := http.NewServeMux() + srv.Register(mux) + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/reach/nobody", nil) + mux.ServeHTTP(rec, req) + if rec.Code != http.StatusNotFound { + t.Fatalf("GET /reach/nobody: status %d, want 404", rec.Code) + } +} diff --git a/web/handlers/server.go b/web/handlers/server.go new file mode 100644 index 0000000..b9eafec --- /dev/null +++ b/web/handlers/server.go @@ -0,0 +1,100 @@ +// Package handlers holds the HTTP handlers for the OpenYield web UI screens. +// +// Each screen (Reach signup, Stash dashboard, Window authorization, Standing +// progress, Bloom accrual) gets its own handler file. handlers/server.go wires +// routes into the mux from web/server.go. Handlers render html/template +// templates against the mock store (web/store). Lexicon-clean by construction +// (REQ-012 / REQ-045): the lexicon_meta_web firewall scans these files. +package handlers + +import ( + "fmt" + "html/template" + "net/http" + "os" + "path/filepath" + + "github.com/oy/openyield/web/store" +) + +// Server bundles the mock store + per-page templates + route registration. +// Each screen handler is a method on Server so it shares the store + tmpl. +// +// Template loading: base.html is parsed once, then each page template is +// parsed in a CLONE of the base set so the per-page "content" block does not +// collide across pages (Go html/template shares the block namespace within +// one set; cloning per page isolates each page's content block). This is the +// standard Go template pattern for layouts + pages. +type Server struct { + Store *store.Store + Pages map[string]*template.Template +} + +// New constructs a Server with the given store + per-page templates loaded +// from templatesDir (the absolute or relative path to web/templates/). +func New(s *store.Store, templatesDir string) (*Server, error) { + basePath := filepath.Join(templatesDir, "base.html") + base, err := template.ParseFiles(basePath) + if err != nil { + return nil, fmt.Errorf("parse base: %w", err) + } + pages := map[string]*template.Template{} + pageGlob := filepath.Join(templatesDir, "*.html") + matches, err := filepath.Glob(pageGlob) + if err != nil { + return nil, fmt.Errorf("glob pages: %w", err) + } + for _, p := range matches { + name := filepath.Base(p) + if name == "base.html" { + continue + } + clone, cerr := base.Clone() + if cerr != nil { + return nil, fmt.Errorf("clone for %s: %w", name, cerr) + } + pt, perr := clone.ParseFiles(p) + if perr != nil { + return nil, fmt.Errorf("parse %s: %w", name, perr) + } + pages[name] = pt + } + return &Server{Store: s, Pages: pages}, nil +} + +// Register wires all screen routes into the given mux (Go 1.22 method +// patterns). Called by web/server.go after constructing the Server. +func (s *Server) Register(mux *http.ServeMux) { + s.registerReach(mux) + // P2..P5 register their own routes (stash, window, standing, bloom). +} + +// render executes the named page template with the given data, writing HTML +// to w. The page template invokes base.html and overrides the "content" block. +func (s *Server) render(w http.ResponseWriter, name string, data any) { + tmpl, ok := s.Pages[name] + if !ok { + http.Error(w, "template not found: "+name, http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := tmpl.ExecuteTemplate(w, "base.html", data); err != nil { + http.Error(w, "render error", http.StatusInternalServerError) + } +} + +// RenderHome renders the home page (public so web/server.go can call it for +// the "/" route which lives outside handlers.Register). +func (s *Server) RenderHome(w http.ResponseWriter, data any) { + s.render(w, "home.html", data) +} + +// templatesDir returns the default web/templates directory relative to the +// working directory. Used by web/server.go when constructing via New(). +func DefaultTemplatesDir() string { + dir, _ := os.Getwd() + if filepath.Base(dir) == "web" || filepath.Base(dir) == "handlers" { + return filepath.Join(dir, "templates") + } + return "web/templates" +} diff --git a/web/main.go b/web/main.go new file mode 100644 index 0000000..77a0032 --- /dev/null +++ b/web/main.go @@ -0,0 +1,5 @@ +package main + +func main() { + runServer() +} diff --git a/web/server.go b/web/server.go new file mode 100644 index 0000000..d472060 --- /dev/null +++ b/web/server.go @@ -0,0 +1,42 @@ +package main + +import ( + "log" + "net/http" + "os" + + "github.com/oy/openyield/web/handlers" + "github.com/oy/openyield/web/store" +) + +func runServer() { + port := os.Getenv("PORT") + if port == "" { + port = "8080" + } + + mux := http.NewServeMux() + + srv, err := handlers.New(store.NewStore(), "web/templates") + if err != nil { + log.Fatalf("init handlers: %v", err) + } + srv.Register(mux) + + // Home page (rendered via the handlers' page machinery too). + mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/" { + http.NotFound(w, r) + return + } + srv.RenderHome(w, nil) + }) + + mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static")))) + + server := &http.Server{Addr: ":" + port, Handler: mux} + log.Printf("OpenYield web on :%s", port) + if err := server.ListenAndServe(); err != nil { + log.Fatalf("server: %v", err) + } +} diff --git a/web/static/htmx.min.js b/web/static/htmx.min.js new file mode 100644 index 0000000..3ace972 --- /dev/null +++ b/web/static/htmx.min.js @@ -0,0 +1,5 @@ +/* htmx.min.js — HTMX 2.0.10 (vendored static asset, NOT a go get; G-006). + Source: https://unpkg.com/htmx.org@2.0.10/dist/htmx.min.js + Used for progressive enhancement of form POSTs (hx-post -> swap). + Pinned version recorded here per PLANS P1-02-02 risk mitigation. */ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.10"};Q.onLoad=j;Q.process=Ft;Q.on=ye;Q.off=xe;Q.trigger=ae;Q.ajax=Nn;Q.find=f;Q.findAll=y;Q.closest=g;Q.remove=z;Q.addClass=w;Q.removeClass=b;Q.toggleClass=G;Q.takeClass=W;Q.swap=_e;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=$;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:U,findThisElement:we,filterValues:yn,swap:_e,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:A,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Se,makeFragment:P,mergeObjects:le,makeSettleInfo:Sn,oobSwap:He,querySelectorExt:ce,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function q(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function A(e,t){while(e&&!t(e)){e=c(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;A(t,function(e){return!!(r=o(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function N(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function I(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function D(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=N(t);let r;if(n==="html"){r=new DocumentFragment;const i=I(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=I(t);L(r,i.body);r.title=i.title}else{const i=I('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){D(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function M(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function F(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function X(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function U(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function V(e){try{const t=new URL(e,window.location.href);e=t.pathname+t.search}catch(e){}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function $(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function y(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return y(te(),e)}}function x(){return window}function z(e,t){e=S(e);if(t){x().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function J(e){return e instanceof HTMLElement?e:null}function K(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function w(e,t,n){e=ue(S(e));if(!e){return}if(n){x().setTimeout(function(){w(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function b(e,t,n){let r=ue(S(e));if(!r){return}if(n){x().setTimeout(function(){b(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function G(e,t){e=S(e);e.classList.toggle(t)}function W(e,t){e=S(e);ie(e.parentElement.children,function(e){b(e,t)});w(ue(e),t)}function g(e,t){e=ue(S(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Z(e,t){return e.substring(e.length-t.length)===t}function Y(e){const t=e.trim();if(l(t,"<")&&Z(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=S(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=Y(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),Y(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),Y(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,Y(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=ge(t,Y(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=q(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const u=p(q(t,!!n));i.push(...F(u.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=p(q(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ce(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function S(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function me(e,t,n,r){if(k(t)){return{target:te().body,event:K(e),listener:t,options:n}}else{return{target:S(e),event:K(t),listener:n,options:r}}}function ye(t,n,r,o){Gn(function(){const e=me(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function xe(t,n,r){Gn(function(){const e=me(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const be=te().createElement("output");function ve(t,n){const e=ne(t,n);if(e){if(e==="this"){return[we(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ue(A(t,function(e){return e!==t&&s(ue(e),n)}));if(i){r.push(...ve(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[be]}else{return r}}}}function we(e,t){return ue(A(e,function(e){return a(ue(e),t)!=null}))}function Se(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return we(e,"hx-target")}else{return ce(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ee(e){return Q.config.attributesToSettle.includes(e)}function Ce(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ee(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ee(e.name)){t.setAttribute(e.name,e.value)}})}function Oe(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!Oe(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){Re(t);je(s,e,e,t,i);Te()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o,target:n})}return e}function Te(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function Re(e){ie(y(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","
");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function qe(i,e,s){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const e=p(i);const r=e&&e.querySelector(CSS.escape(t.tagName)+"#"+CSS.escape(n));if(r&&r!==e){const o=t.cloneNode();Ce(t,r);s.tasks.push(function(){Ce(t,o)})}}})}function Ae(e){return function(){b(e,Q.config.addedClass);Ft(ue(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=J(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function u(e,t,n,r){qe(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;w(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function _e(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=S(h);const r=g.contextElement?q(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=P(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){x().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){x().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function ze(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(M(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,C)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,Ze);const l=o.length;const u=O(o,/[,\[\s]/);if(u!==""){if(u==="every"){const c={trigger:"every"};O(o,Ze);c.pollInterval=d(O(o,/[,\[\s]/));O(o,Ze);var i=nt(e,o,"event");if(i){c.eventFilter=i}r.push(c)}else{const f={trigger:u};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,Ze);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,C))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,C);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,C))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,C)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,C)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,Ze)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,Ze)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ut(e,t,n){const r=oe(e);r.timeout=x().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ut(e,t,n)}},n.pollInterval)}function ct(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ct(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ue(e);if(ft(n)){E(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,u,e,c,f){const a=oe(l);let t;if(c.from){t=m(l,c.from)}else{t=[l]}if(c.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(c)){a.lastValue.set(c,new WeakMap)}a.lastValue.get(c).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(c.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(c,l,e)){return}const t=oe(e);t.triggerSpec=c;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(c.consume){e.stopPropagation()}if(c.target&&e.target){if(!h(ue(e.target),c.target)){return}}if(c.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(c.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(c);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(c.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");u(l,e);a.throttle=x().setTimeout(function(){a.throttle=null},c.throttle)}}else if(c.delay>0){a.delayed=x().setTimeout(function(){ae(l,"htmx:trigger");u(l,e)},c.delay)}else{ae(l,"htmx:trigger");u(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:c.trigger,listener:s,on:i});i.addEventListener(c.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&B(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){x().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(ft(n)){E(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ce(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ut(ue(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=It(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=It(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ue(e),"button, input[type='submit']")}function Nt(e){return e.form||g(e,"form")}function It(e){const t=At(e.target);if(!t){return}const n=Nt(t);if(!n){return}return oe(n)}function Lt(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){De(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!U()){return null}t=V(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);_e(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){_e(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=ve(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;w(e,Q.config.requestClass)});return t}function nn(e){let t=ve(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;if(!e.hasAttribute("disabled")){e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")}});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){b(e,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0&&e.hasAttribute("data-disabled-by-htmx")){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function cn(e){if(e instanceof HTMLSelectElement&&e.multiple){return F(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return F(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,cn(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){un(e.name,cn(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Nt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const c=s.lastButtonClicked||e;const f=ee(c,"name");ln(f,c.value,o)}const u=ve(e,"hx-include");ie(u,function(e){fn(n,r,i,ue(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=X(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=c;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ce(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){x().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ce(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const u in n){if(n.hasOwnProperty(u)){if(i[u]==null){i[u]=n[u]}}}}return Cn(ue(c(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Nn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:S(r)||be,returnPromise:true})}else{let e=S(r.target);if(r.target&&!e||r.source&&!e&&!S(r.source)){e=be}return he(t,n,S(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function In(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Ln(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const u=i.targetOverride||ue(Se(r));if(u==null||u==be){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let c=oe(r);const f=c.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const N=ee(f,"formmethod");if(N!=null){if(de.includes(N.toLowerCase())){t=N}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:u,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const I=d.split(":");const L=I[0].trim();if(L==="this"){h=we(r,"hx-sync")}else{h=ue(ce(r,L))}d=(I[1]||"drop").trim();c=oe(h);if(d==="drop"&&c.xhr&&c.abortable!==true){re(s);return e}else if(d==="abort"){if(c.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(c.xhr){if(c.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(c.queuedRequests==null){c.queuedRequests=[]}if(p==="first"&&c.queuedRequests.length===0){c.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){c.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){c.queuedRequests=[];c.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;c.xhr=g;c.abortable=B;const m=function(){c.xhr=null;c.abortable=false;if(c.queuedRequests!=null&&c.queuedRequests.length>0){const e=c.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:u})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,u,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(u,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:u,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!Ln(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:u,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=In(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;let l=t.etc.push||ne(e,"hx-push-url");let u=t.etc.replace||ne(e,"hx-replace-url");if(l==="false")l=null;if(u==="false")u=null;const c=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(u){f="replace";a=u}else if(c){f="push";a=s||i}if(a){if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};x().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/web/static/style.css b/web/static/style.css new file mode 100644 index 0000000..558e438 --- /dev/null +++ b/web/static/style.css @@ -0,0 +1,78 @@ +/* style.css — OpenYield web UI minimal styling (lexicon-clean). + No banned terms in comments or class names (REQ-012/REQ-045). */ + +:root { + --bg: #0d1117; + --panel: #161b22; + --ink: #c9d1d9; + --muted: #8b949e; + --accent: #58a6ff; + --line: #30363d; +} + +* { box-sizing: border-box; } + +body { + margin: 0; + font-family: system-ui, -apple-system, sans-serif; + background: var(--bg); + color: var(--ink); + line-height: 1.5; +} + +a { color: var(--accent); text-decoration: none; } +a:hover { text-decoration: underline; } + +header.nav { + border-bottom: 1px solid var(--line); + padding: 0.75rem 1.5rem; + display: flex; + gap: 1.25rem; + align-items: center; + background: var(--panel); +} +header.nav .brand { font-weight: 600; color: var(--ink); } +header.nav a { color: var(--muted); } +header.nav a:hover { color: var(--accent); } + +main { max-width: 960px; margin: 2rem auto; padding: 0 1.5rem; } + +footer { + border-top: 1px solid var(--line); + padding: 1rem 1.5rem; + color: var(--muted); + font-size: 0.85rem; + text-align: center; +} + +.panel { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 6px; + padding: 1.25rem; + margin-bottom: 1.5rem; +} + +table { width: 100%; border-collapse: collapse; } +th, td { text-align: left; padding: 0.5rem 0.75rem; border-bottom: 1px solid var(--line); } +th { color: var(--muted); font-weight: 600; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.04em; } + +form .field { margin-bottom: 1rem; } +form label { display: block; margin-bottom: 0.25rem; color: var(--muted); font-size: 0.9rem; } +form input[type=text], form input[type=password] { + width: 100%; max-width: 32rem; + padding: 0.5rem 0.65rem; + background: var(--bg); + border: 1px solid var(--line); + border-radius: 4px; + color: var(--ink); + font-family: monospace; +} +button, .btn { + background: var(--accent); color: #0d1117; border: none; + padding: 0.5rem 1rem; border-radius: 4px; font-weight: 600; cursor: pointer; +} +button:hover, .btn:hover { opacity: 0.9; text-decoration: none; } + +.error { color: #f85149; } +.muted { color: var(--muted); } \ No newline at end of file diff --git a/web/store/fixtures.go b/web/store/fixtures.go new file mode 100644 index 0000000..5f67c02 --- /dev/null +++ b/web/store/fixtures.go @@ -0,0 +1,46 @@ +package store + +import ( + "time" + + identitytypes "github.com/oy/openyield/x/identity/types" + stashtypes "github.com/oy/openyield/x/stash/types" +) + +// seed populates the store with a few pre-existing Reach/Stash pairs for the +// list view. All strings lexicon-clean ("Holder"/"Reach"/"Stash"; NOT the +// banned financial terms). Two fixtures: one mature (90+ active days), +// one immature (45 active days) so the Stash dashboard (P2) can show both +// states. +func (s *Store) seed() { + now := time.Now().Unix() + // Fixture 1: a mature Nomad (ActiveDays=92, MaxGapDays=10 -> IsMature()). + seedOne(s, "holder-alia", "pk-alia-001", now, 920000, 92, 10) + // Fixture 2: an immature Nomad (ActiveDays=45, MaxGapDays=5 -> not mature). + seedOne(s, "holder-bryn", "pk-bryn-002", now, 410000, 45, 5) +} + +func seedOne(s *Store, holderID, pubKey string, now int64, balanceGrain int64, activeDays, maxGap uint32) { + reachID := "reach-" + holderID + stashID := "stash-" + holderID + s.reaches[holderID] = identitytypes.Reach{ + ReachID: reachID, + HolderID: holderID, + CreatedAt: now - int64(activeDays)*86400, + PublicKey: pubKey, + IsNomad: true, + } + s.stashes[holderID] = stashtypes.Stash{ + HolderID: holderID, + StashID: stashID, + CreatedAt: now - int64(activeDays)*86400, + LastActive: now, + BalanceGrain: balanceGrain, + } + s.stashActivities[stashID] = stashtypes.StashActivity{ + StashID: stashID, + ActiveDays: activeDays, + MaxGapDays: maxGap, + LastActivityDay: now, + } +} diff --git a/web/store/import_test.go b/web/store/import_test.go new file mode 100644 index 0000000..5bbef69 --- /dev/null +++ b/web/store/import_test.go @@ -0,0 +1,108 @@ +// import_test.go enforces the G-003/G-025 boundary for web/: web/ is the +// application layer that consumes protocol types (D-070), NOT a cross-x/ +// production import. The invariant: every non-test .go file under web/ may +// import github.com/oy/openyield/x//types packages (the app-layer +// consumption direction), but MUST NOT import github.com/oy/openyield/ +// x//keeper OR github.com/oy/openyield/x/ (the module.go +// packages — G-025 extends the original keeper-only check to also forbid +// module.go, since those packages carry Cosmos runtime machinery the mock UI +// must not reach into). This test uses go/parser (stdlib only — G-006) and +// mirrors the x/window/types/types_test.go G-003 pattern, but with the +// inverted rule: x/*/types is ALLOWED (app-layer consumption), x/*/keeper +// and x/ (module.go) are FORBIDDEN. +package store + +import ( + "go/parser" + "go/token" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestG025WebImportsOnlyTypesNotKeeperOrModule(t *testing.T) { + webRoot := webRoot(t) + fset := token.NewFileSet() + violations := []string{} + err := filepath.Walk(webRoot, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() { + return nil + } + if !strings.HasSuffix(path, ".go") { + return nil + } + // Skip test files (G-025 is about production code only). + if strings.HasSuffix(path, "_test.go") { + return nil + } + f, perr := parser.ParseFile(fset, path, nil, parser.ImportsOnly) + if perr != nil { + return perr + } + for _, imp := range f.Imports { + ip := strings.Trim(imp.Path.Value, `"`) + if isForbiddenXImport(ip) { + rel, _ := filepath.Rel(webRoot, path) + violations = append(violations, rel+" -> "+ip) + } + } + return nil + }) + if err != nil { + t.Fatalf("walk web/: %v", err) + } + if len(violations) > 0 { + t.Errorf("G-025 violation: web/ production files importing forbidden x/ packages:\n %s", + strings.Join(violations, "\n ")) + } +} + +// isForbiddenXImport reports whether ip is an x//keeper or a bare +// x/ (module.go) import — both forbidden from web/ (G-025). The +// x//types packages are ALLOWED (D-070 app-layer consumption). +func isForbiddenXImport(ip string) bool { + const prefix = "github.com/oy/openyield/x/" + if !strings.HasPrefix(ip, prefix) { + return false + } + rest := strings.TrimPrefix(ip, prefix) + parts := strings.Split(rest, "/") + switch len(parts) { + case 1: + // x/ (module.go package) — forbidden (G-025). + return true + case 2: + // x//types -> allowed (D-070). x//keeper -> forbidden. + if parts[1] == "types" { + return false + } + return true + default: + // x///... — forbid anything other than types (e.g. + // x//keeper/... sub-packages). + if parts[1] == "types" { + return false + } + return true + } +} + +// webRoot returns the absolute path to the web/ directory by walking up +// from this test file (web/store/import_test.go -> repoRoot/web). +func webRoot(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("runtime.Caller failed") + } + // file = .../oy/web/store/import_test.go + // repoRoot = filepath.Dir(filepath.Dir(filepath.Dir(file))) + // webRoot = repoRoot/web + repoRoot := filepath.Dir(filepath.Dir(filepath.Dir(file))) + return filepath.Join(repoRoot, "web") +} diff --git a/web/store/store.go b/web/store/store.go new file mode 100644 index 0000000..4d6db21 --- /dev/null +++ b/web/store/store.go @@ -0,0 +1,146 @@ +// Package store is the in-memory mock data layer for the OpenYield web UI. +// +// It instantiates the real x/*/types structs (Reach, Stash, StashActivity) +// from in-memory fixtures and provides create/get/list methods. This is the +// app-layer consumption of protocol types (D-070), NOT a cross-x/ production +// import — web/ is NOT an x/ module. No keeper, no Cosmos runtime, no app.go +// (G-003 boundary enforced by import_test.go / G-025). +package store + +import ( + "fmt" + "strings" + "sync" + "time" + + identitytypes "github.com/oy/openyield/x/identity/types" + stashtypes "github.com/oy/openyield/x/stash/types" +) + +// seedBalanceGrain is the test balance seeded to a new Stash at signup (D-071 +// example: 500000 Grain = 50 Bread per GrainsPerBread=10000). +const seedBalanceGrain int64 = 500000 + +// Store is the in-memory mock store. All methods are goroutine-safe (mu). +type Store struct { + mu sync.Mutex + reaches map[string]identitytypes.Reach + stashes map[string]stashtypes.Stash + stashActivities map[string]stashtypes.StashActivity +} + +// NewStore constructs a Store seeded from fixtures (fixtures.go). +func NewStore() *Store { + s := &Store{ + reaches: map[string]identitytypes.Reach{}, + stashes: map[string]stashtypes.Stash{}, + stashActivities: map[string]stashtypes.StashActivity{}, + } + s.seed() + return s +} + +// CreateReach atomically creates a Reach (IsNomad=true) + a Stash (D-071). +// G-027: HolderID and PublicKey are validated (non-empty, <=128 bytes, no +// path separators, no template syntax) before any map write. Returns the +// created Reach + Stash. +func (s *Store) CreateReach(holderID, publicKey string) (identitytypes.Reach, stashtypes.Stash, error) { + if err := validateReachInput(holderID, publicKey); err != nil { + return identitytypes.Reach{}, stashtypes.Stash{}, err + } + s.mu.Lock() + defer s.mu.Unlock() + if _, dup := s.reaches[holderID]; dup { + return identitytypes.Reach{}, stashtypes.Stash{}, fmt.Errorf("holder %q already has a Reach", holderID) + } + now := time.Now().Unix() + reachID := "reach-" + holderID + stashID := "stash-" + holderID + reach := identitytypes.Reach{ + ReachID: reachID, + HolderID: holderID, + CreatedAt: now, + PublicKey: publicKey, + IsNomad: true, + } + stash := stashtypes.Stash{ + HolderID: holderID, + StashID: stashID, + CreatedAt: now, + LastActive: now, + BalanceGrain: seedBalanceGrain, + } + activity := stashtypes.StashActivity{ + StashID: stashID, + ActiveDays: 1, + MaxGapDays: 1, + LastActivityDay: now, + } + s.reaches[holderID] = reach + s.stashes[holderID] = stash + s.stashActivities[stashID] = activity + return reach, stash, nil +} + +// ListReaches returns all seeded + created Reaches. +func (s *Store) ListReaches() []identitytypes.Reach { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]identitytypes.Reach, 0, len(s.reaches)) + for _, r := range s.reaches { + out = append(out, r) + } + return out +} + +// GetReach returns the Reach for a holderID (by HolderID, the stable key). +func (s *Store) GetReach(holderID string) (identitytypes.Reach, bool) { + s.mu.Lock() + defer s.mu.Unlock() + r, ok := s.reaches[holderID] + return r, ok +} + +// GetStash returns the Stash for a holderID. +func (s *Store) GetStash(holderID string) (stashtypes.Stash, bool) { + s.mu.Lock() + defer s.mu.Unlock() + st, ok := s.stashes[holderID] + return st, ok +} + +// GetStashActivity returns the StashActivity for a stashID. +func (s *Store) GetStashActivity(stashID string) (stashtypes.StashActivity, bool) { + s.mu.Lock() + defer s.mu.Unlock() + a, ok := s.stashActivities[stashID] + return a, ok +} + +// validateReachInput enforces G-027: HolderID and PublicKey must be non-empty, +// <=128 bytes, and contain no path separators or template syntax. This is a +// prototype-robustness gate (the mock store uses holderID as a map key). +func validateReachInput(holderID, publicKey string) error { + if holderID == "" { + return fmt.Errorf("holder id is required") + } + if len(holderID) > 128 { + return fmt.Errorf("holder id too long (max 128)") + } + if strings.ContainsAny(holderID, "/\\") { + return fmt.Errorf("holder id must not contain path separators") + } + if strings.Contains(holderID, "{{") { + return fmt.Errorf("holder id must not contain template syntax") + } + if publicKey == "" { + return fmt.Errorf("public key is required") + } + if len(publicKey) > 128 { + return fmt.Errorf("public key too long (max 128)") + } + if strings.ContainsAny(publicKey, "/\\") { + return fmt.Errorf("public key must not contain path separators") + } + return nil +} diff --git a/web/store/store_test.go b/web/store/store_test.go new file mode 100644 index 0000000..13a863a --- /dev/null +++ b/web/store/store_test.go @@ -0,0 +1,216 @@ +package store + +import ( + "sync" + "testing" + + identitytypes "github.com/oy/openyield/x/identity/types" + stashtypes "github.com/oy/openyield/x/stash/types" +) + +func TestNewStoreSeedsFixtures(t *testing.T) { + s := NewStore() + reaches := s.ListReaches() + if len(reaches) < 2 { + t.Fatalf("NewStore seeded %d reaches, want >=2", len(reaches)) + } + // Both seeded reaches must be Nomads (IsNomad=true). + for _, r := range reaches { + if !r.IsNomad { + t.Errorf("seeded reach %q: IsNomad=false, want true", r.HolderID) + } + } +} + +func TestCreateReachAtomicReachAndStash(t *testing.T) { + s := NewStore() + reach, stash, err := s.CreateReach("holder-test1", "pk-test1") + if err != nil { + t.Fatalf("CreateReach: %v", err) + } + // D-071: Reach must be IsNomad=true. + if !reach.IsNomad { + t.Errorf("reach.IsNomad = false, want true (D-071)") + } + if reach.HolderID != "holder-test1" { + t.Errorf("reach.HolderID = %q, want holder-test1", reach.HolderID) + } + // D-071: Stash must have matching HolderID + seeded BalanceGrain. + if stash.HolderID != reach.HolderID { + t.Errorf("stash.HolderID = %q, want %q (D-071 atomic)", stash.HolderID, reach.HolderID) + } + if stash.BalanceGrain != seedBalanceGrain { + t.Errorf("stash.BalanceGrain = %d, want %d", stash.BalanceGrain, seedBalanceGrain) + } + // Both must be retrievable after the atomic call. + if _, ok := s.GetReach("holder-test1"); !ok { + t.Errorf("GetReach miss after CreateReach (atomicity broken)") + } + if _, ok := s.GetStash("holder-test1"); !ok { + t.Errorf("GetStash miss after CreateReach (atomicity broken)") + } + if _, ok := s.GetStashActivity(stash.StashID); !ok { + t.Errorf("GetStashActivity miss after CreateReach (atomicity broken)") + } +} + +func TestCreateReachDuplicateRejected(t *testing.T) { + s := NewStore() + if _, _, err := s.CreateReach("holder-alia", "pk-dupe"); err == nil { + t.Errorf("CreateReach duplicate holder-alia: expected error, got nil") + } +} + +func TestCreateReachValidationG027(t *testing.T) { + cases := []struct { + name string + holderID string + publicKey string + wantErr bool + }{ + {"empty holder", "", "pk", true}, + {"empty pubkey", "h", "", true}, + {"holder too long", stringOf('x', 129), "pk", true}, + {"pubkey too long", "h", stringOf('y', 129), true}, + {"holder with slash", "h/x", "pk", true}, + {"holder with backslash", "h\\x", "pk", true}, + {"holder with template syntax", "h{{", "pk", true}, + {"pubkey with slash", "h", "p/x", true}, + {"valid minimal", "h", "p", false}, + {"valid typical", "holder-oka", "pk-oka-7", false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + s := NewStore() + _, _, err := s.CreateReach(c.holderID, c.publicKey) + if c.wantErr && err == nil { + t.Errorf("expected error, got nil") + } + if !c.wantErr && err != nil { + t.Errorf("unexpected error: %v", err) + } + }) + } +} + +func TestGetReachHitMiss(t *testing.T) { + s := NewStore() + if _, ok := s.GetReach("holder-alia"); !ok { + t.Errorf("GetReach(holder-alia) miss, want hit (seeded)") + } + if _, ok := s.GetReach("nobody"); ok { + t.Errorf("GetReach(nobody) hit, want miss") + } +} + +func TestGetStashHitMiss(t *testing.T) { + s := NewStore() + if _, ok := s.GetStash("holder-alia"); !ok { + t.Errorf("GetStash(holder-alia) miss, want hit (seeded)") + } + if _, ok := s.GetStash("nobody"); ok { + t.Errorf("GetStash(nobody) hit, want miss") + } +} + +func TestGetStashActivityHitMiss(t *testing.T) { + s := NewStore() + stash, ok := s.GetStash("holder-alia") + if !ok { + t.Fatal("seeded stash holder-alia missing") + } + if _, ok := s.GetStashActivity(stash.StashID); !ok { + t.Errorf("GetStashActivity(%q) miss, want hit", stash.StashID) + } + if _, ok := s.GetStashActivity("stash-nobody"); ok { + t.Errorf("GetStashActivity(stash-nobody) hit, want miss") + } +} + +func TestCreateReachConcurrentNoRace(t *testing.T) { + s := NewStore() + const n = 50 + var wg sync.WaitGroup + wg.Add(n) + for i := 0; i < n; i++ { + go func(i int) { + defer wg.Done() + holder := "holder-concurrent-" + itoa(i) + _, _, _ = s.CreateReach(holder, "pk") + }(i) + } + wg.Wait() + // All n concurrent creates with distinct holder IDs must be present. + for i := 0; i < n; i++ { + if _, ok := s.GetReach("holder-concurrent-" + itoa(i)); !ok { + t.Errorf("concurrent reach %d missing after wg.Wait", i) + } + } +} + +func TestSeededMatureVsImmature(t *testing.T) { + s := NewStore() + // holder-alia: ActiveDays=92, MaxGapDays=10 -> mature. + aliaStash, ok := s.GetStash("holder-alia") + if !ok { + t.Fatal("seeded holder-alia missing") + } + aliaAct, ok := s.GetStashActivity(aliaStash.StashID) + if !ok { + t.Fatal("seeded alia activity missing") + } + if !aliaAct.IsMature() { + t.Errorf("holder-alia IsMature=false, want true (ActiveDays=%d, MaxGap=%d)", + aliaAct.ActiveDays, aliaAct.MaxGapDays) + } + // holder-bryn: ActiveDays=45, MaxGapDays=5 -> not mature. + brynStash, ok := s.GetStash("holder-bryn") + if !ok { + t.Fatal("seeded holder-bryn missing") + } + brynAct, ok := s.GetStashActivity(brynStash.StashID) + if !ok { + t.Fatal("seeded bryn activity missing") + } + if brynAct.IsMature() { + t.Errorf("holder-bryn IsMature=true, want false (ActiveDays=%d, MaxGap=%d)", + brynAct.ActiveDays, brynAct.MaxGapDays) + } +} + +// Compile-time assertions that the types are the real x/*/types structs +// (D-067: the mock store grounds the UI in the real Go type definitions). +var _ identitytypes.Reach +var _ stashtypes.Stash + +// itoa is a tiny strconv.Itoa without the import (keeps store_test.go deps +// to just sync + testing + the two x/*/types packages). +func itoa(n int) string { + if n == 0 { + return "0" + } + neg := n < 0 + if neg { + n = -n + } + var buf [20]byte + i := len(buf) + for n > 0 { + i-- + buf[i] = byte('0' + n%10) + n /= 10 + } + if neg { + i-- + buf[i] = '-' + } + return string(buf[i:]) +} + +func stringOf(r rune, n int) string { + b := make([]byte, n) + for i := range b { + b[i] = byte(r) + } + return string(b) +} diff --git a/web/templates/base.html b/web/templates/base.html new file mode 100644 index 0000000..a042724 --- /dev/null +++ b/web/templates/base.html @@ -0,0 +1,29 @@ +{{define "base.html"}} + + + + + + {{block "title" .}}OpenYield{{end}} + + + + + +
+ {{block "content" .}}{{end}} +
+
+ OpenYield — real production on the mesh. Reach, Stash, Window, Standing, Bloom. +
+ + +{{end}} \ No newline at end of file diff --git a/web/templates/home.html b/web/templates/home.html new file mode 100644 index 0000000..2a96f13 --- /dev/null +++ b/web/templates/home.html @@ -0,0 +1,24 @@ +{{define "title"}}OpenYield — real production on the mesh{{end}} + +{{define "content"}} +
+

OpenYield

+

+ OpenYield is a mesh-native system for real production. A Holder creates a + Reach to enter the mesh, holds a Stash of Grain, and authorizes Window + access to partners. Standing accrues through honest participation, and + Bloom rewards sustained contribution. No middleman holds your Stash. +

+
+ +
+

The five screens

+
    +
  • Reach — create a Reach and view the mesh of Holders.
  • +
  • Stash — your sovereign Grain Stash (P2).
  • +
  • Window — authorize partner access to your Stash (P3).
  • +
  • Standing — track progress toward Freeholder standing (P4).
  • +
  • Bloom — accrued rewards for sustained contribution (P5).
  • +
+
+{{end}} \ No newline at end of file diff --git a/web/templates/reach_detail.html b/web/templates/reach_detail.html new file mode 100644 index 0000000..7297df0 --- /dev/null +++ b/web/templates/reach_detail.html @@ -0,0 +1,31 @@ +{{define "title"}}{{.Reach.ReachID}} — OpenYield{{end}} + +{{define "content"}} +
+

{{.Reach.ReachID}}

+ + + + + + + +
Reach ID{{.Reach.ReachID}}
Holder ID{{.Reach.HolderID}}
Public Key{{.Reach.PublicKey}}
Created{{.Reach.CreatedAt}}
Nomad{{if .Reach.IsNomad}}yes{{else}}no{{end}}
Freeholder{{if .Reach.IsFreeholder}}yes{{else}}no{{end}}
+
+ +{{if .Stash.StashID}} +
+

Stash

+ + + + + + +
Stash ID{{.Stash.StashID}}
Balance{{.Stash.BalanceGrain}} Grain
Created{{.Stash.CreatedAt}}
Last active{{.Stash.LastActive}}
Still{{if .Stash.IsStill}}paused{{else}}active{{end}}
+

View Stash dashboard

+
+{{end}} + +

Back to Reach list

+{{end}} \ No newline at end of file diff --git a/web/templates/reach_list.html b/web/templates/reach_list.html new file mode 100644 index 0000000..27e866e --- /dev/null +++ b/web/templates/reach_list.html @@ -0,0 +1,35 @@ +{{define "title"}}Reach — OpenYield{{end}} + +{{define "content"}} +
+

Reach

+

A Reach is the mesh-native identity a Holder uses to act on the mesh + without a custodian, a gatekeeper, or a legacy financial position. A Nomad + is a Holder who has a Reach and a Stash and is on the way to earning the + four Freeholder signals.

+

Create a Reach

+
+ +
+

Holders on the mesh

+ {{if .Reaches}} + + + + + + {{range .Reaches}} + + + + + + + {{end}} + +
Reach IDHolder IDNomadFreeholder
{{.ReachID}}{{.HolderID}}{{if .IsNomad}}yes{{else}}no{{end}}{{if .IsFreeholder}}yes{{else}}no{{end}}
+ {{else}} +

No Reaches yet. Create a Reach to begin.

+ {{end}} +
+{{end}} \ No newline at end of file diff --git a/web/templates/reach_new.html b/web/templates/reach_new.html new file mode 100644 index 0000000..7a98642 --- /dev/null +++ b/web/templates/reach_new.html @@ -0,0 +1,22 @@ +{{define "title"}}Create a Reach — OpenYield{{end}} + +{{define "content"}} +
+

Create a Reach

+

A Reach is an identity, not a custodial position. The protocol does not + require KYC at the protocol layer; the Reach is the unit of self-service. + Creating a Reach also opens a Stash for you (the place a Nomad holds + Grain) — that pair is enough to begin on the mesh.

+ +
+ + + + + +
+

Back to Reach list

+
+{{end}} \ No newline at end of file