From ebc7a546c5b5d7a6e2e3180b7dccee833d2a2f2f Mon Sep 17 00:00:00 2001 From: Sulthan Zaki Date: Sun, 26 Jul 2026 03:59:58 +0700 Subject: [PATCH] feat: password-gated web UI on the same backend (#1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a password-gated browser UI for the bookmark list, served by the same Go binary and container as the userscript API. ## What - `GET /` — list page, or the login page when there is no session (200, no redirect). - `POST /login`, `POST /logout` — stateless HMAC session cookie, 60-day Max-Age. - `GET /ui/list?tab=all|fav`, `POST /ui/bookmarks/{key}/favorite`, `POST /ui/bookmarks/{key}/chapter`, `DELETE /ui/bookmarks/{key}` — htmx fragments. - `GET /static/*` — embedded `style.css`, `htmx.min.js`, `filter.js`. Mobile-first dark CSS, 2–3 column grid at ≥900px, "Continue reading" strip of the five most recent series, NEW badge, client-side title search, no build step. ## Stack Go `html/template` + htmx 2.0.4 (vendored, 50 KB) + plain CSS. No npm, no bundler. Templates and assets are `go:embed`-ed, so `CGO_ENABLED=0` and the distroless image still hold. ## Auth `WEB_PASSWORD` gates the UI; unset means the web routes are never registered and `/` returns 404. Session cookie is `HttpOnly`, `SameSite=Lax`, `Secure` when the request is HTTPS. The signing key derives from `API_TOKEN` + `WEB_PASSWORD`, so rotating either logs every browser out. Login is rate-limited to 10 failures per 20 minutes per client IP, keyed on the **rightmost** `X-Forwarded-For` entry (Traefik appends the observed peer, so the leftmost is client-spoofable). CGNAT lockout is a known, accepted limitation — the window self-heals. ## Invariants preserved - A session cookie never authenticates `/bookmarks*`. That API stays JSON + bearer token, unchanged, as does the userscript. - `Store.Upsert` is byte-for-byte unmodified. Every UI write goes read-modify-write through the new `Store.Get`, so the conditional-`updated_at` rule (favouriting must not reorder the list, a chapter override must) lives in exactly one function. ## Deployment `docker-compose.prod.yml` gains a second Traefik router on `MANGA_WEB_HOST` pointing at the same service — one container, one certificate resolver, no second service. Both `MANGA_API_HOST` and `MANGA_WEB_HOST` are required (`:?`), with no example fallback in `.env.example`: a placeholder there would make Traefik silently publish the UI on a domain you do not own. Needs a DNS A/AAAA record for `manga.`. See `DEPLOY.md` §1b. ## Docs - Design: `docs/superpowers/specs/2026-07-25-web-ui-design.md` - Plan: `plans/2026-07-25-web-ui-implementation-plan.md` ## Verification `gofmt` clean, `go vet`, `go test -race ./...`, `CGO_ENABLED=0 go build`, a real `docker build` + curl smoke test, and a Playwright pass covering login reject/accept, favourite-without-reorder, chapter edit, delete-with-confirm, search, tab switch + back button, 390px with no horizontal overflow, and zero JS console errors. Reviewed-on: https://gitea.violetcrown.my.id/sulthan/mangaBookmark/pulls/1 Co-authored-by: Sulthan Zaki Co-committed-by: Sulthan Zaki --- .claude/settings.json | 24 + .env.example | 13 + CLAUDE.md | 13 +- DEPLOY.md | 48 +- backend/.dockerignore | 7 +- backend/Dockerfile | 4 + backend/main.go | 20 +- backend/session.go | 188 ++ backend/session_test.go | 232 ++ backend/static/filter.js | 33 + backend/static/htmx.min.js | 1 + backend/static/style.css | 225 ++ backend/store.go | 32 + backend/store_test.go | 95 + backend/templates/app.html | 53 + backend/templates/card.html | 37 + backend/templates/list.html | 9 + backend/templates/login.html | 24 + backend/web.go | 306 +++ backend/web_test.go | 485 ++++ docker-compose.prod.yml | 9 + docker-compose.yml | 2 + .../specs/2026-07-25-web-ui-design.md | 263 ++ .../2026-07-25-web-ui-implementation-plan.md | 2330 +++++++++++++++++ 24 files changed, 4446 insertions(+), 7 deletions(-) create mode 100644 .claude/settings.json create mode 100644 backend/session.go create mode 100644 backend/session_test.go create mode 100644 backend/static/filter.js create mode 100644 backend/static/htmx.min.js create mode 100644 backend/static/style.css create mode 100644 backend/templates/app.html create mode 100644 backend/templates/card.html create mode 100644 backend/templates/list.html create mode 100644 backend/templates/login.html create mode 100644 backend/web.go create mode 100644 backend/web_test.go create mode 100644 docs/superpowers/specs/2026-07-25-web-ui-design.md create mode 100644 plans/2026-07-25-web-ui-implementation-plan.md diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..b2d512a --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,24 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); case \"$CMD\" in *grep*|*rg\\ *|*ripgrep*|*find\\ *|*fd\\ *|*ack\\ *|*ag\\ *) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run `graphify query \\\"\\\"` before grepping raw files. Only grep after graphify has oriented you, or to modify/debug specific lines.\"}}' || true ;; esac" + } + ] + }, + { + "matcher": "Read|Glob", + "hooks": [ + { + "type": "command", + "command": "HIT=$(python3 -c \"import json,sys;d=json.load(sys.stdin);t=d.get('tool_input',d);exts=('.py','.js','.ts','.tsx','.jsx','.astro','.vue','.svelte','.go','.rs','.java','.rb','.c','.h','.cpp','.hpp','.cc','.cs','.kt','.swift','.php','.scala','.lua','.sh','.md','.rst','.txt','.mdx');vals=[str(t.get('file_path') or ''),str(t.get('pattern') or ''),str(t.get('path') or '')];j=' '.join(vals).lower().replace(chr(92),'/');tails=[('.'+x.rsplit('.',1)[-1]) for v in vals if v for x in [v.lower().replace(chr(92),'/').rsplit('/',1)[-1]] if '.' in x];sys.stdout.write('1' if 'graphify-out/' not in j and any(tl in exts for tl in tails) else '')\" 2>/dev/null || true); if [ \"$HIT\" = 1 ] && [ -f graphify-out/graph.json ]; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run graphify before reading source files. Use: `graphify query \\\"\\\"` (scoped subgraph), `graphify explain \\\"\\\"`, or `graphify path \\\"\\\" \\\"\\\"`. Only read raw files after graphify has oriented you, or to modify/debug specific lines. This rule applies to subagents too \u2014 include it in every subagent prompt involving code exploration.\"}}'; fi || true" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/.env.example b/.env.example index 48ab922..119c07f 100644 --- a/.env.example +++ b/.env.example @@ -16,3 +16,16 @@ ALLOWED_ORIGINS=https://asuracomic.net,https://asurascans.com,https://demonicsca # Traefik HTTPS entrypoint + cert resolver names, if yours differ from these. # TRAEFIK_ENTRYPOINT=websecure # TRAEFIK_CERTRESOLVER=le + +# --- Web UI --- +# Password for the browser UI at https://$MANGA_WEB_HOST. Leave unset to +# disable the web UI entirely (the routes are not registered at all). +# Generate one: openssl rand -base64 18 +WEB_PASSWORD= + +# Subdomain Traefik routes to the browser UI (required by the prod override, +# whether or not WEB_PASSWORD is set). Left commented on purpose: an example +# value here would be a silent wrong-hostname fallback, and Traefik would +# publish the UI router on a domain you do not own. The same container also +# answers on MANGA_API_HOST for the userscript's API. +# MANGA_WEB_HOST=manga.example.com diff --git a/CLAUDE.md b/CLAUDE.md index 453d735..9405fd0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -26,11 +26,20 @@ Bromite userscript (isolated world, per-site adapters, localStorage cache) -- fetch() HTTPS --> reverse proxy (TLS + CORS) --> Go net/http --> SQLite (volume) ``` -- **Backend** (`backend/`): stdlib `net/http` (3 routes, no framework) + `modernc.org/sqlite` (pure Go, `CGO_ENABLED=0` -> static binary -> distroless/scratch image). The reverse proxy terminates TLS; the Go service listens plain `:8080`. +- **Backend** (`backend/`): stdlib `net/http` (a handful of routes, no framework) + `modernc.org/sqlite` (pure Go, `CGO_ENABLED=0` -> static binary -> distroless/scratch image). The reverse proxy terminates TLS; the Go service listens plain `:8080`. - **Single-user store.** One `bookmarks` table keyed `:` (`asura`|`demonic`). Sync is **last-write-wins**. Schema and endpoint list are in the plan. - **Endpoints:** `GET /bookmarks`, `PUT /bookmarks/{key}` (upsert; see `updated_at` rule below), `DELETE /bookmarks/{key}`, `GET /healthz` (no auth). +- **Web UI:** the same binary serves a password-gated browser UI on a second + hostname — `GET /` (list, or login page when there is no session), + `POST /login`, `POST /logout`, `GET /static/*`, and htmx fragment endpoints + under `/ui/*`. Templates and assets are `go:embed`-ed, so `backend/Dockerfile` + must copy `templates/` and `static/` as well as `*.go`. Sessions are stateless + HMAC cookies keyed off `API_TOKEN`; `WEB_PASSWORD` gates them and, when empty, + the web routes are not registered at all. UI mutations read-modify-write + through `Store.Get` + `Store.Upsert` so the `updated_at` rule stays in one + place. See `docs/superpowers/specs/2026-07-25-web-ui-design.md`. - **`updated_at` drives list order, so it moves only on real reading progress:** the server applies its timestamp when the row is new or `last_chapter_num` changes, and otherwise keeps the stored value — favouriting a series or recording a newly published chapter must not reorder the list. `PUT` therefore returns the row **as stored**, and clients must adopt that response rather than their own payload. See `plans/2026-07-25-bookmark-list-favorites-design.md` §4. -- **Config via env:** `API_TOKEN`, `ALLOWED_ORIGINS` (comma list), `DB_PATH` (default `/data/bookmarks.db`), `PORT` (default `8080`). +- **Config via env:** `API_TOKEN`, `ALLOWED_ORIGINS` (comma list), `DB_PATH` (default `/data/bookmarks.db`), `PORT` (default `8080`), `WEB_PASSWORD` (gates the browser UI; unset disables it). ### Userscript structure (single IIFE, `manga-bookmark.user.js`) diff --git a/DEPLOY.md b/DEPLOY.md index 2bbb2ec..98fbe78 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -38,8 +38,11 @@ API_TOKEN= # CORS allowlist — leave as-is unless a site changes hostname. ALLOWED_ORIGINS=https://asuracomic.net,https://asurascans.com,https://demonicscans.org -# Required for the Traefik override. +# Required for the Traefik override. Both have no fallback — compose refuses +# to start without them. MANGA_WEB_HOST is required even if you never set +# WEB_PASSWORD; see 1b. MANGA_API_HOST=manga-api.violetcrown.my.id +MANGA_WEB_HOST=manga.violetcrown.my.id # Only if your Traefik setup differs from these defaults: # PROXY_NETWORK=proxy @@ -60,6 +63,49 @@ grep -E '^API_TOKEN=' .env # copy this — the userscript needs the same value --- +## 1b. Web UI + +The browser UI is served by the same container on a second hostname. + +1. Add a DNS `A`/`AAAA` record for `manga.` pointing at the server — + the same address as `manga-api.`. + +2. Set both variables in `.env`: + + ```ini + MANGA_WEB_HOST=manga.violetcrown.my.id + WEB_PASSWORD= + ``` + + Generate and insert in one line: + + ```bash + sed -i "s|^WEB_PASSWORD=.*|WEB_PASSWORD=$(openssl rand -base64 18)|" .env + grep -E '^WEB_PASSWORD=' .env # this is what you type into the site + ``` + +3. Redeploy and check: + + ```bash + docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build + curl -s -o /dev/null -w '%{http_code}\n' https://manga.violetcrown.my.id/ + ``` + + Expected `200`, serving the login page. + +Leaving `WEB_PASSWORD` unset is safe: the web routes are not registered and `/` +returns 404. The userscript's API on `MANGA_API_HOST` is unaffected either way. + +`MANGA_WEB_HOST` itself is required by the prod override regardless — like +`MANGA_API_HOST`, its Traefik label has no fallback, so `docker compose up` +refuses to start without it even if `WEB_PASSWORD` is unset and the web UI is +otherwise dormant. + +Sessions are signed with a key derived from `API_TOKEN` and `WEB_PASSWORD`, so +rotating either one logs every browser out. The session cookie lasts 60 days. + +--- + ## 2. Build + start ```bash diff --git a/backend/.dockerignore b/backend/.dockerignore index 723850f..84b07d1 100644 --- a/backend/.dockerignore +++ b/backend/.dockerignore @@ -1,5 +1,10 @@ -# Only go source + module files are needed in the build context. +# Only go source + module files, plus the go:embed'd templates/static +# directories, are needed in the build context. * !go.mod !go.sum !*.go +!templates/ +!templates/** +!static/ +!static/** diff --git a/backend/Dockerfile b/backend/Dockerfile index 6f8a527..c4b45cd 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -9,7 +9,11 @@ COPY go.mod go.sum ./ RUN go mod download # Then source (changes often). +# Source plus the go:embed'd assets. Missing either directory turns the embed +# directive into a build error, so both must be copied before `go build`. COPY *.go ./ +COPY templates/ ./templates/ +COPY static/ ./static/ # Static binary: pure-Go sqlite means CGO_ENABLED=0 -> no libc dependency. # -trimpath + -ldflags strip paths and debug info for a smaller image. diff --git a/backend/main.go b/backend/main.go index de900b8..117028b 100644 --- a/backend/main.go +++ b/backend/main.go @@ -18,6 +18,8 @@ type Config struct { AllowedOrigins []string DBPath string Port string + // WebPassword gates the browser UI. Empty disables the web routes entirely. + WebPassword string } func envOr(key, def string) string { @@ -29,9 +31,10 @@ func envOr(key, def string) string { func loadConfig() Config { c := Config{ - Token: os.Getenv("API_TOKEN"), - DBPath: envOr("DB_PATH", "/data/bookmarks.db"), - Port: envOr("PORT", "8080"), + Token: os.Getenv("API_TOKEN"), + DBPath: envOr("DB_PATH", "/data/bookmarks.db"), + Port: envOr("PORT", "8080"), + WebPassword: os.Getenv("WEB_PASSWORD"), } for _, o := range strings.Split(os.Getenv("ALLOWED_ORIGINS"), ",") { if o = strings.TrimSpace(o); o != "" { @@ -58,6 +61,17 @@ func newRouter(store *Store, cfg Config) http.Handler { mux.Handle("/bookmarks", auth) mux.Handle("/bookmarks/", auth) + // The browser UI is registered only when a password is configured, so a + // deployment that forgets WEB_PASSWORD exposes nothing rather than + // exposing an unprotected list. + if cfg.WebPassword != "" { + web, err := newWebHandler(store, cfg) + if err != nil { + log.Fatalf("web handler: %v", err) + } + web.register(mux) + } + return withCORS(cfg.AllowedOrigins, mux) } diff --git a/backend/session.go b/backend/session.go new file mode 100644 index 0000000..34d63c8 --- /dev/null +++ b/backend/session.go @@ -0,0 +1,188 @@ +package main + +import ( + "crypto/hmac" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" +) + +const ( + sessionCookieName = "mangabm_session" + // 60 days: long enough that a phone stays logged in between reading spells. + sessionTTL = 60 * 24 * time.Hour + // Domain separation, so the session key can never collide with any other + // use of the secrets it is derived from. Changing this string logs + // everyone out. + sessionKeyPurpose = "mangabm-web-session-v1" +) + +// sessionKey derives the cookie-signing key from both secrets. Sessions are +// stateless — there is no session table — so rotating either API_TOKEN or +// WEB_PASSWORD invalidates every outstanding cookie at once. The \x00 +// separator prevents the concatenation ambiguity a bare apiToken+webPassword +// would have (e.g. "ab"+"c" colliding with "a"+"bc"). +func sessionKey(apiToken, webPassword string) []byte { + sum := sha256.Sum256([]byte(apiToken + "\x00" + webPassword + sessionKeyPurpose)) + return sum[:] +} + +// signSession encodes ".". +func signSession(key []byte, expiryMs int64) string { + payload := strconv.FormatInt(expiryMs, 10) + return payload + "." + sessionMAC(key, payload) +} + +func sessionMAC(key []byte, payload string) string { + mac := hmac.New(sha256.New, key) + mac.Write([]byte(payload)) + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) +} + +// verifySession checks shape, then expiry, then the signature — in that order. +// The signature comparison is constant-time; the checks before it only look at +// data the holder already supplied, so their timing leaks nothing. +func verifySession(key []byte, value string, nowMs int64) bool { + payload, sig, ok := strings.Cut(value, ".") + if !ok { + return false + } + expiry, err := strconv.ParseInt(payload, 10, 64) + if err != nil || expiry <= nowMs { + return false + } + want := sessionMAC(key, payload) + return subtle.ConstantTimeCompare([]byte(sig), []byte(want)) == 1 +} + +// isHTTPS reports whether the browser's connection is encrypted. Behind Traefik +// the Go server itself speaks plain HTTP, so the forwarded header is the only +// signal; without this check the Secure cookie would never be set in +// production, and setting it unconditionally would break http://localhost dev. +func isHTTPS(r *http.Request) bool { + return r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" +} + +func setSessionCookie(w http.ResponseWriter, r *http.Request, key []byte) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: signSession(key, time.Now().Add(sessionTTL).UnixMilli()), + Path: "/", + MaxAge: int(sessionTTL / time.Second), + HttpOnly: true, + Secure: isHTTPS(r), + SameSite: http.SameSiteLaxMode, + }) +} + +func clearSessionCookie(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + Secure: isHTTPS(r), + SameSite: http.SameSiteLaxMode, + }) +} + +const ( + loginMaxFailures = 10 + loginWindow = 20 * time.Minute +) + +// clientIP returns the address the reverse proxy actually observed. +// +// Traefik appends the peer address to whatever X-Forwarded-For the client sent, +// so the leftmost entry is attacker-controlled and the rightmost is not. Go's +// Header.Get would only read the first header line, which a client can preempt +// by sending its own; Values covers every line so the true last hop is found. +// RemoteAddr is useless behind the proxy — it is always the Traefik container — +// so it serves only as the direct-connection fallback for local development. +func clientIP(r *http.Request) string { + if vals := r.Header.Values("X-Forwarded-For"); len(vals) > 0 { + hops := strings.Split(vals[len(vals)-1], ",") + if ip := strings.TrimSpace(hops[len(hops)-1]); ip != "" { + return ip + } + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} + +// loginLimiter throttles password guessing: loginMaxFailures failures inside a +// rolling loginWindow blocks further attempts from that IP until the oldest one +// ages out. There is no permanent ban and no unlock step. +// +// Behind carrier-grade NAT this budget is shared with every other subscriber on +// the same public address, so a stranger can lock the owner out for up to one +// window. That is accepted: the block self-heals, and ten attempts is generous +// for a mistyped password. +// +// State is in memory and per-process, so a restart clears it. Entries are +// pruned lazily on access; for a single-user deployment the map cannot grow +// past the handful of addresses that ever attempt a login. +type loginLimiter struct { + mu sync.Mutex + failures map[string][]time.Time +} + +func newLoginLimiter() *loginLimiter { + return &loginLimiter{failures: make(map[string][]time.Time)} +} + +// retryAfter returns how long ip must wait, or zero when it may try now. +func (l *loginLimiter) retryAfter(ip string, now time.Time) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + + recent := l.pruneLocked(ip, now) + if len(recent) < loginMaxFailures { + return 0 + } + return recent[0].Add(loginWindow).Sub(now) +} + +func (l *loginLimiter) fail(ip string, now time.Time) { + l.mu.Lock() + defer l.mu.Unlock() + l.failures[ip] = append(l.pruneLocked(ip, now), now) +} + +func (l *loginLimiter) reset(ip string) { + l.mu.Lock() + defer l.mu.Unlock() + delete(l.failures, ip) +} + +// pruneLocked drops attempts older than the window and returns what is left. +// The caller must hold l.mu. +func (l *loginLimiter) pruneLocked(ip string, now time.Time) []time.Time { + cutoff := now.Add(-loginWindow) + // In-place filter: kept reuses the backing array of the slice being + // ranged over. Safe to alias because append writes at index len(kept), + // which is always <= the range index i, and element i is read before + // that write — the write cursor can never overtake the read cursor. + kept := l.failures[ip][:0] + for _, at := range l.failures[ip] { + if at.After(cutoff) { + kept = append(kept, at) + } + } + if len(kept) == 0 { + delete(l.failures, ip) + return nil + } + l.failures[ip] = kept + return kept +} diff --git a/backend/session_test.go b/backend/session_test.go new file mode 100644 index 0000000..4c261b4 --- /dev/null +++ b/backend/session_test.go @@ -0,0 +1,232 @@ +package main + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestSessionRoundTrip(t *testing.T) { + key := sessionKey("token-abc", "pw-abc") + now := time.Now().UnixMilli() + value := signSession(key, now+60_000) + if !verifySession(key, value, now) { + t.Fatal("verifySession = false for a freshly signed cookie, want true") + } +} + +func TestSessionRejects(t *testing.T) { + key := sessionKey("token-abc", "pw-abc") + now := time.Now().UnixMilli() + valid := signSession(key, now+60_000) + payload, sig, _ := strings.Cut(valid, ".") + + cases := []struct { + name string + value string + }{ + {"empty", ""}, + {"no separator", payload + sig}, + {"unparseable expiry", "notanumber." + sig}, + {"expired", signSession(key, now-1)}, + {"tampered signature", payload + "." + flipLastChar(sig)}, + {"tampered expiry", "99999999999999." + sig}, + {"signed with another key", signSession(sessionKey("other-token", "pw-abc"), now+60_000)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if verifySession(key, tc.value, now) { + t.Fatalf("verifySession(%q) = true, want false", tc.value) + } + }) + } +} + +func flipLastChar(s string) string { + if s == "" { + return "x" + } + last := s[len(s)-1] + if last == 'A' { + return s[:len(s)-1] + "B" + } + return s[:len(s)-1] + "A" +} + +func TestSessionKeyDependsOnToken(t *testing.T) { + a := sessionKey("token-a", "pw-abc") + b := sessionKey("token-b", "pw-abc") + if string(a) == string(b) { + t.Fatal("sessionKey collided for different API tokens") + } +} + +func TestSessionKeyDependsOnWebPassword(t *testing.T) { + a := sessionKey("token-abc", "pw-a") + b := sessionKey("token-abc", "pw-b") + if string(a) == string(b) { + t.Fatal("sessionKey collided for different web passwords with the same API token") + } +} + +func TestSetSessionCookieAttributes(t *testing.T) { + cases := []struct { + name string + tls bool + forwarded string + wantSecure bool + }{ + {"plain http dev", false, "", false}, + {"direct tls", true, "", true}, + {"behind https proxy", false, "https", true}, + {"behind http proxy", false, "http", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodPost, "/login", nil) + if tc.tls { + r.TLS = &tls.ConnectionState{} + } + if tc.forwarded != "" { + r.Header.Set("X-Forwarded-Proto", tc.forwarded) + } + rr := httptest.NewRecorder() + setSessionCookie(rr, r, sessionKey("token-abc", "pw-abc")) + + cookies := rr.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("got %d cookies, want 1", len(cookies)) + } + c := cookies[0] + if c.Name != sessionCookieName { + t.Fatalf("cookie name = %q, want %q", c.Name, sessionCookieName) + } + if !c.HttpOnly { + t.Fatal("cookie HttpOnly = false, want true") + } + if c.SameSite != http.SameSiteLaxMode { + t.Fatalf("cookie SameSite = %v, want Lax", c.SameSite) + } + if c.Path != "/" { + t.Fatalf("cookie Path = %q, want /", c.Path) + } + if c.Secure != tc.wantSecure { + t.Fatalf("cookie Secure = %v, want %v", c.Secure, tc.wantSecure) + } + if c.MaxAge != int(sessionTTL/time.Second) { + t.Fatalf("cookie MaxAge = %d, want %d", c.MaxAge, int(sessionTTL/time.Second)) + } + }) + } +} + +func TestClearSessionCookie(t *testing.T) { + r := httptest.NewRequest(http.MethodPost, "/logout", nil) + rr := httptest.NewRecorder() + clearSessionCookie(rr, r) + + cookies := rr.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("got %d cookies, want 1", len(cookies)) + } + if cookies[0].MaxAge >= 0 { + t.Fatalf("cleared cookie MaxAge = %d, want negative", cookies[0].MaxAge) + } +} + +func TestClientIP(t *testing.T) { + cases := []struct { + name string + remoteAddr string + xff []string + want string + }{ + {"no header falls back to remote addr", "203.0.113.9:5555", nil, "203.0.113.9"}, + {"single proxy hop", "10.0.0.1:5555", []string{"203.0.113.9"}, "203.0.113.9"}, + { + // The client sent "1.2.3.4" itself; Traefik appended the address it + // actually saw. Only the rightmost entry is trustworthy. + name: "spoofed left entry is ignored", + remoteAddr: "10.0.0.1:5555", + xff: []string{"1.2.3.4, 203.0.113.9"}, + want: "203.0.113.9", + }, + { + name: "spoofed separate header line is ignored", + remoteAddr: "10.0.0.1:5555", + xff: []string{"1.2.3.4", "203.0.113.9"}, + want: "203.0.113.9", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodPost, "/login", nil) + r.RemoteAddr = tc.remoteAddr + for _, v := range tc.xff { + r.Header.Add("X-Forwarded-For", v) + } + if got := clientIP(r); got != tc.want { + t.Fatalf("clientIP() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestLoginLimiterBlocksAfterMaxFailures(t *testing.T) { + l := newLoginLimiter() + now := time.Now() + for i := 0; i < loginMaxFailures; i++ { + if wait := l.retryAfter("1.2.3.4", now); wait != 0 { + t.Fatalf("blocked after %d failures, want block only after %d", i, loginMaxFailures) + } + l.fail("1.2.3.4", now) + } + wait := l.retryAfter("1.2.3.4", now) + if wait <= 0 { + t.Fatalf("retryAfter = %v after %d failures, want > 0", wait, loginMaxFailures) + } + if wait > loginWindow { + t.Fatalf("retryAfter = %v, want <= %v", wait, loginWindow) + } +} + +func TestLoginLimiterWindowExpires(t *testing.T) { + l := newLoginLimiter() + start := time.Now() + for i := 0; i < loginMaxFailures; i++ { + l.fail("1.2.3.4", start) + } + if l.retryAfter("1.2.3.4", start) == 0 { + t.Fatal("expected block immediately after the failures") + } + later := start.Add(loginWindow + time.Second) + if wait := l.retryAfter("1.2.3.4", later); wait != 0 { + t.Fatalf("retryAfter = %v once the window passed, want 0", wait) + } +} + +func TestLoginLimiterResetClearsCounter(t *testing.T) { + l := newLoginLimiter() + now := time.Now() + for i := 0; i < loginMaxFailures; i++ { + l.fail("1.2.3.4", now) + } + l.reset("1.2.3.4") + if wait := l.retryAfter("1.2.3.4", now); wait != 0 { + t.Fatalf("retryAfter = %v after reset, want 0", wait) + } +} + +func TestLoginLimiterIsPerIP(t *testing.T) { + l := newLoginLimiter() + now := time.Now() + for i := 0; i < loginMaxFailures; i++ { + l.fail("1.2.3.4", now) + } + if wait := l.retryAfter("5.6.7.8", now); wait != 0 { + t.Fatalf("retryAfter for a different IP = %v, want 0", wait) + } +} diff --git a/backend/static/filter.js b/backend/static/filter.js new file mode 100644 index 0000000..61a45ae --- /dev/null +++ b/backend/static/filter.js @@ -0,0 +1,33 @@ +// Title search runs entirely in the browser: the full list is already in the +// DOM, so filtering it needs no request. +(function () { + function applyFilter() { + var box = document.getElementById("search"); + if (!box) return; + var needle = box.value.trim().toLowerCase(); + document.querySelectorAll(".card").forEach(function (card) { + var title = (card.dataset.title || "").toLowerCase(); + card.hidden = needle !== "" && title.indexOf(needle) === -1; + }); + } + + document.addEventListener("input", function (e) { + if (e.target && e.target.id === "search") applyFilter(); + }); + + // htmx replaces the list on a tab switch, so re-apply to the new cards. + document.body.addEventListener("htmx:afterSwap", applyFilter); +})(); + +function setActiveTab(el) { + el.parentElement.querySelectorAll("[role=tab]").forEach(function (t) { + t.classList.toggle("active", t === el); + }); +} + +function toggleChapterForm(key) { + var form = document.getElementById("chapter-form-" + key); + if (!form) return; + form.hidden = !form.hidden; + if (!form.hidden) form.querySelector("input").focus(); +} diff --git a/backend/static/htmx.min.js b/backend/static/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/backend/static/htmx.min.js @@ -0,0 +1 @@ +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=cn(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},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.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 te(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 ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(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 re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(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 q(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 A(e){const t=ne().createElement("script");se(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 N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");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){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(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=m(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 c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(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 ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;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=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(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(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(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=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().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 C(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=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(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){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(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=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(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(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(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;ct(ue(r),n,e)}else{pt(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 Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(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 It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(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 an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(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 dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;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{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(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(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(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 bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.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=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(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 On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(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 Ln(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 An(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)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(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 de(t,n,r,o,i,D){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=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,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(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(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;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(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){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/backend/static/style.css b/backend/static/style.css new file mode 100644 index 0000000..29f5d5e --- /dev/null +++ b/backend/static/style.css @@ -0,0 +1,225 @@ +/* Mobile first. Dark by default because manga reading happens at night; the + light branch follows the system preference. */ +:root { + color-scheme: dark light; + --bg: #14161a; + --surface: #1d2026; + --surface-2: #262a32; + --text: #e8eaed; + --muted: #9aa1ac; + --accent: #6aa9ff; + --danger: #ff6a6a; + --star: #ffc857; + --radius: 12px; +} + +@media (prefers-color-scheme: light) { + :root { + --bg: #f4f5f7; + --surface: #ffffff; + --surface-2: #eceef2; + --text: #1a1d22; + --muted: #5d646e; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + padding: 0 12px calc(24px + env(safe-area-inset-bottom)); + background: var(--bg); + color: var(--text); + font: 16px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +/* Every interactive element clears the 44px touch-target floor. */ +button, .primary, [role="tab"] { + min-height: 44px; + border-radius: var(--radius); + border: 0; + font: inherit; + cursor: pointer; +} + +/* --- login --- */ + +.login-body { + display: grid; + place-items: center; + min-height: 100dvh; +} + +.login-card { + width: min(380px, 100%); + padding: 24px; + background: var(--surface); + border-radius: var(--radius); +} + +.login-card h1 { margin: 0 0 20px; font-size: 1.25rem; } +.login-card label { display: block; margin-bottom: 6px; color: var(--muted); font-size: .875rem; } + +.login-card input { + width: 100%; + min-height: 44px; + padding: 0 12px; + margin-bottom: 12px; + background: var(--surface-2); + color: var(--text); + border: 1px solid transparent; + border-radius: var(--radius); + font: inherit; +} + +.login-card input:focus-visible { outline: 2px solid var(--accent); } +.login-card button { width: 100%; background: var(--accent); color: #0b1220; font-weight: 600; } +.error { margin: 0 0 12px; color: var(--danger); font-size: .875rem; } + +/* --- chrome --- */ + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 0; +} + +.topbar h1 { margin: 0; font-size: 1.125rem; } +.ghost { padding: 0 12px; background: var(--surface-2); color: var(--muted); } + +.search { + width: 100%; + min-height: 44px; + padding: 0 12px; + margin-bottom: 12px; + background: var(--surface); + color: var(--text); + border: 1px solid transparent; + border-radius: var(--radius); + font: inherit; +} + +.search:focus-visible { outline: 2px solid var(--accent); } + +.tabs { display: flex; gap: 8px; margin-bottom: 16px; } + +.tabs [role="tab"] { + flex: 1; + display: grid; + place-items: center; + background: var(--surface); + color: var(--muted); + text-decoration: none; +} + +.tabs [role="tab"].active { background: var(--accent); color: #0b1220; font-weight: 600; } + +/* --- continue reading --- */ + +.recent h2 { margin: 0 0 8px; font-size: .8125rem; text-transform: uppercase; color: var(--muted); } + +.recent-strip { + display: flex; + gap: 10px; + overflow-x: auto; + padding-bottom: 8px; + margin-bottom: 16px; + scroll-snap-type: x mandatory; + -webkit-overflow-scrolling: touch; +} + +.recent-card { + flex: 0 0 110px; + scroll-snap-align: start; + display: block; + padding: 8px; + background: var(--surface); + border-radius: var(--radius); + color: var(--text); + text-decoration: none; +} + +.recent-card img { width: 100%; aspect-ratio: 3 / 4; object-fit: cover; border-radius: 8px; } +.recent-title { display: block; margin-top: 6px; font-size: .8125rem; line-height: 1.25; + overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } +.recent-chapter { display: block; color: var(--muted); font-size: .75rem; } + +/* --- list --- */ + +.list { display: grid; gap: 10px; } + +.card { + display: grid; + grid-template-columns: 72px 1fr; + gap: 12px; + padding: 10px; + background: var(--surface); + border-radius: var(--radius); +} + +.card .cover img { width: 72px; aspect-ratio: 3 / 4; object-fit: cover; border-radius: 8px; } +.card .body { min-width: 0; } +.card .title { margin: 0 0 4px; font-size: 1rem; line-height: 1.25; } + +.meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 0 0 10px; + font-size: .75rem; color: var(--muted); } + +.site { padding: 2px 6px; background: var(--surface-2); border-radius: 6px; text-transform: uppercase; } +.new { padding: 2px 6px; background: var(--accent); color: #0b1220; border-radius: 6px; font-weight: 700; } + +.actions { display: flex; flex-wrap: wrap; gap: 8px; } + +.primary { + flex: 1 1 auto; + display: grid; + place-items: center; + padding: 0 14px; + background: var(--accent); + color: #0b1220; + font-weight: 600; + text-decoration: none; +} + +.icon { width: 44px; background: var(--surface-2); color: var(--text); font-size: 1.125rem; } +.icon.on { color: var(--star); } +.icon.danger { color: var(--danger); } + +.chapter-form { display: flex; gap: 8px; margin-top: 8px; } + +.chapter-form input { + flex: 1; + min-height: 44px; + padding: 0 12px; + background: var(--surface-2); + color: var(--text); + border: 1px solid transparent; + border-radius: var(--radius); + font: inherit; +} + +.chapter-form button { padding: 0 14px; background: var(--accent); color: #0b1220; font-weight: 600; } +.empty { padding: 32px 12px; text-align: center; color: var(--muted); } + +/* Cards hidden by the search filter. The .chapter-form { display: flex } + rule above has equal specificity to the UA [hidden] rule, so without this + override the form stays visible even when the hidden attribute is set. */ +.card[hidden] { display: none; } +.chapter-form[hidden] { display: none; } + +/* --- wide screens --- */ + +@media (min-width: 900px) { + body { max-width: 1100px; margin: 0 auto; padding-inline: 24px; } + .list { grid-template-columns: repeat(2, 1fr); } + .recent-card { flex-basis: 140px; } +} + +@media (min-width: 1300px) { + .list { grid-template-columns: repeat(3, 1fr); } +} + +@media (prefers-reduced-motion: reduce) { + * { animation: none !important; transition: none !important; } +} diff --git a/backend/store.go b/backend/store.go index dc8a09a..7588509 100644 --- a/backend/store.go +++ b/backend/store.go @@ -2,6 +2,7 @@ package main import ( "database/sql" + "errors" "fmt" "strings" @@ -28,6 +29,22 @@ type Bookmark struct { UpdatedAt int64 `json:"updated_at"` // unix ms; see Upsert } +// HasNewChapter reports whether the site has published past the read point. +// A nil LatestChapterNum means nothing has been captured yet, which is not the +// same as "nothing new". +func (b Bookmark) HasNewChapter() bool { + return b.LatestChapterNum != nil && *b.LatestChapterNum > b.LastChapterNum +} + +// ContinueURL is where the Continue button points: the chapter last read, or +// the series page when no chapter URL was ever captured. +func (b Bookmark) ContinueURL() string { + if b.LastChapterURL != "" { + return b.LastChapterURL + } + return b.SeriesURL +} + const schema = ` CREATE TABLE IF NOT EXISTS bookmarks ( key TEXT PRIMARY KEY, @@ -182,6 +199,21 @@ func (s *Store) List() ([]Bookmark, error) { return out, rows.Err() } +// Get returns one bookmark by key. A missing key is not an error: ok is false +// and err is nil. UI mutations read-modify-write through this so they preserve +// the fields they do not touch. +func (s *Store) Get(key string) (Bookmark, bool, error) { + b, err := scanBookmark(s.db.QueryRow( + `SELECT `+bookmarkColumns+` FROM bookmarks WHERE key = ?`, key).Scan) + if errors.Is(err, sql.ErrNoRows) { + return Bookmark{}, false, nil + } + if err != nil { + return Bookmark{}, false, fmt.Errorf("get %q: %w", key, err) + } + return b, true, nil +} + // Upsert inserts or replaces a bookmark by key (last-write-wins) and returns // the row as actually stored. // diff --git a/backend/store_test.go b/backend/store_test.go index 8c8b081..1a442ee 100644 --- a/backend/store_test.go +++ b/backend/store_test.go @@ -34,6 +34,16 @@ func newTestServer(t *testing.T) http.Handler { return newRouter(store, testConfig()) } +func newTestStore(t *testing.T) *Store { + t.Helper() + store, err := OpenStore(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + t.Cleanup(func() { store.Close() }) + return store +} + func auth(req *http.Request) *http.Request { req.Header.Set("Authorization", "Bearer "+testToken) return req @@ -433,3 +443,88 @@ func TestOpenStoreMigratesLegacySchema(t *testing.T) { } store2.Close() } + +func TestStoreGet(t *testing.T) { + store := newTestStore(t) + if _, err := store.Upsert(Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapterNum: 45, UpdatedAt: 1000, + }); err != nil { + t.Fatalf("Upsert: %v", err) + } + + got, ok, err := store.Get("asura:solo") + if err != nil { + t.Fatalf("Get: %v", err) + } + if !ok { + t.Fatal("Get ok = false, want true") + } + if got.Title != "Solo Leveling" || got.LastChapterNum != 45 { + t.Fatalf("Get = %+v, want title/chapter preserved", got) + } +} + +func TestStoreGetMissing(t *testing.T) { + store := newTestStore(t) + _, ok, err := store.Get("asura:nope") + if err != nil { + t.Fatalf("Get missing returned error %v, want nil", err) + } + if ok { + t.Fatal("Get ok = true for missing key, want false") + } +} + +func TestBookmarkHasNewChapter(t *testing.T) { + num := func(f float64) *float64 { return &f } + cases := []struct { + name string + b Bookmark + want bool + }{ + {"latest ahead", Bookmark{LastChapterNum: 45, LatestChapterNum: num(47)}, true}, + {"latest equal", Bookmark{LastChapterNum: 45, LatestChapterNum: num(45)}, false}, + {"latest behind", Bookmark{LastChapterNum: 45, LatestChapterNum: num(44)}, false}, + {"latest unknown", Bookmark{LastChapterNum: 45}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.b.HasNewChapter(); got != tc.want { + t.Fatalf("HasNewChapter() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestBookmarkContinueURL(t *testing.T) { + cases := []struct { + name string + b Bookmark + want string + }{ + {"chapter url present", Bookmark{LastChapterURL: "/ch/45", SeriesURL: "/series"}, "/ch/45"}, + {"falls back to series", Bookmark{SeriesURL: "/series"}, "/series"}, + {"both empty", Bookmark{}, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.b.ContinueURL(); got != tc.want { + t.Fatalf("ContinueURL() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestLoadConfigWebPassword(t *testing.T) { + t.Setenv("API_TOKEN", "token-abc") + t.Setenv("WEB_PASSWORD", "hunter2") + if got := loadConfig().WebPassword; got != "hunter2" { + t.Fatalf("WebPassword = %q, want hunter2", got) + } + + t.Setenv("WEB_PASSWORD", "") + if got := loadConfig().WebPassword; got != "" { + t.Fatalf("WebPassword = %q with the variable unset, want empty", got) + } +} diff --git a/backend/templates/app.html b/backend/templates/app.html new file mode 100644 index 0000000..75cacbf --- /dev/null +++ b/backend/templates/app.html @@ -0,0 +1,53 @@ +{{define "app"}} + + + + + + + mangaBookmark + + + + + +
+

mangaBookmark

+
+ +
+
+ + + +
+ + {{if .Recent}} +
+

Continue reading

+ +
+ {{end}} + +
+ {{template "list" .}} +
+ + +{{end}} diff --git a/backend/templates/card.html b/backend/templates/card.html new file mode 100644 index 0000000..a7e19ef --- /dev/null +++ b/backend/templates/card.html @@ -0,0 +1,37 @@ +{{define "card"}} +
+ + {{if .Cover}}{{end}} + +
+

{{.Title}}

+

+ {{.Site}} + Ch {{.LastChapter}} + {{if .HasNewChapter}}NEW {{.LatestChapter}}{{end}} +

+
+ Continue + + + +
+ +
+
+{{end}} diff --git a/backend/templates/list.html b/backend/templates/list.html new file mode 100644 index 0000000..2a5dcd8 --- /dev/null +++ b/backend/templates/list.html @@ -0,0 +1,9 @@ +{{define "list"}} +{{if .Items}} + {{range .Items}}{{template "card" .}}{{end}} +{{else}} +

+ Nothing here yet. Bookmarks appear once the userscript records a chapter. +

+{{end}} +{{end}} diff --git a/backend/templates/login.html b/backend/templates/login.html new file mode 100644 index 0000000..d3e9e82 --- /dev/null +++ b/backend/templates/login.html @@ -0,0 +1,24 @@ +{{define "login"}} + + + + + + + mangaBookmark + + + +
+

mangaBookmark

+
+ + + {{if .Error}}

{{.Error}}

{{end}} + +
+
+ + +{{end}} diff --git a/backend/web.go b/backend/web.go new file mode 100644 index 0000000..d712a42 --- /dev/null +++ b/backend/web.go @@ -0,0 +1,306 @@ +package main + +import ( + "crypto/subtle" + "embed" + "html/template" + "io/fs" + "log" + "math" + "net/http" + "strconv" + "strings" + "time" +) + +//go:embed templates +var templateFS embed.FS + +//go:embed static +var staticFS embed.FS + +// recentCount is how many series the "Continue reading" strip shows. +const recentCount = 5 + +// webHandler serves the browser UI: full pages at / and htmx fragments at /ui/. +// It is a separate handler from bookmarkHandler because the two speak different +// representations (HTML versus JSON) to different clients under different auth. +type webHandler struct { + store *Store + tmpl *template.Template + key []byte + password string + limiter *loginLimiter +} + +// listView is what every list-rendering template receives. +type listView struct { + Tab string // "all" or "fav" + Recent []Bookmark + Items []Bookmark +} + +// loginView is what the login template receives. +type loginView struct { + Error string +} + +// newWebHandler parses every template up front so a broken one kills the +// process at startup rather than the first request that touches it. +func newWebHandler(store *Store, cfg Config) (*webHandler, error) { + tmpl, err := template.ParseFS(templateFS, "templates/*.html") + if err != nil { + return nil, err + } + return &webHandler{ + store: store, + tmpl: tmpl, + key: sessionKey(cfg.Token, cfg.WebPassword), + password: cfg.WebPassword, + limiter: newLoginLimiter(), + }, nil +} + +func (h *webHandler) register(mux *http.ServeMux) { + mux.HandleFunc("GET /{$}", h.index) + mux.HandleFunc("POST /login", h.login) + mux.HandleFunc("POST /logout", h.logout) + mux.Handle("GET /static/", staticHandler()) + + mux.HandleFunc("GET /ui/list", h.requireSession(h.uiList)) + mux.HandleFunc("POST /ui/bookmarks/{key}/favorite", h.requireSession(h.uiFavorite)) + mux.HandleFunc("POST /ui/bookmarks/{key}/chapter", h.requireSession(h.uiChapter)) + mux.HandleFunc("DELETE /ui/bookmarks/{key}", h.requireSession(h.uiDelete)) +} + +// staticHandler serves the embedded assets. An hour, not longer: assets are +// not fingerprinted, and embed.FS reports a zero ModTime, so http.FileServer +// emits no Last-Modified or ETag and a client has no way to revalidate a +// cached copy after a deploy short of waiting out max-age. +func staticHandler() http.Handler { + sub, err := fs.Sub(staticFS, "static") + if err != nil { + panic("embed static: " + err.Error()) + } + files := http.FileServer(http.FS(sub)) + return http.StripPrefix("/static/", http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "public, max-age=3600") + files.ServeHTTP(w, r) + })) +} + +// authed reports whether the request carries a valid session cookie. +func (h *webHandler) authed(r *http.Request) bool { + c, err := r.Cookie(sessionCookieName) + return err == nil && verifySession(h.key, c.Value, time.Now().UnixMilli()) +} + +// requireSession guards the fragment endpoints. It answers 401 rather than +// redirecting, because htmx swaps whatever body it receives into the page and a +// redirected login page would be spliced into the card list. +func (h *webHandler) requireSession(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !h.authed(r) { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + next(w, r) + } +} + +func (h *webHandler) render(w http.ResponseWriter, status int, name string, data any) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + if err := h.tmpl.ExecuteTemplate(w, name, data); err != nil { + // The status line is already sent, so this can only be logged. + log.Printf("render %s: %v", name, err) + } +} + +// index renders the list, or the login page when there is no session. The login +// page is served at / with status 200 rather than as a redirect to a separate +// URL: one page, no redirect loop to reason about. +func (h *webHandler) index(w http.ResponseWriter, r *http.Request) { + if !h.authed(r) { + h.render(w, http.StatusOK, "login", loginView{}) + return + } + view, err := h.buildListView(r.URL.Query().Get("tab")) + if err != nil { + log.Printf("index: %v", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + h.render(w, http.StatusOK, "app", view) +} + +// buildListView loads the list once and derives both the tab-filtered items and +// the recent strip from it. The strip always reflects overall recency, not the +// active tab, so it is built before filtering. +func (h *webHandler) buildListView(tab string) (listView, error) { + all, err := h.store.List() // already ordered updated_at DESC + if err != nil { + return listView{}, err + } + + recent := all + if len(recent) > recentCount { + recent = recent[:recentCount] + } + + items := all + if tab == "fav" { + items = []Bookmark{} + for _, b := range all { + if b.Favorite { + items = append(items, b) + } + } + } else { + tab = "all" + } + return listView{Tab: tab, Recent: recent, Items: items}, nil +} + +func (h *webHandler) uiList(w http.ResponseWriter, r *http.Request) { + view, err := h.buildListView(r.URL.Query().Get("tab")) + if err != nil { + log.Printf("ui list: %v", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + h.render(w, http.StatusOK, "list", view) +} + +func (h *webHandler) login(w http.ResponseWriter, r *http.Request) { + ip := clientIP(r) + if wait := h.limiter.retryAfter(ip, time.Now()); wait > 0 { + secs := int(wait.Seconds()) + 1 + w.Header().Set("Retry-After", strconv.Itoa(secs)) + h.render(w, http.StatusTooManyRequests, "login", loginView{ + Error: "Too many attempts. Try again in " + + strconv.Itoa((secs+59)/60) + " min.", + }) + return + } + + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + got := r.PostFormValue("password") + if subtle.ConstantTimeCompare([]byte(got), []byte(h.password)) != 1 { + h.limiter.fail(ip, time.Now()) + h.render(w, http.StatusUnauthorized, "login", loginView{Error: "Wrong password."}) + return + } + + h.limiter.reset(ip) + setSessionCookie(w, r, h.key) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (h *webHandler) logout(w http.ResponseWriter, r *http.Request) { + clearSessionCookie(w, r) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +// loadForMutation fetches the row a mutation targets, writing the error +// response itself when there is nothing to mutate. +func (h *webHandler) loadForMutation(w http.ResponseWriter, r *http.Request) (Bookmark, bool) { + key := r.PathValue("key") + if key == "" { + http.Error(w, "missing key", http.StatusBadRequest) + return Bookmark{}, false + } + b, ok, err := h.store.Get(key) + if err != nil { + log.Printf("ui get %q: %v", key, err) + http.Error(w, "internal error", http.StatusInternalServerError) + return Bookmark{}, false + } + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return Bookmark{}, false + } + return b, true +} + +// saveAndRenderCard upserts and renders the row as stored. Upsert decides +// whether updated_at moves, so the argument's timestamp is only a candidate and +// the response must come from the return value. +func (h *webHandler) saveAndRenderCard(w http.ResponseWriter, b Bookmark) { + stored, err := h.store.Upsert(b) + if err != nil { + log.Printf("ui upsert %q: %v", b.Key, err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + h.render(w, http.StatusOK, "card", stored) +} + +// uiFavorite flips the favourite flag. last_chapter_num is untouched, so +// Upsert keeps the stored updated_at and the list does not reorder. +func (h *webHandler) uiFavorite(w http.ResponseWriter, r *http.Request) { + b, ok := h.loadForMutation(w, r) + if !ok { + return + } + b.Favorite = !b.Favorite + b.UpdatedAt = time.Now().UnixMilli() + h.saveAndRenderCard(w, b) +} + +// uiChapter forces the read chapter to a value the user typed. +// +// Writing the number also clears last_chapter_url: that URL points at the +// chapter actually read, and once the number is forced elsewhere it would send +// the reader backwards. ContinueURL then falls back to the series page, which +// is always right. +// +// A submit that does not change the number touches nothing. The form is +// pre-filled, so a bare tap of Save is an easy accidental submit; it must not +// destroy last_chapter_url, nor rewrite the last_chapter display string ("45.0" +// to "45") behind a frozen updated_at. +func (h *webHandler) uiChapter(w http.ResponseWriter, r *http.Request) { + b, ok := h.loadForMutation(w, r) + if !ok { + return + } + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + raw := strings.TrimSpace(r.PostFormValue("chapter")) + num, err := strconv.ParseFloat(raw, 64) + if err != nil || num < 0 || math.IsNaN(num) || math.IsInf(num, 0) { + http.Error(w, "chapter must be a non-negative number", http.StatusBadRequest) + return + } + + if num != b.LastChapterNum { + b.LastChapterURL = "" + b.LastChapter = raw + b.LastChapterNum = num + } + b.UpdatedAt = time.Now().UnixMilli() + h.saveAndRenderCard(w, b) +} + +// uiDelete removes the row and answers with an empty body, which htmx swaps in +// place of the card — removing it from the page. +func (h *webHandler) uiDelete(w http.ResponseWriter, r *http.Request) { + key := r.PathValue("key") + if key == "" { + http.Error(w, "missing key", http.StatusBadRequest) + return + } + if err := h.store.Delete(key); err != nil { + log.Printf("ui delete %q: %v", key, err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusOK) +} diff --git a/backend/web_test.go b/backend/web_test.go new file mode 100644 index 0000000..c4e81ce --- /dev/null +++ b/backend/web_test.go @@ -0,0 +1,485 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +const testPassword = "hunter2" + +func webConfig() Config { + cfg := testConfig() + cfg.WebPassword = testPassword + return cfg +} + +// newWebTestServer returns the full router plus the store behind it, so tests +// can seed rows and assert on what the handlers wrote back. +func newWebTestServer(t *testing.T, cfg Config) (http.Handler, *Store) { + t.Helper() + store, err := OpenStore(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + t.Cleanup(func() { store.Close() }) + return newRouter(store, cfg), store +} + +// sessionCookie returns a cookie a handler will accept for cfg's API token. +func sessionCookie(t *testing.T, cfg Config) *http.Cookie { + t.Helper() + return &http.Cookie{ + Name: sessionCookieName, + Value: signSession(sessionKey(cfg.Token, cfg.WebPassword), time.Now().Add(time.Hour).UnixMilli()), + } +} + +func TestIndexWithoutSessionShowsLogin(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/", nil)) + + if rr.Code != http.StatusOK { + t.Fatalf("GET / status = %d, want 200", rr.Code) + } + if !strings.Contains(rr.Body.String(), `type="password"`) { + t.Fatal("GET / without a session did not render the password field") + } +} + +func TestIndexWithSessionShowsList(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + if _, err := store.Upsert(Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + UpdatedAt: time.Now().UnixMilli(), + }); err != nil { + t.Fatalf("Upsert: %v", err) + } + + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.AddCookie(sessionCookie(t, cfg)) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusOK { + t.Fatalf("GET / status = %d, want 200", rr.Code) + } + if !strings.Contains(rr.Body.String(), "Solo Leveling") { + t.Fatal("GET / with a session did not render the bookmark title") + } +} + +func TestLoginSuccessSetsCookie(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + req := httptest.NewRequest(http.MethodPost, "/login", + strings.NewReader(url.Values{"password": {testPassword}}.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusSeeOther { + t.Fatalf("POST /login status = %d, want 303", rr.Code) + } + cookies := rr.Result().Cookies() + if len(cookies) != 1 || cookies[0].Name != sessionCookieName || cookies[0].Value == "" { + t.Fatalf("POST /login cookies = %+v, want one non-empty %s", cookies, sessionCookieName) + } +} + +func TestLoginWrongPassword(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + req := httptest.NewRequest(http.MethodPost, "/login", + strings.NewReader(url.Values{"password": {"wrong"}}.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Fatalf("POST /login status = %d, want 401", rr.Code) + } + if len(rr.Result().Cookies()) != 0 { + t.Fatal("a failed login set a cookie") + } +} + +func TestLoginRateLimited(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + post := func() *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/login", + strings.NewReader(url.Values{"password": {"wrong"}}.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("X-Forwarded-For", "203.0.113.9") + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + return rr + } + for i := 0; i < loginMaxFailures; i++ { + if code := post().Code; code != http.StatusUnauthorized { + t.Fatalf("attempt %d status = %d, want 401", i+1, code) + } + } + rr := post() + if rr.Code != http.StatusTooManyRequests { + t.Fatalf("attempt %d status = %d, want 429", loginMaxFailures+1, rr.Code) + } + if after := rr.Header().Get("Retry-After"); after == "" { + t.Fatal("429 response has no Retry-After header") + } else if n, err := strconv.Atoi(after); err != nil || n <= 0 { + t.Fatalf("Retry-After = %q, want a positive integer", after) + } +} + +func TestLogoutClearsCookie(t *testing.T) { + cfg := webConfig() + srv, _ := newWebTestServer(t, cfg) + req := httptest.NewRequest(http.MethodPost, "/logout", nil) + req.AddCookie(sessionCookie(t, cfg)) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusSeeOther { + t.Fatalf("POST /logout status = %d, want 303", rr.Code) + } + cookies := rr.Result().Cookies() + if len(cookies) != 1 || cookies[0].MaxAge >= 0 { + t.Fatalf("POST /logout cookies = %+v, want one expiring cookie", cookies) + } +} + +func TestWebDisabledWhenNoPassword(t *testing.T) { + cfg := testConfig() // WebPassword empty + srv, _ := newWebTestServer(t, cfg) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/", nil)) + + if rr.Code != http.StatusNotFound { + t.Fatalf("GET / with WEB_PASSWORD unset = %d, want 404", rr.Code) + } +} + +func TestBookmarksAPIStillBearerOnly(t *testing.T) { + cfg := webConfig() + srv, _ := newWebTestServer(t, cfg) + + // A session cookie must not grant access to the userscript's JSON API. + req := httptest.NewRequest(http.MethodGet, "/bookmarks", nil) + req.AddCookie(sessionCookie(t, cfg)) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + if rr.Code != http.StatusUnauthorized { + t.Fatalf("GET /bookmarks with only a cookie = %d, want 401", rr.Code) + } + + // And the bearer token must still work. + rr = httptest.NewRecorder() + srv.ServeHTTP(rr, auth(httptest.NewRequest(http.MethodGet, "/bookmarks", nil))) + if rr.Code != http.StatusOK { + t.Fatalf("GET /bookmarks with bearer = %d, want 200", rr.Code) + } +} + +func TestStaticAssetsServed(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + for _, path := range []string{"/static/style.css", "/static/htmx.min.js", "/static/filter.js"} { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil)) + if rr.Code != http.StatusOK { + t.Fatalf("GET %s = %d, want 200", path, rr.Code) + } + if rr.Body.Len() == 0 { + t.Fatalf("GET %s returned an empty body", path) + } + } +} + +// seed inserts one bookmark and returns it as stored. +func seed(t *testing.T, store *Store, b Bookmark) Bookmark { + t.Helper() + stored, err := store.Upsert(b) + if err != nil { + t.Fatalf("Upsert: %v", err) + } + return stored +} + +func uiRequest(t *testing.T, cfg Config, method, path string, form url.Values) *http.Request { + t.Helper() + var req *http.Request + if form == nil { + req = httptest.NewRequest(method, path, nil) + } else { + req = httptest.NewRequest(method, path, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + req.AddCookie(sessionCookie(t, cfg)) + return req +} + +func TestUIRoutesRequireSession(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + cases := []struct{ method, path string }{ + {http.MethodGet, "/ui/list"}, + {http.MethodPost, "/ui/bookmarks/asura:solo/favorite"}, + {http.MethodPost, "/ui/bookmarks/asura:solo/chapter"}, + {http.MethodDelete, "/ui/bookmarks/asura:solo"}, + } + for _, tc := range cases { + t.Run(tc.method+" "+tc.path, func(t *testing.T) { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(tc.method, tc.path, nil)) + if rr.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401", rr.Code) + } + }) + } +} + +func TestFavoriteTogglesWithoutReordering(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + before := seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:solo/favorite", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("favorite status = %d, want 200", rr.Code) + } + + after, ok, err := store.Get("asura:solo") + if err != nil || !ok { + t.Fatalf("Get after favorite: %v ok=%v", err, ok) + } + if !after.Favorite { + t.Fatal("Favorite = false after toggling, want true") + } + if after.UpdatedAt != before.UpdatedAt { + t.Fatalf("UpdatedAt moved from %d to %d; favouriting must not reorder the list", + before.UpdatedAt, after.UpdatedAt) + } + if !strings.Contains(rr.Body.String(), `id="card-asura:solo"`) { + t.Fatal("favorite response did not render the card fragment") + } + + // Toggling again turns it back off. + rr = httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:solo/favorite", nil)) + back, _, _ := store.Get("asura:solo") + if back.Favorite { + t.Fatal("Favorite = true after a second toggle, want false") + } +} + +// TestCardHxTargetIsValidSelectorForColonKey asserts the rendered card's +// hx-target attributes use the fixed-string attribute-selector form +// ([id='card-']) rather than a bare CSS id-selector (#card-). +// +// A key like "asura:solo" makes "#card-asura:solo" an invalid CSS selector: +// the browser parses ":solo" as an unrecognised pseudo-class and htmx's +// querySelectorAll throws SyntaxError, so the button never resolves its +// swap target. httptest never executes htmx, so this only checks the +// rendered attribute's shape — it is not proof the browser accepts the +// selector, just a regression guard against reintroducing the bare-id form. +func TestCardHxTargetIsValidSelectorForColonKey(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodGet, "/ui/list", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rr.Code) + } + body := rr.Body.String() + + want := `hx-target="[id='card-asura:solo']"` + if strings.Count(body, want) != 3 { + t.Fatalf("body has %d occurrences of %s, want 3 (favorite button, delete button, chapter form)", + strings.Count(body, want), want) + } + if strings.Contains(body, `hx-target="#card-asura:solo"`) { + t.Fatal("body still uses the bare id CSS selector, which is invalid for a key containing ':'") + } +} + +func TestChapterOverrideMovesUpdatedAt(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + before := seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + LastChapterURL: "https://example.test/ch/45", SeriesURL: "https://example.test/solo", + UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, + "/ui/bookmarks/asura:solo/chapter", url.Values{"chapter": {"60"}})) + if rr.Code != http.StatusOK { + t.Fatalf("chapter override status = %d, want 200", rr.Code) + } + + after, ok, err := store.Get("asura:solo") + if err != nil || !ok { + t.Fatalf("Get after override: %v ok=%v", err, ok) + } + if after.LastChapterNum != 60 || after.LastChapter != "60" { + t.Fatalf("chapter = %q/%v, want 60", after.LastChapter, after.LastChapterNum) + } + if after.UpdatedAt <= before.UpdatedAt { + t.Fatalf("UpdatedAt = %d, want later than %d", after.UpdatedAt, before.UpdatedAt) + } + if after.LastChapterURL != "" { + t.Fatalf("LastChapterURL = %q, want cleared by a manual override", after.LastChapterURL) + } + if after.Title != "Solo Leveling" { + t.Fatalf("Title = %q, want the untouched fields preserved", after.Title) + } +} + +func TestChapterOverrideNoOpPreservesURLAndUpdatedAt(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + before := seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45.0", LastChapterNum: 45, + LastChapterURL: "https://example.test/ch/45", SeriesURL: "https://example.test/solo", + UpdatedAt: 1_000_000, + }) + + // The chapter form is pre-filled with the current value, so tapping Save + // without editing resubmits the unchanged number. That must be a no-op: it + // must not clear last_chapter_url, rewrite the last_chapter display string, + // or move updated_at. The seed stores "45.0" against 45 so the display + // string differs from what the form submits back. + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, + "/ui/bookmarks/asura:solo/chapter", url.Values{"chapter": {"45"}})) + if rr.Code != http.StatusOK { + t.Fatalf("chapter no-op status = %d, want 200", rr.Code) + } + + after, ok, err := store.Get("asura:solo") + if err != nil || !ok { + t.Fatalf("Get after no-op override: %v ok=%v", err, ok) + } + if after.LastChapterURL != before.LastChapterURL { + t.Fatalf("LastChapterURL = %q, want preserved %q on a no-op save", + after.LastChapterURL, before.LastChapterURL) + } + if after.LastChapter != before.LastChapter { + t.Fatalf("LastChapter = %q, want preserved %q on a no-op save", + after.LastChapter, before.LastChapter) + } + if after.UpdatedAt != before.UpdatedAt { + t.Fatalf("UpdatedAt = %d, want unchanged %d on a no-op save", + after.UpdatedAt, before.UpdatedAt) + } +} + +func TestChapterOverrideRejectsBadInput(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapterNum: 45, UpdatedAt: 1_000_000, + }) + + for _, bad := range []string{"", "abc", "-3", "NaN", "Infinity", "-Inf"} { + t.Run("input "+bad, func(t *testing.T) { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, + "/ui/bookmarks/asura:solo/chapter", url.Values{"chapter": {bad}})) + if rr.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", rr.Code) + } + after, _, _ := store.Get("asura:solo") + if after.LastChapterNum != 45 { + t.Fatalf("chapter changed to %v on invalid input", after.LastChapterNum) + } + }) + } +} + +func TestMutationsOnMissingKey(t *testing.T) { + cfg := webConfig() + srv, _ := newWebTestServer(t, cfg) + cases := []struct { + name string + req *http.Request + }{ + {"favorite", uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:nope/favorite", nil)}, + {"chapter", uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:nope/chapter", url.Values{"chapter": {"1"}})}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, tc.req) + if rr.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", rr.Code) + } + }) + } +} + +func TestUIDeleteRemovesRow(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodDelete, "/ui/bookmarks/asura:solo", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("delete status = %d, want 200", rr.Code) + } + if rr.Body.Len() != 0 { + t.Fatalf("delete body = %q, want empty so htmx swaps the card away", rr.Body.String()) + } + if _, ok, _ := store.Get("asura:solo"); ok { + t.Fatal("row still present after delete") + } +} + +func TestUIListFavouritesTab(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", Favorite: true, UpdatedAt: 2_000_000, + }) + seed(t, store, Bookmark{ + Key: "demonic:tower", Site: "demonic", SeriesID: "tower", + Title: "Tower of God", Favorite: false, UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodGet, "/ui/list?tab=fav", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rr.Code) + } + body := rr.Body.String() + if !strings.Contains(body, "Solo Leveling") { + t.Fatal("favourites tab omitted the favourited series") + } + if strings.Contains(body, "Tower of God") { + t.Fatal("favourites tab included a non-favourite") + } +} diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 968c2ef..78bc45b 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -5,6 +5,7 @@ # # Set in .env: # MANGA_API_HOST=manga-api.example.com # your subdomain (required) +# MANGA_WEB_HOST=manga.example.com # browser UI subdomain, same container (required) # PROXY_NETWORK=proxy # Traefik's network name, if not "proxy" # TRAEFIK_ENTRYPOINT=websecure # your HTTPS entrypoint name # TRAEFIK_CERTRESOLVER=le # your ACME/cert resolver name @@ -26,6 +27,14 @@ services: - "traefik.http.routers.mangabm.tls=true" - "traefik.http.routers.mangabm.tls.certresolver=${TRAEFIK_CERTRESOLVER:-le}" - "traefik.http.services.mangabm.loadbalancer.server.port=8080" + # Second hostname for the browser UI, same container. Traefik needs the + # service named explicitly once more than one router targets it. + - "traefik.http.routers.mangabm.service=mangabm" + - "traefik.http.routers.mangaweb.rule=Host(`${MANGA_WEB_HOST:?set MANGA_WEB_HOST in .env}`)" + - "traefik.http.routers.mangaweb.entrypoints=${TRAEFIK_ENTRYPOINT:-websecure}" + - "traefik.http.routers.mangaweb.tls=true" + - "traefik.http.routers.mangaweb.tls.certresolver=${TRAEFIK_CERTRESOLVER:-le}" + - "traefik.http.routers.mangaweb.service=mangabm" networks: proxy: diff --git a/docker-compose.yml b/docker-compose.yml index 8f1487d..8436895 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -18,6 +18,8 @@ services: ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://asuracomic.net,https://asurascans.com,https://demonicscans.org} DB_PATH: /data/bookmarks.db PORT: "8080" + # Gates the browser UI. Unset means the web routes are not served at all. + WEB_PASSWORD: ${WEB_PASSWORD:-} volumes: - bookmarks-data:/data # Bound to loopback only: the proxy (or curl during smoke test) reaches it, diff --git a/docs/superpowers/specs/2026-07-25-web-ui-design.md b/docs/superpowers/specs/2026-07-25-web-ui-design.md new file mode 100644 index 0000000..e82cd9d --- /dev/null +++ b/docs/superpowers/specs/2026-07-25-web-ui-design.md @@ -0,0 +1,263 @@ +# Web UI Design — browser-accessible bookmark list + +Date: 2026-07-25 +Branch: `feat/web-ui` +Status: approved + +## 1. Problem + +The bookmark list is reachable only from inside the userscript, which means it +exists only on pages of asurascans.com and demonicscans.org. There is no way to +open the list on its own — from a desktop, from a phone home screen, or when +neither manga site is loaded. + +This adds a website, served by the existing Go backend, that renders the same +list with the same actions. + +## 2. Scope + +In scope: + +- Password-gated website showing all bookmarks, ordered by `updated_at DESC`. +- All / Favourites tabs. +- A "Continue reading" strip of the five most recent series. +- Per-series actions: continue reading, toggle favourite, manually override the + read chapter, delete. +- Client-side title search. + +Out of scope: + +- A chapter-level reading-event log. The list order already answers "what did I + read last". A `reading_events` table is a separate future spec. +- Any change to `GET /bookmarks`, `PUT /bookmarks/{key}`, + `DELETE /bookmarks/{key}`, or to the userscript. Those stay exactly as they + are, so the website cannot regress phone reading. +- Offline support. The userscript keeps its `localStorage` cache; the website is + server-rendered and requires connectivity. + +## 3. Architecture + +One binary, one container, one SQLite file. The website is added to the running +service rather than deployed alongside it. + +``` +Bromite userscript ──bearer──> /bookmarks* ─┐ + ├─> Store ──> SQLite +Browser (phone/desktop) ──cookie──> / , /ui/*┘ +``` + +New files under `backend/`: + +| File | Purpose | +| --- | --- | +| `web.go` | Page and HTML-fragment handlers | +| `session.go` | Cookie signing/verification, login rate limit | +| `templates/*.html` | `go:embed`-ed templates | +| `static/*` | `go:embed`-ed `style.css`, `htmx.min.js`, `filter.js` | + +Templates and static assets are embedded, so the image stays a single static +binary on distroless and `CGO_ENABLED=0` still holds. + +### 3.1 Routes + +| Route | Auth | Response | +| --- | --- | --- | +| `GET /` | session | List page; login page when no valid session | +| `POST /login` | none | Sets cookie, `303` to `/` | +| `POST /logout` | session | Clears cookie, `303` to `/` | +| `GET /static/{path...}` | none | Embedded asset, long-lived cache header | +| `GET /ui/list?tab=all\|fav` | session | List fragment | +| `POST /ui/bookmarks/{key}/favorite` | session | Re-rendered card | +| `POST /ui/bookmarks/{key}/chapter` | session | Re-rendered card | +| `DELETE /ui/bookmarks/{key}` | session | `200` with empty body | + +`GET /` returns the login page with status `200` rather than redirecting to a +separate login URL. One page, no redirect loop to reason about. + +`/ui/*` returns HTML fragments, not JSON, and is authenticated by cookie. It is +kept separate from `/bookmarks*` deliberately: that API is JSON, authenticated +by bearer token, and consumed by the userscript. Sharing one route for two +representations and two auth schemes would couple the website's needs to the +userscript's contract. + +Middleware layering is unchanged at the top: `withCORS` stays outermost. +`/bookmarks*` keeps `withAuth` (bearer). `/` and `/ui/*` are wrapped in a new +`withSession`. Web routes are same-origin, so CORS is a no-op for them. + +### 3.2 Store change + +`Store` gains one method: + +```go +func (s *Store) Get(key string) (Bookmark, bool, error) +``` + +Every UI mutation is read-modify-write: load the row, change the single field, +call the existing `Upsert`, then render the row `Upsert` returns. This reuses +the conditional-`updated_at` rule rather than reimplementing it — favouriting +does not reorder the list, a chapter override does. Rendering the returned row +(not the request payload) is the same contract `PUT /bookmarks/{key}` already +follows. + +Not adding `Get` and instead patching columns directly would duplicate the +`updated_at` decision in a second place. That rule has already caused one bug; +it lives in exactly one function. + +## 4. Session authentication + +### 4.1 Configuration + +New environment variable `WEB_PASSWORD`. When it is empty the web routes are not +registered at all and `/` returns `404`. Fail-closed: a deployment that forgets +the variable exposes nothing. + +The password is stored in plaintext in `.env`, alongside `API_TOKEN`. This is a +single-user deployment with no user table, and anyone who can read `.env` +already holds the API token, so hashing it protects nothing that is not already +lost. `.env` is gitignored and the repository is private and self-hosted. + +### 4.2 Cookie + +Name `mangabm_session`. Value: + +``` + "." base64url(HMAC-SHA256(, key)) +key = SHA256(API_TOKEN || 0x00 || WEB_PASSWORD || "mangabm-web-session-v1") +``` + +Stateless: no session table, sessions survive restarts, and rotating either +`API_TOKEN` or `WEB_PASSWORD` invalidates every session at once. Both secrets +are bound in so that changing the password actually logs existing browsers out; +the `0x00` separates the two variable-length secrets so no pair of different +inputs can concatenate to the same string. + +Attributes: `HttpOnly`, `SameSite=Lax`, `Path=/`, `Max-Age` 60 days so the phone +stays logged in across long gaps. `Secure` is set when `r.TLS != nil` or +`X-Forwarded-Proto: https`, and omitted otherwise so `http://localhost` +development can still log in. + +Verification order is fixed: split on `.`, parse the expiry, reject if it is in +the past, and only then `subtle.ConstantTimeCompare` the HMAC. Comparing before +validating the shape leaks structure through error timing. + +The password comparison at login is also constant-time. + +### 4.3 CSRF + +All mutations are `POST` or `DELETE` and carry a `SameSite=Lax` cookie, which a +cross-site form post does not send. No separate CSRF token. + +### 4.4 Login rate limit + +In-memory, no persistence. Ten failed attempts within a rolling 20-minute window +for one client IP return `429` with a `Retry-After` header. Entries expire on +their own; there is no permanent ban and no unlock step. A successful login +clears that IP's counter. + +Client IP is the **rightmost** entry of `X-Forwarded-For`. Traefik appends the +peer address it observed to whatever the client sent, so the leftmost entry is +attacker-controlled and the rightmost is not. `r.RemoteAddr` is unusable here — +behind Traefik it is always the proxy's container address, which would turn a +per-IP limit into a global one. + +Known and accepted limitation: behind carrier-grade NAT the limit is shared with +every other subscriber on the same public address, so a stranger exhausting the +budget can lock the owner out for up to 20 minutes. The window self-heals and +ten attempts is generous for a mistyped password, so this is preferred over +removing the limit. + +## 5. Interface + +Mobile-first. Dark by default, honouring `prefers-color-scheme`. Tap targets at +least 44px. At viewports 900px and wider the card list becomes a 2–3 column +grid. + +### 5.1 Login page + +A centered card with a single password field (`type="password"`, +`autocomplete="current-password"`) and a submit button. Failed attempts render +an inline error. A rate-limited attempt renders how long to wait. + +### 5.2 List page + +``` +┌──────────────────────────┐ +│ mangaBookmark [logout]│ +│ [ search… ] │ +│ ( All ) ( Favourites ) │ +├──────────────────────────┤ +│ Continue reading │ +│ [card][card][card] → │ +├──────────────────────────┤ +│ ┌────┬───────────────┐ │ +│ │cvr │ Title ASURA│ │ +│ │ │ Ch 45 · NEW 47│ │ +│ │ │ [Continue]★✎🗑│ │ +│ └────┴───────────────┘ │ +└──────────────────────────┘ +``` + +- The main list is ordered `updated_at DESC`. That ordering is the reading + history; no separate history view exists. +- "Continue reading" shows the top five of the same ordering in a horizontally + scrolling strip. +- A `NEW` badge appears when `latest_chapter_num` is present and greater than + `last_chapter_num`. +- **Continue** opens `last_chapter_url` in a new tab; it falls back to + `series_url` when no chapter URL is stored. +- The favourite control is an htmx `POST`; the swapped-in card shows the new + state. The list does not reorder. +- The chapter override expands an inline number input on the card. Submitting + forces `last_chapter` and `last_chapter_num` to the entered value, which does + move `updated_at` and therefore does reorder the list. +- Delete asks for confirmation, then htmx removes the card from the DOM. +- Search filters cards by title in the browser with roughly fifteen lines of + JavaScript. No request is made. +- The empty list renders a short message pointing at the userscript. + +### 5.3 Tabs + +Switching tabs issues `GET /ui/list?tab=…` and swaps the list container, +pushing the URL so the back button works. Favourites is the same list filtered +to `favorite = true`, in the same order. + +## 6. Testing + +`session_test.go`: + +- A signed cookie round-trips and verifies. +- An expired cookie is rejected. +- A cookie with a tampered HMAC is rejected. +- A cookie with a tampered expiry is rejected. +- A correct password logs in; a wrong one does not. +- Ten failures trip the limiter; the eleventh attempt returns `429`. +- A successful login clears the counter. +- The rightmost `X-Forwarded-For` entry is the one keyed on. + +`web_test.go`: + +- `GET /` without a cookie returns `200` and the login page. +- `/ui/*` without a cookie returns `401`. +- `/ui/list` with a cookie returns the list fragment; `?tab=fav` returns only + favourites. +- Toggling favourite leaves `updated_at` unchanged. +- A chapter override changes `updated_at`. +- Deleting removes the row. +- With `WEB_PASSWORD` empty, `/` returns `404`. + +Templates are parsed once at startup so a broken template fails the process +immediately rather than the first request. + +## 7. Deployment + +- `.env` and `.env.example` gain `WEB_PASSWORD`. +- `docker-compose.prod.yml` gains a second Traefik router label for + `manga.violetcrown.my.id` pointing at the same service on port 8080. Both + routers share one container; no second service, no second certificate + resolver. +- A DNS `A`/`AAAA` record for `manga.violetcrown.my.id`. +- `DEPLOY.md` gains a section covering the DNS record, the new variable, and + generating a password. + +`ALLOWED_ORIGINS` is untouched. The website is same-origin and never triggers +CORS; only the userscript's cross-origin calls do. diff --git a/plans/2026-07-25-web-ui-implementation-plan.md b/plans/2026-07-25-web-ui-implementation-plan.md new file mode 100644 index 0000000..bea56e9 --- /dev/null +++ b/plans/2026-07-25-web-ui-implementation-plan.md @@ -0,0 +1,2330 @@ +# Web UI Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add a password-gated website, served by the existing Go backend on a new subdomain, that shows the bookmark list with continue-reading, favourite, chapter-override, delete, and title search. + +**Architecture:** The existing binary gains server-rendered HTML pages and htmx fragment endpoints, with templates and static assets compiled in via `go:embed`. Browser requests authenticate with a stateless HMAC-signed session cookie; the userscript's bearer-authenticated `/bookmarks*` JSON API is not touched. All UI mutations go read-modify-write through the existing `Store.Upsert`, so the conditional-`updated_at` rule stays in exactly one place. + +**Tech Stack:** Go 1.23 stdlib (`net/http`, `html/template`, `embed`, `crypto/hmac`), `modernc.org/sqlite`, htmx 2.x vendored as a single file, hand-written CSS. No npm, no bundler, no build step. + +**Design doc:** `docs/superpowers/specs/2026-07-25-web-ui-design.md` + +## Global Constraints + +- Go 1.23, module `mangabm/backend`. Everything lives in `package main` under `backend/`. +- `CGO_ENABLED=0` must keep working — the image is `gcr.io/distroless/static:nonroot` and the binary must stay static. No new cgo dependencies. +- **No new Go module dependencies.** Stdlib only. htmx is vendored as a static asset, not a Go dependency. +- Do not modify `GET /bookmarks`, `PUT /bookmarks/{key}`, `DELETE /bookmarks/{key}`, `withAuth`, `withCORS`, or `userscript/manga-bookmark.user.js`. A regression there breaks phone reading. +- `Store.Upsert` is the only place the `updated_at` rule lives. Never write `updated_at` from a UI handler by any other route. +- Every UI handler renders the bookmark that `Upsert` **returned**, never the one it passed in. +- Existing test conventions: table-driven where there is more than one case, `t.TempDir()` for the database, `t.Helper()` on helpers, no external assertion library. +- Secrets (`API_TOKEN`, `WEB_PASSWORD`) come from environment variables only. Never hardcode, never log. +- Session cookie name: `mangabm_session`. HMAC domain-separation string: `mangabm-web-session-v1`. Both are exact — a typo silently invalidates every existing session. +- Run `gofmt -w` on every file you touch before committing. + +--- + +## File Structure + +| File | Responsibility | +| --- | --- | +| `backend/store.go` | Modify: add `Store.Get`, add `Bookmark.HasNewChapter` / `Bookmark.ContinueURL` | +| `backend/main.go` | Modify: `WEB_PASSWORD` config, wire web routes | +| `backend/session.go` | Create: cookie sign/verify, cookie set/clear, client IP, login rate limiter | +| `backend/web.go` | Create: page + fragment handlers, template embedding | +| `backend/templates/login.html` | Create: login page | +| `backend/templates/app.html` | Create: list page shell | +| `backend/templates/list.html` | Create: `list` fragment (cards only) | +| `backend/templates/card.html` | Create: `card` fragment (one series) | +| `backend/static/style.css` | Create: all styling | +| `backend/static/filter.js` | Create: client-side title search | +| `backend/static/htmx.min.js` | Create: vendored htmx 2.x | +| `backend/session_test.go` | Create: cookie, limiter, client IP tests | +| `backend/web_test.go` | Create: route, auth, mutation tests | +| `backend/Dockerfile` | Modify: copy `templates/` and `static/` into the build stage | +| `docker-compose.yml` | Modify: pass `WEB_PASSWORD` | +| `docker-compose.prod.yml` | Modify: second Traefik router for the web host | +| `.env.example`, `DEPLOY.md` | Modify: document `WEB_PASSWORD` and `MANGA_WEB_HOST` | + +Split rationale: `session.go` holds everything security-sensitive (signing, comparison, rate limiting) so it can be reviewed as one unit; `web.go` holds only request routing and rendering. Templates are split so that `card.html` is rendered both standalone (htmx swap after a mutation) and nested inside `list.html`. + +--- + +### Task 1: `Store.Get` and the two `Bookmark` view helpers + +**Files:** +- Modify: `backend/store.go` +- Test: `backend/store_test.go` + +**Interfaces:** +- Consumes: nothing. +- Produces: + - `func (s *Store) Get(key string) (Bookmark, bool, error)` — second return is false when the key does not exist; error is nil in that case. + - `func (b Bookmark) HasNewChapter() bool` + - `func (b Bookmark) ContinueURL() string` + +- [ ] **Step 1: Write the failing tests** + +Append to `backend/store_test.go`. Note `newTestStore` may not exist yet — check the file; if the existing tests only build a store inline, add this helper next to the other helpers at the top of the file: + +```go +func newTestStore(t *testing.T) *Store { + t.Helper() + store, err := OpenStore(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + t.Cleanup(func() { store.Close() }) + return store +} +``` + +Then the tests: + +```go +func TestStoreGet(t *testing.T) { + store := newTestStore(t) + if _, err := store.Upsert(Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapterNum: 45, UpdatedAt: 1000, + }); err != nil { + t.Fatalf("Upsert: %v", err) + } + + got, ok, err := store.Get("asura:solo") + if err != nil { + t.Fatalf("Get: %v", err) + } + if !ok { + t.Fatal("Get ok = false, want true") + } + if got.Title != "Solo Leveling" || got.LastChapterNum != 45 { + t.Fatalf("Get = %+v, want title/chapter preserved", got) + } +} + +func TestStoreGetMissing(t *testing.T) { + store := newTestStore(t) + _, ok, err := store.Get("asura:nope") + if err != nil { + t.Fatalf("Get missing returned error %v, want nil", err) + } + if ok { + t.Fatal("Get ok = true for missing key, want false") + } +} + +func TestBookmarkHasNewChapter(t *testing.T) { + num := func(f float64) *float64 { return &f } + cases := []struct { + name string + b Bookmark + want bool + }{ + {"latest ahead", Bookmark{LastChapterNum: 45, LatestChapterNum: num(47)}, true}, + {"latest equal", Bookmark{LastChapterNum: 45, LatestChapterNum: num(45)}, false}, + {"latest behind", Bookmark{LastChapterNum: 45, LatestChapterNum: num(44)}, false}, + {"latest unknown", Bookmark{LastChapterNum: 45}, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.b.HasNewChapter(); got != tc.want { + t.Fatalf("HasNewChapter() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestBookmarkContinueURL(t *testing.T) { + cases := []struct { + name string + b Bookmark + want string + }{ + {"chapter url present", Bookmark{LastChapterURL: "/ch/45", SeriesURL: "/series"}, "/ch/45"}, + {"falls back to series", Bookmark{SeriesURL: "/series"}, "/series"}, + {"both empty", Bookmark{}, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := tc.b.ContinueURL(); got != tc.want { + t.Fatalf("ContinueURL() = %q, want %q", got, tc.want) + } + }) + } +} +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cd backend && go test ./... -run 'TestStoreGet|TestBookmark' -v` +Expected: compile failure — `store.Get undefined`, `b.HasNewChapter undefined`, `b.ContinueURL undefined`. + +- [ ] **Step 3: Implement** + +Add to `backend/store.go`, immediately after the `Bookmark` struct: + +```go +// HasNewChapter reports whether the site has published past the read point. +// A nil LatestChapterNum means nothing has been captured yet, which is not the +// same as "nothing new". +func (b Bookmark) HasNewChapter() bool { + return b.LatestChapterNum != nil && *b.LatestChapterNum > b.LastChapterNum +} + +// ContinueURL is where the Continue button points: the chapter last read, or +// the series page when no chapter URL was ever captured. +func (b Bookmark) ContinueURL() string { + if b.LastChapterURL != "" { + return b.LastChapterURL + } + return b.SeriesURL +} +``` + +Add after `List`: + +```go +// Get returns one bookmark by key. A missing key is not an error: ok is false +// and err is nil. UI mutations read-modify-write through this so they preserve +// the fields they do not touch. +func (s *Store) Get(key string) (Bookmark, bool, error) { + b, err := scanBookmark(s.db.QueryRow( + `SELECT `+bookmarkColumns+` FROM bookmarks WHERE key = ?`, key).Scan) + if errors.Is(err, sql.ErrNoRows) { + return Bookmark{}, false, nil + } + if err != nil { + return Bookmark{}, false, fmt.Errorf("get %q: %w", key, err) + } + return b, true, nil +} +``` + +Add `"errors"` to the import block in `backend/store.go`. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS, including all pre-existing tests. + +- [ ] **Step 5: Commit** + +```bash +gofmt -w backend/store.go backend/store_test.go +git add backend/store.go backend/store_test.go +git commit -m "feat(backend): add Store.Get and bookmark view helpers" +``` + +--- + +### Task 2: Session cookie signing and verification + +**Files:** +- Create: `backend/session.go` +- Test: `backend/session_test.go` + +**Interfaces:** +- Consumes: nothing. +- Produces: + - `const sessionCookieName = "mangabm_session"` + - `const sessionTTL = 60 * 24 * time.Hour` + - `func sessionKey(apiToken string) []byte` + - `func signSession(key []byte, expiryMs int64) string` + - `func verifySession(key []byte, value string, nowMs int64) bool` + - `func setSessionCookie(w http.ResponseWriter, r *http.Request, key []byte)` + - `func clearSessionCookie(w http.ResponseWriter, r *http.Request)` + +- [ ] **Step 1: Write the failing tests** + +Create `backend/session_test.go`: + +```go +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestSessionRoundTrip(t *testing.T) { + key := sessionKey("token-abc") + now := time.Now().UnixMilli() + value := signSession(key, now+60_000) + if !verifySession(key, value, now) { + t.Fatal("verifySession = false for a freshly signed cookie, want true") + } +} + +func TestSessionRejects(t *testing.T) { + key := sessionKey("token-abc") + now := time.Now().UnixMilli() + valid := signSession(key, now+60_000) + payload, sig, _ := strings.Cut(valid, ".") + + cases := []struct { + name string + value string + }{ + {"empty", ""}, + {"no separator", payload + sig}, + {"unparseable expiry", "notanumber." + sig}, + {"expired", signSession(key, now-1)}, + {"tampered signature", payload + "." + flipLastChar(sig)}, + {"tampered expiry", "99999999999999." + sig}, + {"signed with another key", signSession(sessionKey("other-token"), now+60_000)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if verifySession(key, tc.value, now) { + t.Fatalf("verifySession(%q) = true, want false", tc.value) + } + }) + } +} + +func flipLastChar(s string) string { + if s == "" { + return "x" + } + last := s[len(s)-1] + if last == 'A' { + return s[:len(s)-1] + "B" + } + return s[:len(s)-1] + "A" +} + +func TestSessionKeyDependsOnToken(t *testing.T) { + a := sessionKey("token-a") + b := sessionKey("token-b") + if string(a) == string(b) { + t.Fatal("sessionKey collided for different API tokens") + } +} + +func TestSetSessionCookieAttributes(t *testing.T) { + cases := []struct { + name string + tls bool + forwarded string + wantSecure bool + }{ + {"plain http dev", false, "", false}, + {"direct tls", true, "", true}, + {"behind https proxy", false, "https", true}, + {"behind http proxy", false, "http", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodPost, "/login", nil) + if tc.tls { + r.TLS = &tls.ConnectionState{} + } + if tc.forwarded != "" { + r.Header.Set("X-Forwarded-Proto", tc.forwarded) + } + rr := httptest.NewRecorder() + setSessionCookie(rr, r, sessionKey("token-abc")) + + cookies := rr.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("got %d cookies, want 1", len(cookies)) + } + c := cookies[0] + if c.Name != sessionCookieName { + t.Fatalf("cookie name = %q, want %q", c.Name, sessionCookieName) + } + if !c.HttpOnly { + t.Fatal("cookie HttpOnly = false, want true") + } + if c.SameSite != http.SameSiteLaxMode { + t.Fatalf("cookie SameSite = %v, want Lax", c.SameSite) + } + if c.Path != "/" { + t.Fatalf("cookie Path = %q, want /", c.Path) + } + if c.Secure != tc.wantSecure { + t.Fatalf("cookie Secure = %v, want %v", c.Secure, tc.wantSecure) + } + if c.MaxAge != int(sessionTTL/time.Second) { + t.Fatalf("cookie MaxAge = %d, want %d", c.MaxAge, int(sessionTTL/time.Second)) + } + }) + } +} + +func TestClearSessionCookie(t *testing.T) { + r := httptest.NewRequest(http.MethodPost, "/logout", nil) + rr := httptest.NewRecorder() + clearSessionCookie(rr, r) + + cookies := rr.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("got %d cookies, want 1", len(cookies)) + } + if cookies[0].MaxAge >= 0 { + t.Fatalf("cleared cookie MaxAge = %d, want negative", cookies[0].MaxAge) + } +} +``` + +Add `"crypto/tls"` to that file's imports (used by `TestSetSessionCookieAttributes`). + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cd backend && go test ./... -run TestSession -v` +Expected: compile failure — `sessionKey`, `signSession`, `verifySession`, `setSessionCookie`, `clearSessionCookie`, `sessionCookieName`, `sessionTTL` all undefined. + +- [ ] **Step 3: Implement** + +Create `backend/session.go`: + +```go +package main + +import ( + "crypto/hmac" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "net/http" + "strconv" + "strings" + "time" +) + +const ( + sessionCookieName = "mangabm_session" + // 60 days: long enough that a phone stays logged in between reading spells. + sessionTTL = 60 * 24 * time.Hour + // Domain separation, so the session key can never collide with any other + // use of API_TOKEN. Changing this string logs everyone out. + sessionKeyPurpose = "mangabm-web-session-v1" +) + +// sessionKey derives the cookie-signing key from the API token. Sessions are +// stateless — there is no session table — so rotating API_TOKEN invalidates +// every outstanding cookie at once. +func sessionKey(apiToken string) []byte { + sum := sha256.Sum256([]byte(apiToken + sessionKeyPurpose)) + return sum[:] +} + +// signSession encodes ".". +func signSession(key []byte, expiryMs int64) string { + payload := strconv.FormatInt(expiryMs, 10) + return payload + "." + sessionMAC(key, payload) +} + +func sessionMAC(key []byte, payload string) string { + mac := hmac.New(sha256.New, key) + mac.Write([]byte(payload)) + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) +} + +// verifySession checks shape, then expiry, then the signature — in that order. +// The signature comparison is constant-time; the checks before it only look at +// data the holder already supplied, so their timing leaks nothing. +func verifySession(key []byte, value string, nowMs int64) bool { + payload, sig, ok := strings.Cut(value, ".") + if !ok { + return false + } + expiry, err := strconv.ParseInt(payload, 10, 64) + if err != nil || expiry <= nowMs { + return false + } + want := sessionMAC(key, payload) + return subtle.ConstantTimeCompare([]byte(sig), []byte(want)) == 1 +} + +// isHTTPS reports whether the browser's connection is encrypted. Behind Traefik +// the Go server itself speaks plain HTTP, so the forwarded header is the only +// signal; without this check the Secure cookie would never be set in +// production, and setting it unconditionally would break http://localhost dev. +func isHTTPS(r *http.Request) bool { + return r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" +} + +func setSessionCookie(w http.ResponseWriter, r *http.Request, key []byte) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: signSession(key, time.Now().Add(sessionTTL).UnixMilli()), + Path: "/", + MaxAge: int(sessionTTL / time.Second), + HttpOnly: true, + Secure: isHTTPS(r), + SameSite: http.SameSiteLaxMode, + }) +} + +func clearSessionCookie(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{ + Name: sessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + HttpOnly: true, + Secure: isHTTPS(r), + SameSite: http.SameSiteLaxMode, + }) +} +``` + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +gofmt -w backend/session.go backend/session_test.go +git add backend/session.go backend/session_test.go +git commit -m "feat(backend): stateless HMAC session cookies for the web UI" +``` + +--- + +### Task 3: Login rate limiter and client IP extraction + +**Files:** +- Modify: `backend/session.go` +- Test: `backend/session_test.go` + +**Interfaces:** +- Consumes: nothing from earlier tasks. +- Produces: + - `func clientIP(r *http.Request) string` + - `type loginLimiter struct{ ... }` + - `func newLoginLimiter() *loginLimiter` + - `func (l *loginLimiter) retryAfter(ip string, now time.Time) time.Duration` — zero when not blocked + - `func (l *loginLimiter) fail(ip string, now time.Time)` + - `func (l *loginLimiter) reset(ip string)` + - `const loginMaxFailures = 10`, `const loginWindow = 20 * time.Minute` + +- [ ] **Step 1: Write the failing tests** + +Append to `backend/session_test.go`: + +```go +func TestClientIP(t *testing.T) { + cases := []struct { + name string + remoteAddr string + xff []string + want string + }{ + {"no header falls back to remote addr", "203.0.113.9:5555", nil, "203.0.113.9"}, + {"single proxy hop", "10.0.0.1:5555", []string{"203.0.113.9"}, "203.0.113.9"}, + { + // The client sent "1.2.3.4" itself; Traefik appended the address it + // actually saw. Only the rightmost entry is trustworthy. + name: "spoofed left entry is ignored", + remoteAddr: "10.0.0.1:5555", + xff: []string{"1.2.3.4, 203.0.113.9"}, + want: "203.0.113.9", + }, + { + name: "spoofed separate header line is ignored", + remoteAddr: "10.0.0.1:5555", + xff: []string{"1.2.3.4", "203.0.113.9"}, + want: "203.0.113.9", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodPost, "/login", nil) + r.RemoteAddr = tc.remoteAddr + for _, v := range tc.xff { + r.Header.Add("X-Forwarded-For", v) + } + if got := clientIP(r); got != tc.want { + t.Fatalf("clientIP() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestLoginLimiterBlocksAfterMaxFailures(t *testing.T) { + l := newLoginLimiter() + now := time.Now() + for i := 0; i < loginMaxFailures; i++ { + if wait := l.retryAfter("1.2.3.4", now); wait != 0 { + t.Fatalf("blocked after %d failures, want block only after %d", i, loginMaxFailures) + } + l.fail("1.2.3.4", now) + } + wait := l.retryAfter("1.2.3.4", now) + if wait <= 0 { + t.Fatalf("retryAfter = %v after %d failures, want > 0", wait, loginMaxFailures) + } + if wait > loginWindow { + t.Fatalf("retryAfter = %v, want <= %v", wait, loginWindow) + } +} + +func TestLoginLimiterWindowExpires(t *testing.T) { + l := newLoginLimiter() + start := time.Now() + for i := 0; i < loginMaxFailures; i++ { + l.fail("1.2.3.4", start) + } + if l.retryAfter("1.2.3.4", start) == 0 { + t.Fatal("expected block immediately after the failures") + } + later := start.Add(loginWindow + time.Second) + if wait := l.retryAfter("1.2.3.4", later); wait != 0 { + t.Fatalf("retryAfter = %v once the window passed, want 0", wait) + } +} + +func TestLoginLimiterResetClearsCounter(t *testing.T) { + l := newLoginLimiter() + now := time.Now() + for i := 0; i < loginMaxFailures; i++ { + l.fail("1.2.3.4", now) + } + l.reset("1.2.3.4") + if wait := l.retryAfter("1.2.3.4", now); wait != 0 { + t.Fatalf("retryAfter = %v after reset, want 0", wait) + } +} + +func TestLoginLimiterIsPerIP(t *testing.T) { + l := newLoginLimiter() + now := time.Now() + for i := 0; i < loginMaxFailures; i++ { + l.fail("1.2.3.4", now) + } + if wait := l.retryAfter("5.6.7.8", now); wait != 0 { + t.Fatalf("retryAfter for a different IP = %v, want 0", wait) + } +} +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cd backend && go test ./... -run 'TestClientIP|TestLoginLimiter' -v` +Expected: compile failure — `clientIP`, `newLoginLimiter`, `loginMaxFailures`, `loginWindow` undefined. + +- [ ] **Step 3: Implement** + +Append to `backend/session.go`: + +```go +const ( + loginMaxFailures = 10 + loginWindow = 20 * time.Minute +) + +// clientIP returns the address the reverse proxy actually observed. +// +// Traefik appends the peer address to whatever X-Forwarded-For the client sent, +// so the leftmost entry is attacker-controlled and the rightmost is not. Go's +// Header.Get would only read the first header line, which a client can preempt +// by sending its own; Values covers every line so the true last hop is found. +// RemoteAddr is useless behind the proxy — it is always the Traefik container — +// so it serves only as the direct-connection fallback for local development. +func clientIP(r *http.Request) string { + if vals := r.Header.Values("X-Forwarded-For"); len(vals) > 0 { + hops := strings.Split(vals[len(vals)-1], ",") + if ip := strings.TrimSpace(hops[len(hops)-1]); ip != "" { + return ip + } + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} + +// loginLimiter throttles password guessing: loginMaxFailures failures inside a +// rolling loginWindow blocks further attempts from that IP until the oldest one +// ages out. There is no permanent ban and no unlock step. +// +// Behind carrier-grade NAT this budget is shared with every other subscriber on +// the same public address, so a stranger can lock the owner out for up to one +// window. That is accepted: the block self-heals, and ten attempts is generous +// for a mistyped password. +// +// State is in memory and per-process, so a restart clears it. Entries are +// pruned lazily on access; for a single-user deployment the map cannot grow +// past the handful of addresses that ever attempt a login. +type loginLimiter struct { + mu sync.Mutex + failures map[string][]time.Time +} + +func newLoginLimiter() *loginLimiter { + return &loginLimiter{failures: make(map[string][]time.Time)} +} + +// retryAfter returns how long ip must wait, or zero when it may try now. +func (l *loginLimiter) retryAfter(ip string, now time.Time) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + + recent := l.pruneLocked(ip, now) + if len(recent) < loginMaxFailures { + return 0 + } + return recent[0].Add(loginWindow).Sub(now) +} + +func (l *loginLimiter) fail(ip string, now time.Time) { + l.mu.Lock() + defer l.mu.Unlock() + l.failures[ip] = append(l.pruneLocked(ip, now), now) +} + +func (l *loginLimiter) reset(ip string) { + l.mu.Lock() + defer l.mu.Unlock() + delete(l.failures, ip) +} + +// pruneLocked drops attempts older than the window and returns what is left. +// The caller must hold l.mu. +func (l *loginLimiter) pruneLocked(ip string, now time.Time) []time.Time { + cutoff := now.Add(-loginWindow) + kept := l.failures[ip][:0] + for _, at := range l.failures[ip] { + if at.After(cutoff) { + kept = append(kept, at) + } + } + if len(kept) == 0 { + delete(l.failures, ip) + return nil + } + l.failures[ip] = kept + return kept +} +``` + +Add `"net"` and `"sync"` to the import block in `backend/session.go`. + +- [ ] **Step 4: Run the tests to verify they pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS. + +- [ ] **Step 5: Run the race detector** + +Run: `cd backend && go test -race ./...` +Expected: PASS, no race warnings. The limiter is shared across concurrent requests, so this matters. + +- [ ] **Step 6: Commit** + +```bash +gofmt -w backend/session.go backend/session_test.go +git add backend/session.go backend/session_test.go +git commit -m "feat(backend): per-IP login rate limit with proxy-aware client IP" +``` + +--- + +### Task 4: Vendor htmx and add the config variable + +**Files:** +- Create: `backend/static/htmx.min.js` +- Modify: `backend/main.go` +- Test: `backend/store_test.go` (extend the existing `testConfig`, add a config test) + +**Interfaces:** +- Consumes: nothing. +- Produces: `Config.WebPassword string`, populated from `WEB_PASSWORD`. + +- [ ] **Step 1: Vendor htmx** + +```bash +mkdir -p backend/static +curl -fsSL https://unpkg.com/htmx.org@2.0.4/dist/htmx.min.js -o backend/static/htmx.min.js +wc -c backend/static/htmx.min.js +``` + +Expected: roughly 48000–52000 bytes. If the download fails or the file is under 10000 bytes, stop — do not proceed with a truncated file. Fetch it manually from `https://github.com/bigskysoftware/htmx/releases` instead. The file is committed to the repository on purpose: the Docker build has no network access and there is no npm step. + +- [ ] **Step 2: Write the failing test** + +Append to `backend/store_test.go`: + +```go +func TestLoadConfigWebPassword(t *testing.T) { + t.Setenv("API_TOKEN", "token-abc") + t.Setenv("WEB_PASSWORD", "hunter2") + if got := loadConfig().WebPassword; got != "hunter2" { + t.Fatalf("WebPassword = %q, want hunter2", got) + } + + t.Setenv("WEB_PASSWORD", "") + if got := loadConfig().WebPassword; got != "" { + t.Fatalf("WebPassword = %q with the variable unset, want empty", got) + } +} +``` + +- [ ] **Step 3: Run the test to verify it fails** + +Run: `cd backend && go test ./... -run TestLoadConfigWebPassword -v` +Expected: compile failure — `cfg.WebPassword undefined`. + +- [ ] **Step 4: Implement** + +In `backend/main.go`, add the field to `Config`: + +```go + // WebPassword gates the browser UI. Empty disables the web routes entirely. + WebPassword string +``` + +And in `loadConfig`, inside the struct literal: + +```go + WebPassword: os.Getenv("WEB_PASSWORD"), +``` + +- [ ] **Step 5: Run the tests to verify they pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +gofmt -w backend/main.go backend/store_test.go +git add backend/static/htmx.min.js backend/main.go backend/store_test.go +git commit -m "chore(backend): vendor htmx 2.0.4 and add WEB_PASSWORD config" +``` + +--- + +### Task 5: Templates and the login flow + +**Files:** +- Create: `backend/web.go`, `backend/templates/login.html`, `backend/templates/app.html`, `backend/templates/list.html`, `backend/templates/card.html` +- Modify: `backend/main.go` +- Test: `backend/web_test.go` + +**Interfaces:** +- Consumes: `sessionKey`, `signSession`, `setSessionCookie`, `clearSessionCookie`, `sessionCookieName`, `verifySession`, `clientIP`, `newLoginLimiter`, `loginMaxFailures` (Tasks 2–3); `Store.List`, `Bookmark.HasNewChapter`, `Bookmark.ContinueURL` (Task 1); `Config.WebPassword` (Task 4). +- Produces: + - `type webHandler struct{ store *Store; tmpl *template.Template; key []byte; password string; limiter *loginLimiter }` + - `func newWebHandler(store *Store, cfg Config) (*webHandler, error)` + - `func (h *webHandler) register(mux *http.ServeMux)` + - `func (h *webHandler) authed(r *http.Request) bool` + - `func (h *webHandler) requireSession(next http.HandlerFunc) http.HandlerFunc` + - `type listView struct{ Tab string; Recent []Bookmark; Items []Bookmark }` + +All four templates are created in this task because `newWebHandler` parses the whole set at startup and fails if any is missing. Tasks 6 and 7 fill in the interactive attributes and the styling. + +- [ ] **Step 1: Write the failing tests** + +Create `backend/web_test.go`: + +```go +package main + +import ( + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +const testPassword = "hunter2" + +func webConfig() Config { + cfg := testConfig() + cfg.WebPassword = testPassword + return cfg +} + +// newWebTestServer returns the full router plus the store behind it, so tests +// can seed rows and assert on what the handlers wrote back. +func newWebTestServer(t *testing.T, cfg Config) (http.Handler, *Store) { + t.Helper() + store, err := OpenStore(filepath.Join(t.TempDir(), "test.db")) + if err != nil { + t.Fatalf("OpenStore: %v", err) + } + t.Cleanup(func() { store.Close() }) + return newRouter(store, cfg), store +} + +// sessionCookie returns a cookie a handler will accept for cfg's API token. +func sessionCookie(t *testing.T, cfg Config) *http.Cookie { + t.Helper() + return &http.Cookie{ + Name: sessionCookieName, + Value: signSession(sessionKey(cfg.Token), time.Now().Add(time.Hour).UnixMilli()), + } +} + +func TestIndexWithoutSessionShowsLogin(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/", nil)) + + if rr.Code != http.StatusOK { + t.Fatalf("GET / status = %d, want 200", rr.Code) + } + if !strings.Contains(rr.Body.String(), `type="password"`) { + t.Fatal("GET / without a session did not render the password field") + } +} + +func TestIndexWithSessionShowsList(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + if _, err := store.Upsert(Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + UpdatedAt: time.Now().UnixMilli(), + }); err != nil { + t.Fatalf("Upsert: %v", err) + } + + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.AddCookie(sessionCookie(t, cfg)) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusOK { + t.Fatalf("GET / status = %d, want 200", rr.Code) + } + if !strings.Contains(rr.Body.String(), "Solo Leveling") { + t.Fatal("GET / with a session did not render the bookmark title") + } +} + +func TestLoginSuccessSetsCookie(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + req := httptest.NewRequest(http.MethodPost, "/login", + strings.NewReader(url.Values{"password": {testPassword}}.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusSeeOther { + t.Fatalf("POST /login status = %d, want 303", rr.Code) + } + cookies := rr.Result().Cookies() + if len(cookies) != 1 || cookies[0].Name != sessionCookieName || cookies[0].Value == "" { + t.Fatalf("POST /login cookies = %+v, want one non-empty %s", cookies, sessionCookieName) + } +} + +func TestLoginWrongPassword(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + req := httptest.NewRequest(http.MethodPost, "/login", + strings.NewReader(url.Values{"password": {"wrong"}}.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusUnauthorized { + t.Fatalf("POST /login status = %d, want 401", rr.Code) + } + if len(rr.Result().Cookies()) != 0 { + t.Fatal("a failed login set a cookie") + } +} + +func TestLoginRateLimited(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + post := func() *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/login", + strings.NewReader(url.Values{"password": {"wrong"}}.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("X-Forwarded-For", "203.0.113.9") + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + return rr + } + for i := 0; i < loginMaxFailures; i++ { + if code := post().Code; code != http.StatusUnauthorized { + t.Fatalf("attempt %d status = %d, want 401", i+1, code) + } + } + rr := post() + if rr.Code != http.StatusTooManyRequests { + t.Fatalf("attempt %d status = %d, want 429", loginMaxFailures+1, rr.Code) + } + if after := rr.Header().Get("Retry-After"); after == "" { + t.Fatal("429 response has no Retry-After header") + } else if n, err := strconv.Atoi(after); err != nil || n <= 0 { + t.Fatalf("Retry-After = %q, want a positive integer", after) + } +} + +func TestLogoutClearsCookie(t *testing.T) { + cfg := webConfig() + srv, _ := newWebTestServer(t, cfg) + req := httptest.NewRequest(http.MethodPost, "/logout", nil) + req.AddCookie(sessionCookie(t, cfg)) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + + if rr.Code != http.StatusSeeOther { + t.Fatalf("POST /logout status = %d, want 303", rr.Code) + } + cookies := rr.Result().Cookies() + if len(cookies) != 1 || cookies[0].MaxAge >= 0 { + t.Fatalf("POST /logout cookies = %+v, want one expiring cookie", cookies) + } +} + +func TestWebDisabledWhenNoPassword(t *testing.T) { + cfg := testConfig() // WebPassword empty + srv, _ := newWebTestServer(t, cfg) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, "/", nil)) + + if rr.Code != http.StatusNotFound { + t.Fatalf("GET / with WEB_PASSWORD unset = %d, want 404", rr.Code) + } +} + +func TestBookmarksAPIStillBearerOnly(t *testing.T) { + cfg := webConfig() + srv, _ := newWebTestServer(t, cfg) + + // A session cookie must not grant access to the userscript's JSON API. + req := httptest.NewRequest(http.MethodGet, "/bookmarks", nil) + req.AddCookie(sessionCookie(t, cfg)) + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, req) + if rr.Code != http.StatusUnauthorized { + t.Fatalf("GET /bookmarks with only a cookie = %d, want 401", rr.Code) + } + + // And the bearer token must still work. + rr = httptest.NewRecorder() + srv.ServeHTTP(rr, auth(httptest.NewRequest(http.MethodGet, "/bookmarks", nil))) + if rr.Code != http.StatusOK { + t.Fatalf("GET /bookmarks with bearer = %d, want 200", rr.Code) + } +} + +func TestStaticAssetsServed(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + for _, path := range []string{"/static/style.css", "/static/htmx.min.js", "/static/filter.js"} { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil)) + if rr.Code != http.StatusOK { + t.Fatalf("GET %s = %d, want 200", path, rr.Code) + } + if rr.Body.Len() == 0 { + t.Fatalf("GET %s returned an empty body", path) + } + } +} +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cd backend && go test ./... -run 'TestIndex|TestLogin|TestLogout|TestWeb|TestStatic|TestBookmarksAPI' -v` +Expected: compile failure — `webConfig` references `Config.WebPassword` (present after Task 4) but `newWebHandler` and the routes do not exist, so `GET /` returns 404 and the login tests fail. + +- [ ] **Step 3: Create the templates** + +`backend/templates/login.html`: + +```html +{{define "login"}} + + + + + + + mangaBookmark + + + +
+

mangaBookmark

+
+ + + {{if .Error}}

{{.Error}}

{{end}} + +
+
+ + +{{end}} +``` + +`backend/templates/app.html`: + +```html +{{define "app"}} + + + + + + + mangaBookmark + + + + + +
+

mangaBookmark

+
+ +
+
+ + + + + + {{if .Recent}} +
+

Continue reading

+ +
+ {{end}} + +
+ {{template "list" .}} +
+ + +{{end}} +``` + +`backend/templates/list.html`: + +```html +{{define "list"}} +{{if .Items}} + {{range .Items}}{{template "card" .}}{{end}} +{{else}} +

+ Nothing here yet. Bookmarks appear once the userscript records a chapter. +

+{{end}} +{{end}} +``` + +`backend/templates/card.html` — the interactive attributes land in Task 6; this is the static shape: + +```html +{{define "card"}} + +{{end}} +``` + +- [ ] **Step 4: Create placeholder static assets** + +`TestStaticAssetsServed` requires both files to exist and be non-empty. Task 7 writes the real content. + +`backend/static/style.css`: + +```css +/* Styling lands in Task 7. */ +:root { color-scheme: dark light; } +``` + +`backend/static/filter.js`: + +```js +// Title search and tab-state handling land in Task 7. +function setActiveTab(el) { + el.parentElement.querySelectorAll("[role=tab]").forEach(function (t) { + t.classList.toggle("active", t === el); + }); +} +``` + +- [ ] **Step 5: Implement `web.go`** + +Create `backend/web.go`: + +```go +package main + +import ( + "crypto/subtle" + "embed" + "html/template" + "io/fs" + "log" + "net/http" + "strconv" + "time" +) + +//go:embed templates +var templateFS embed.FS + +//go:embed static +var staticFS embed.FS + +// recentCount is how many series the "Continue reading" strip shows. +const recentCount = 5 + +// webHandler serves the browser UI: full pages at / and htmx fragments at /ui/. +// It is a separate handler from bookmarkHandler because the two speak different +// representations (HTML versus JSON) to different clients under different auth. +type webHandler struct { + store *Store + tmpl *template.Template + key []byte + password string + limiter *loginLimiter +} + +// listView is what every list-rendering template receives. +type listView struct { + Tab string // "all" or "fav" + Recent []Bookmark + Items []Bookmark +} + +// loginView is what the login template receives. +type loginView struct { + Error string +} + +// newWebHandler parses every template up front so a broken one kills the +// process at startup rather than the first request that touches it. +func newWebHandler(store *Store, cfg Config) (*webHandler, error) { + tmpl, err := template.ParseFS(templateFS, "templates/*.html") + if err != nil { + return nil, err + } + return &webHandler{ + store: store, + tmpl: tmpl, + key: sessionKey(cfg.Token), + password: cfg.WebPassword, + limiter: newLoginLimiter(), + }, nil +} + +func (h *webHandler) register(mux *http.ServeMux) { + mux.HandleFunc("GET /{$}", h.index) + mux.HandleFunc("POST /login", h.login) + mux.HandleFunc("POST /logout", h.logout) + mux.Handle("GET /static/", staticHandler()) + + mux.HandleFunc("GET /ui/list", h.requireSession(h.uiList)) +} + +// staticHandler serves the embedded assets. The vendored htmx build and the +// stylesheet change only on deploy, so a long max-age is safe; a redeploy +// changes the binary and the browser revalidates on its own schedule. +func staticHandler() http.Handler { + sub, err := fs.Sub(staticFS, "static") + if err != nil { + panic("embed static: " + err.Error()) + } + files := http.FileServer(http.FS(sub)) + return http.StripPrefix("/static/", http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "public, max-age=3600") + files.ServeHTTP(w, r) + })) +} + +// authed reports whether the request carries a valid session cookie. +func (h *webHandler) authed(r *http.Request) bool { + c, err := r.Cookie(sessionCookieName) + return err == nil && verifySession(h.key, c.Value, time.Now().UnixMilli()) +} + +// requireSession guards the fragment endpoints. It answers 401 rather than +// redirecting, because htmx swaps whatever body it receives into the page and a +// redirected login page would be spliced into the card list. +func (h *webHandler) requireSession(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if !h.authed(r) { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + next(w, r) + } +} + +func (h *webHandler) render(w http.ResponseWriter, status int, name string, data any) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + if err := h.tmpl.ExecuteTemplate(w, name, data); err != nil { + // The status line is already sent, so this can only be logged. + log.Printf("render %s: %v", name, err) + } +} + +// index renders the list, or the login page when there is no session. The login +// page is served at / with status 200 rather than as a redirect to a separate +// URL: one page, no redirect loop to reason about. +func (h *webHandler) index(w http.ResponseWriter, r *http.Request) { + if !h.authed(r) { + h.render(w, http.StatusOK, "login", loginView{}) + return + } + view, err := h.buildListView(r.URL.Query().Get("tab")) + if err != nil { + log.Printf("index: %v", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + h.render(w, http.StatusOK, "app", view) +} + +// buildListView loads the list once and derives both the tab-filtered items and +// the recent strip from it. The strip always reflects overall recency, not the +// active tab, so it is built before filtering. +func (h *webHandler) buildListView(tab string) (listView, error) { + all, err := h.store.List() // already ordered updated_at DESC + if err != nil { + return listView{}, err + } + + recent := all + if len(recent) > recentCount { + recent = recent[:recentCount] + } + + items := all + if tab == "fav" { + items = []Bookmark{} + for _, b := range all { + if b.Favorite { + items = append(items, b) + } + } + } else { + tab = "all" + } + return listView{Tab: tab, Recent: recent, Items: items}, nil +} + +func (h *webHandler) uiList(w http.ResponseWriter, r *http.Request) { + view, err := h.buildListView(r.URL.Query().Get("tab")) + if err != nil { + log.Printf("ui list: %v", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + h.render(w, http.StatusOK, "list", view) +} + +func (h *webHandler) login(w http.ResponseWriter, r *http.Request) { + ip := clientIP(r) + if wait := h.limiter.retryAfter(ip, time.Now()); wait > 0 { + secs := int(wait.Seconds()) + 1 + w.Header().Set("Retry-After", strconv.Itoa(secs)) + h.render(w, http.StatusTooManyRequests, "login", loginView{ + Error: "Too many attempts. Try again in " + + strconv.Itoa((secs+59)/60) + " min.", + }) + return + } + + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + got := r.PostFormValue("password") + if subtle.ConstantTimeCompare([]byte(got), []byte(h.password)) != 1 { + h.limiter.fail(ip, time.Now()) + h.render(w, http.StatusUnauthorized, "login", loginView{Error: "Wrong password."}) + return + } + + h.limiter.reset(ip) + setSessionCookie(w, r, h.key) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (h *webHandler) logout(w http.ResponseWriter, r *http.Request) { + clearSessionCookie(w, r) + http.Redirect(w, r, "/", http.StatusSeeOther) +} +``` + +- [ ] **Step 6: Wire it into the router** + +In `backend/main.go`, inside `newRouter`, after the existing `mux.Handle("/bookmarks/", auth)` line and before the `return`: + +```go + // The browser UI is registered only when a password is configured, so a + // deployment that forgets WEB_PASSWORD exposes nothing rather than + // exposing an unprotected list. + if cfg.WebPassword != "" { + web, err := newWebHandler(store, cfg) + if err != nil { + log.Fatalf("web handler: %v", err) + } + web.register(mux) + } +``` + +`GET /{$}` matches only the exact path `/`, so registering it does not shadow `/bookmarks` or `/healthz`. + +- [ ] **Step 7: Run the tests to verify they pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS, including every pre-existing test. `TestBookmarksAPIStillBearerOnly` is the one that proves the userscript's API is unaffected. + +- [ ] **Step 8: Commit** + +```bash +gofmt -w backend/web.go backend/main.go backend/web_test.go +git add backend/web.go backend/web_test.go backend/main.go backend/templates backend/static +git commit -m "feat(backend): password login, session gate, and list page" +``` + +--- + +### Task 6: Favourite, chapter override, and delete fragments + +**Files:** +- Modify: `backend/web.go`, `backend/templates/card.html` +- Test: `backend/web_test.go` + +**Interfaces:** +- Consumes: `Store.Get`, `Store.Upsert`, `Store.Delete`, `webHandler.requireSession`, `webHandler.render`. +- Produces: routes `POST /ui/bookmarks/{key}/favorite`, `POST /ui/bookmarks/{key}/chapter`, `DELETE /ui/bookmarks/{key}`. + +**Decision recorded here:** a manual chapter override clears `last_chapter_url`. The stored URL points at the chapter that was actually read; once the number is forced to something else, that URL is wrong. Clearing it makes Continue fall back to the series page, which is always correct, instead of linking to a chapter the user has already passed. + +- [ ] **Step 1: Write the failing tests** + +Append to `backend/web_test.go`: + +```go +// seed inserts one bookmark and returns it as stored. +func seed(t *testing.T, store *Store, b Bookmark) Bookmark { + t.Helper() + stored, err := store.Upsert(b) + if err != nil { + t.Fatalf("Upsert: %v", err) + } + return stored +} + +func uiRequest(t *testing.T, cfg Config, method, path string, form url.Values) *http.Request { + t.Helper() + var req *http.Request + if form == nil { + req = httptest.NewRequest(method, path, nil) + } else { + req = httptest.NewRequest(method, path, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + req.AddCookie(sessionCookie(t, cfg)) + return req +} + +func TestUIRoutesRequireSession(t *testing.T) { + srv, _ := newWebTestServer(t, webConfig()) + cases := []struct{ method, path string }{ + {http.MethodGet, "/ui/list"}, + {http.MethodPost, "/ui/bookmarks/asura:solo/favorite"}, + {http.MethodPost, "/ui/bookmarks/asura:solo/chapter"}, + {http.MethodDelete, "/ui/bookmarks/asura:solo"}, + } + for _, tc := range cases { + t.Run(tc.method+" "+tc.path, func(t *testing.T) { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, httptest.NewRequest(tc.method, tc.path, nil)) + if rr.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401", rr.Code) + } + }) + } +} + +func TestFavoriteTogglesWithoutReordering(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + before := seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:solo/favorite", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("favorite status = %d, want 200", rr.Code) + } + + after, ok, err := store.Get("asura:solo") + if err != nil || !ok { + t.Fatalf("Get after favorite: %v ok=%v", err, ok) + } + if !after.Favorite { + t.Fatal("Favorite = false after toggling, want true") + } + if after.UpdatedAt != before.UpdatedAt { + t.Fatalf("UpdatedAt moved from %d to %d; favouriting must not reorder the list", + before.UpdatedAt, after.UpdatedAt) + } + if !strings.Contains(rr.Body.String(), `id="card-asura:solo"`) { + t.Fatal("favorite response did not render the card fragment") + } + + // Toggling again turns it back off. + rr = httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:solo/favorite", nil)) + back, _, _ := store.Get("asura:solo") + if back.Favorite { + t.Fatal("Favorite = true after a second toggle, want false") + } +} + +func TestChapterOverrideMovesUpdatedAt(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + before := seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapter: "45", LastChapterNum: 45, + LastChapterURL: "https://example.test/ch/45", SeriesURL: "https://example.test/solo", + UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, + "/ui/bookmarks/asura:solo/chapter", url.Values{"chapter": {"60"}})) + if rr.Code != http.StatusOK { + t.Fatalf("chapter override status = %d, want 200", rr.Code) + } + + after, ok, err := store.Get("asura:solo") + if err != nil || !ok { + t.Fatalf("Get after override: %v ok=%v", err, ok) + } + if after.LastChapterNum != 60 || after.LastChapter != "60" { + t.Fatalf("chapter = %q/%v, want 60", after.LastChapter, after.LastChapterNum) + } + if after.UpdatedAt <= before.UpdatedAt { + t.Fatalf("UpdatedAt = %d, want later than %d", after.UpdatedAt, before.UpdatedAt) + } + if after.LastChapterURL != "" { + t.Fatalf("LastChapterURL = %q, want cleared by a manual override", after.LastChapterURL) + } + if after.Title != "Solo Leveling" { + t.Fatalf("Title = %q, want the untouched fields preserved", after.Title) + } +} + +func TestChapterOverrideRejectsBadInput(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", LastChapterNum: 45, UpdatedAt: 1_000_000, + }) + + for _, bad := range []string{"", "abc", "-3"} { + t.Run("input "+bad, func(t *testing.T) { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodPost, + "/ui/bookmarks/asura:solo/chapter", url.Values{"chapter": {bad}})) + if rr.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400", rr.Code) + } + after, _, _ := store.Get("asura:solo") + if after.LastChapterNum != 45 { + t.Fatalf("chapter changed to %v on invalid input", after.LastChapterNum) + } + }) + } +} + +func TestMutationsOnMissingKey(t *testing.T) { + cfg := webConfig() + srv, _ := newWebTestServer(t, cfg) + cases := []struct { + name string + req *http.Request + }{ + {"favorite", uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:nope/favorite", nil)}, + {"chapter", uiRequest(t, cfg, http.MethodPost, "/ui/bookmarks/asura:nope/chapter", url.Values{"chapter": {"1"}})}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, tc.req) + if rr.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", rr.Code) + } + }) + } +} + +func TestUIDeleteRemovesRow(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodDelete, "/ui/bookmarks/asura:solo", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("delete status = %d, want 200", rr.Code) + } + if rr.Body.Len() != 0 { + t.Fatalf("delete body = %q, want empty so htmx swaps the card away", rr.Body.String()) + } + if _, ok, _ := store.Get("asura:solo"); ok { + t.Fatal("row still present after delete") + } +} + +func TestUIListFavouritesTab(t *testing.T) { + cfg := webConfig() + srv, store := newWebTestServer(t, cfg) + seed(t, store, Bookmark{ + Key: "asura:solo", Site: "asura", SeriesID: "solo", + Title: "Solo Leveling", Favorite: true, UpdatedAt: 2_000_000, + }) + seed(t, store, Bookmark{ + Key: "demonic:tower", Site: "demonic", SeriesID: "tower", + Title: "Tower of God", Favorite: false, UpdatedAt: 1_000_000, + }) + + rr := httptest.NewRecorder() + srv.ServeHTTP(rr, uiRequest(t, cfg, http.MethodGet, "/ui/list?tab=fav", nil)) + if rr.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rr.Code) + } + body := rr.Body.String() + if !strings.Contains(body, "Solo Leveling") { + t.Fatal("favourites tab omitted the favourited series") + } + if strings.Contains(body, "Tower of God") { + t.Fatal("favourites tab included a non-favourite") + } +} +``` + +- [ ] **Step 2: Run the tests to verify they fail** + +Run: `cd backend && go test ./... -run 'TestUI|TestFavorite|TestChapter|TestMutations' -v` +Expected: FAIL — the mutation routes are unregistered, so `/ui/bookmarks/...` returns 404 where 401 or 200 is expected. + +- [ ] **Step 3: Register the routes** + +In `backend/web.go`, add to `register`, below the `GET /ui/list` line: + +```go + mux.HandleFunc("POST /ui/bookmarks/{key}/favorite", h.requireSession(h.uiFavorite)) + mux.HandleFunc("POST /ui/bookmarks/{key}/chapter", h.requireSession(h.uiChapter)) + mux.HandleFunc("DELETE /ui/bookmarks/{key}", h.requireSession(h.uiDelete)) +``` + +- [ ] **Step 4: Implement the handlers** + +Append to `backend/web.go`: + +```go +// loadForMutation fetches the row a mutation targets, writing the error +// response itself when there is nothing to mutate. +func (h *webHandler) loadForMutation(w http.ResponseWriter, r *http.Request) (Bookmark, bool) { + key := r.PathValue("key") + if key == "" { + http.Error(w, "missing key", http.StatusBadRequest) + return Bookmark{}, false + } + b, ok, err := h.store.Get(key) + if err != nil { + log.Printf("ui get %q: %v", key, err) + http.Error(w, "internal error", http.StatusInternalServerError) + return Bookmark{}, false + } + if !ok { + http.Error(w, "not found", http.StatusNotFound) + return Bookmark{}, false + } + return b, true +} + +// saveAndRenderCard upserts and renders the row as stored. Upsert decides +// whether updated_at moves, so the argument's timestamp is only a candidate and +// the response must come from the return value. +func (h *webHandler) saveAndRenderCard(w http.ResponseWriter, b Bookmark) { + stored, err := h.store.Upsert(b) + if err != nil { + log.Printf("ui upsert %q: %v", b.Key, err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + h.render(w, http.StatusOK, "card", stored) +} + +// uiFavorite flips the favourite flag. last_chapter_num is untouched, so +// Upsert keeps the stored updated_at and the list does not reorder. +func (h *webHandler) uiFavorite(w http.ResponseWriter, r *http.Request) { + b, ok := h.loadForMutation(w, r) + if !ok { + return + } + b.Favorite = !b.Favorite + b.UpdatedAt = time.Now().UnixMilli() + h.saveAndRenderCard(w, b) +} + +// uiChapter forces the read chapter to a value the user typed. +// +// It clears last_chapter_url: that URL points at the chapter actually read, and +// once the number is forced elsewhere it would send the reader backwards. +// ContinueURL then falls back to the series page, which is always right. +func (h *webHandler) uiChapter(w http.ResponseWriter, r *http.Request) { + b, ok := h.loadForMutation(w, r) + if !ok { + return + } + if err := r.ParseForm(); err != nil { + http.Error(w, "invalid form", http.StatusBadRequest) + return + } + raw := strings.TrimSpace(r.PostFormValue("chapter")) + num, err := strconv.ParseFloat(raw, 64) + if err != nil || num < 0 { + http.Error(w, "chapter must be a non-negative number", http.StatusBadRequest) + return + } + + b.LastChapter = raw + b.LastChapterNum = num + b.LastChapterURL = "" + b.UpdatedAt = time.Now().UnixMilli() + h.saveAndRenderCard(w, b) +} + +// uiDelete removes the row and answers with an empty body, which htmx swaps in +// place of the card — removing it from the page. +func (h *webHandler) uiDelete(w http.ResponseWriter, r *http.Request) { + key := r.PathValue("key") + if key == "" { + http.Error(w, "missing key", http.StatusBadRequest) + return + } + if err := h.store.Delete(key); err != nil { + log.Printf("ui delete %q: %v", key, err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(http.StatusOK) +} +``` + +Add `"strings"` to the import block in `backend/web.go`. + +- [ ] **Step 5: Add the controls to the card template** + +Replace the `
` block in `backend/templates/card.html` with: + +```html +
+ Continue + + + +
+ +``` + +- [ ] **Step 6: Add the toggle helper** + +Append to `backend/static/filter.js`: + +```js +function toggleChapterForm(key) { + var form = document.getElementById("chapter-form-" + key); + if (!form) return; + form.hidden = !form.hidden; + if (!form.hidden) form.querySelector("input").focus(); +} +``` + +- [ ] **Step 7: Run the tests to verify they pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS. `TestFavoriteTogglesWithoutReordering` is the important one — it is the regression guard on the `updated_at` rule. + +- [ ] **Step 8: Commit** + +```bash +gofmt -w backend/web.go backend/web_test.go +git add backend/web.go backend/web_test.go backend/templates/card.html backend/static/filter.js +git commit -m "feat(backend): favourite, chapter override, and delete fragments" +``` + +--- + +### Task 7: Styling and client-side search + +**Files:** +- Modify: `backend/static/style.css`, `backend/static/filter.js` + +**Interfaces:** +- Consumes: the class names in the templates from Tasks 5 and 6 — `login-body`, `login-card`, `error`, `topbar`, `ghost`, `search`, `tabs`, `active`, `recent`, `recent-strip`, `recent-card`, `recent-title`, `recent-chapter`, `list`, `card`, `cover`, `body`, `title`, `meta`, `site`, `chapter`, `new`, `actions`, `primary`, `icon`, `on`, `danger`, `chapter-form`, `empty`. The card carries `data-title` for the search filter. +- Produces: nothing other tasks consume. + +- [ ] **Step 1: Write the stylesheet** + +Replace the whole of `backend/static/style.css`: + +```css +/* Mobile first. Dark by default because manga reading happens at night; the + light branch follows the system preference. */ +:root { + color-scheme: dark light; + --bg: #14161a; + --surface: #1d2026; + --surface-2: #262a32; + --text: #e8eaed; + --muted: #9aa1ac; + --accent: #6aa9ff; + --danger: #ff6a6a; + --star: #ffc857; + --radius: 12px; +} + +@media (prefers-color-scheme: light) { + :root { + --bg: #f4f5f7; + --surface: #ffffff; + --surface-2: #eceef2; + --text: #1a1d22; + --muted: #5d646e; + } +} + +* { box-sizing: border-box; } + +body { + margin: 0; + padding: 0 12px calc(24px + env(safe-area-inset-bottom)); + background: var(--bg); + color: var(--text); + font: 16px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; +} + +/* Every interactive element clears the 44px touch-target floor. */ +button, .primary, [role="tab"] { + min-height: 44px; + border-radius: var(--radius); + border: 0; + font: inherit; + cursor: pointer; +} + +/* --- login --- */ + +.login-body { + display: grid; + place-items: center; + min-height: 100dvh; +} + +.login-card { + width: min(380px, 100%); + padding: 24px; + background: var(--surface); + border-radius: var(--radius); +} + +.login-card h1 { margin: 0 0 20px; font-size: 1.25rem; } +.login-card label { display: block; margin-bottom: 6px; color: var(--muted); font-size: .875rem; } + +.login-card input { + width: 100%; + min-height: 44px; + padding: 0 12px; + margin-bottom: 12px; + background: var(--surface-2); + color: var(--text); + border: 1px solid transparent; + border-radius: var(--radius); + font: inherit; +} + +.login-card input:focus-visible { outline: 2px solid var(--accent); } +.login-card button { width: 100%; background: var(--accent); color: #0b1220; font-weight: 600; } +.error { margin: 0 0 12px; color: var(--danger); font-size: .875rem; } + +/* --- chrome --- */ + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 0; +} + +.topbar h1 { margin: 0; font-size: 1.125rem; } +.ghost { padding: 0 12px; background: var(--surface-2); color: var(--muted); } + +.search { + width: 100%; + min-height: 44px; + padding: 0 12px; + margin-bottom: 12px; + background: var(--surface); + color: var(--text); + border: 1px solid transparent; + border-radius: var(--radius); + font: inherit; +} + +.search:focus-visible { outline: 2px solid var(--accent); } + +.tabs { display: flex; gap: 8px; margin-bottom: 16px; } + +.tabs [role="tab"] { + flex: 1; + display: grid; + place-items: center; + background: var(--surface); + color: var(--muted); + text-decoration: none; +} + +.tabs [role="tab"].active { background: var(--accent); color: #0b1220; font-weight: 600; } + +/* --- continue reading --- */ + +.recent h2 { margin: 0 0 8px; font-size: .8125rem; text-transform: uppercase; color: var(--muted); } + +.recent-strip { + display: flex; + gap: 10px; + overflow-x: auto; + padding-bottom: 8px; + margin-bottom: 16px; + scroll-snap-type: x mandatory; + -webkit-overflow-scrolling: touch; +} + +.recent-card { + flex: 0 0 110px; + scroll-snap-align: start; + display: block; + padding: 8px; + background: var(--surface); + border-radius: var(--radius); + color: var(--text); + text-decoration: none; +} + +.recent-card img { width: 100%; aspect-ratio: 3 / 4; object-fit: cover; border-radius: 8px; } +.recent-title { display: block; margin-top: 6px; font-size: .8125rem; line-height: 1.25; + overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } +.recent-chapter { display: block; color: var(--muted); font-size: .75rem; } + +/* --- list --- */ + +.list { display: grid; gap: 10px; } + +.card { + display: grid; + grid-template-columns: 72px 1fr; + gap: 12px; + padding: 10px; + background: var(--surface); + border-radius: var(--radius); +} + +.card .cover img { width: 72px; aspect-ratio: 3 / 4; object-fit: cover; border-radius: 8px; } +.card .body { min-width: 0; } +.card .title { margin: 0 0 4px; font-size: 1rem; line-height: 1.25; } + +.meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 0 0 10px; + font-size: .75rem; color: var(--muted); } + +.site { padding: 2px 6px; background: var(--surface-2); border-radius: 6px; text-transform: uppercase; } +.new { padding: 2px 6px; background: var(--accent); color: #0b1220; border-radius: 6px; font-weight: 700; } + +.actions { display: flex; flex-wrap: wrap; gap: 8px; } + +.primary { + flex: 1 1 auto; + display: grid; + place-items: center; + padding: 0 14px; + background: var(--accent); + color: #0b1220; + font-weight: 600; + text-decoration: none; +} + +.icon { width: 44px; background: var(--surface-2); color: var(--text); font-size: 1.125rem; } +.icon.on { color: var(--star); } +.icon.danger { color: var(--danger); } + +.chapter-form { display: flex; gap: 8px; margin-top: 8px; } + +.chapter-form input { + flex: 1; + min-height: 44px; + padding: 0 12px; + background: var(--surface-2); + color: var(--text); + border: 1px solid transparent; + border-radius: var(--radius); + font: inherit; +} + +.chapter-form button { padding: 0 14px; background: var(--accent); color: #0b1220; font-weight: 600; } +.empty { padding: 32px 12px; text-align: center; color: var(--muted); } + +/* Cards hidden by the search filter. */ +.card[hidden] { display: none; } + +/* --- wide screens --- */ + +@media (min-width: 900px) { + body { max-width: 1100px; margin: 0 auto; padding-inline: 24px; } + .list { grid-template-columns: repeat(2, 1fr); } + .recent-card { flex-basis: 140px; } +} + +@media (min-width: 1300px) { + .list { grid-template-columns: repeat(3, 1fr); } +} + +@media (prefers-reduced-motion: reduce) { + * { animation: none !important; transition: none !important; } +} +``` + +- [ ] **Step 2: Write the search filter** + +Replace the whole of `backend/static/filter.js`: + +```js +// Title search runs entirely in the browser: the full list is already in the +// DOM, so filtering it needs no request. +(function () { + function applyFilter() { + var box = document.getElementById("search"); + if (!box) return; + var needle = box.value.trim().toLowerCase(); + document.querySelectorAll(".card").forEach(function (card) { + var title = (card.dataset.title || "").toLowerCase(); + card.hidden = needle !== "" && title.indexOf(needle) === -1; + }); + } + + document.addEventListener("input", function (e) { + if (e.target && e.target.id === "search") applyFilter(); + }); + + // htmx replaces the list on a tab switch, so re-apply to the new cards. + document.body.addEventListener("htmx:afterSwap", applyFilter); +})(); + +function setActiveTab(el) { + el.parentElement.querySelectorAll("[role=tab]").forEach(function (t) { + t.classList.toggle("active", t === el); + }); +} + +function toggleChapterForm(key) { + var form = document.getElementById("chapter-form-" + key); + if (!form) return; + form.hidden = !form.hidden; + if (!form.hidden) form.querySelector("input").focus(); +} +``` + +- [ ] **Step 3: Verify the tests still pass** + +Run: `cd backend && go test ./... -v` +Expected: PASS. `TestStaticAssetsServed` confirms both files are still embedded and non-empty. + +- [ ] **Step 4: Look at it in a real browser** + +```bash +cd backend +API_TOKEN=dev-token WEB_PASSWORD=dev-pass DB_PATH=/tmp/mangabm-dev.db PORT=8080 go run . +``` + +Seed a row so there is something to look at: + +```bash +curl -X PUT http://localhost:8080/bookmarks/asura:solo \ + -H "Authorization: Bearer dev-token" -H "Content-Type: application/json" \ + -d '{"title":"Solo Leveling","series_url":"https://example.test/solo","last_chapter":"45","last_chapter_num":45,"latest_chapter":"47","latest_chapter_num":47}' +``` + +Open `http://localhost:8080/`, sign in with `dev-pass`, and confirm by hand: +- the login page rejects a wrong password and accepts the right one; +- the card shows the `NEW 47` badge; +- the star toggles and the card does not jump position; +- ✎ opens the number input and saving updates the chapter; +- 🗑 asks for confirmation and removes the card; +- typing in the search box filters; +- switching to Favourites and back works, and the browser back button follows; +- at a narrow width (device toolbar, 390px) nothing overflows horizontally. + +Stop the server when done. + +- [ ] **Step 5: Commit** + +```bash +git add backend/static/style.css backend/static/filter.js +git commit -m "feat(backend): mobile-first styling and client-side title search" +``` + +--- + +### Task 8: Docker, compose, and deployment docs + +**Files:** +- Modify: `backend/Dockerfile`, `docker-compose.yml`, `docker-compose.prod.yml`, `.env.example`, `DEPLOY.md`, `CLAUDE.md` + +**Interfaces:** +- Consumes: `WEB_PASSWORD` (Task 4), the `templates/` and `static/` directories (Tasks 5–7). +- Produces: nothing other tasks consume. + +**This task is required, not optional.** The current Dockerfile copies only `*.go`; without the change the image builds and then panics at startup on the missing embedded directories. + +- [ ] **Step 1: Fix the Dockerfile** + +In `backend/Dockerfile`, replace the line: + +```dockerfile +COPY *.go ./ +``` + +with: + +```dockerfile +# Source plus the go:embed'd assets. Missing either directory turns the embed +# directive into a build error, so both must be copied before `go build`. +COPY *.go ./ +COPY templates/ ./templates/ +COPY static/ ./static/ +``` + +- [ ] **Step 2: Verify the image builds and runs** + +```bash +docker build -t mangabm-backend:test ./backend +docker run --rm -e API_TOKEN=dev-token -e WEB_PASSWORD=dev-pass \ + -e DB_PATH=/tmp/test.db -p 8080:8080 mangabm-backend:test & +sleep 2 +curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/healthz +curl -s http://localhost:8080/ | grep -c 'type="password"' +curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8080/static/htmx.min.js +``` + +Expected: `200`, then `1`, then `200`. Stop the container afterwards (`docker stop $(docker ps -q --filter ancestor=mangabm-backend:test)`). + +If the build fails with `pattern templates: no matching files found`, the COPY lines are wrong or in the wrong stage. + +- [ ] **Step 3: Pass the password through compose** + +In `docker-compose.yml`, add to the `environment:` block under `manga-api`: + +```yaml + # Gates the browser UI. Unset means the web routes are not served at all. + WEB_PASSWORD: ${WEB_PASSWORD:-} +``` + +- [ ] **Step 4: Add the second Traefik router** + +In `docker-compose.prod.yml`, add to the `labels:` list. Both routers point at the one `mangabm` service, so there is no second container and no second certificate resolver: + +```yaml + # Second hostname for the browser UI, same container. Traefik needs the + # service named explicitly once more than one router targets it. + - "traefik.http.routers.mangabm.service=mangabm" + - "traefik.http.routers.mangaweb.rule=Host(`${MANGA_WEB_HOST:-manga.example.com}`)" + - "traefik.http.routers.mangaweb.entrypoints=${TRAEFIK_ENTRYPOINT:-websecure}" + - "traefik.http.routers.mangaweb.tls=true" + - "traefik.http.routers.mangaweb.tls.certresolver=${TRAEFIK_CERTRESOLVER:-le}" + - "traefik.http.routers.mangaweb.service=mangabm" +``` + +Also update the header comment block in that file to list `MANGA_WEB_HOST` alongside `MANGA_API_HOST`. + +- [ ] **Step 5: Document the variables** + +Append to `.env.example`: + +```ini +# --- Web UI --- +# Password for the browser UI at https://$MANGA_WEB_HOST. Leave unset to +# disable the web UI entirely (the routes are not registered at all). +# Generate one: openssl rand -base64 18 +WEB_PASSWORD= + +# Subdomain Traefik routes to the browser UI (prod override only). The same +# container also answers on MANGA_API_HOST for the userscript's API. +# MANGA_WEB_HOST=manga.example.com +``` + +Add a section to `DEPLOY.md` after the existing `.env` section: + +```markdown +## 1b. Web UI + +The browser UI is served by the same container on a second hostname. + +1. Add a DNS `A`/`AAAA` record for `manga.` pointing at the server — + the same address as `manga-api.`. + +2. Set both variables in `.env`: + + ```ini + MANGA_WEB_HOST=manga.violetcrown.my.id + WEB_PASSWORD= + ``` + + Generate and insert in one line: + + ```bash + sed -i "s|^WEB_PASSWORD=.*|WEB_PASSWORD=$(openssl rand -base64 18)|" .env + grep -E '^WEB_PASSWORD=' .env # this is what you type into the site + ``` + +3. Redeploy and check: + + ```bash + docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d --build + curl -s -o /dev/null -w '%{http_code}\n' https://manga.violetcrown.my.id/ + ``` + + Expected `200`, serving the login page. + +Leaving `WEB_PASSWORD` unset is safe: the web routes are not registered and `/` +returns 404. The userscript's API on `MANGA_API_HOST` is unaffected either way. + +Sessions are signed with a key derived from `API_TOKEN`, so rotating the token +logs every browser out. The session cookie lasts 60 days. +``` + +- [ ] **Step 6: Update the project instructions** + +In `CLAUDE.md`, under **Architecture**, add after the `Endpoints:` bullet: + +```markdown +- **Web UI:** the same binary serves a password-gated browser UI on a second + hostname — `GET /` (list, or login page when there is no session), + `POST /login`, `POST /logout`, `GET /static/*`, and htmx fragment endpoints + under `/ui/*`. Templates and assets are `go:embed`-ed, so `backend/Dockerfile` + must copy `templates/` and `static/` as well as `*.go`. Sessions are stateless + HMAC cookies keyed off `API_TOKEN`; `WEB_PASSWORD` gates them and, when empty, + the web routes are not registered at all. UI mutations read-modify-write + through `Store.Get` + `Store.Upsert` so the `updated_at` rule stays in one + place. See `docs/superpowers/specs/2026-07-25-web-ui-design.md`. +``` + +Add `WEB_PASSWORD` to the **Config via env** bullet in the same file. + +- [ ] **Step 7: Full verification** + +```bash +cd backend +gofmt -l . # expect no output +go vet ./... # expect no output +go test -race ./... # expect ok +CGO_ENABLED=0 go build -o /dev/null . +``` + +All four must pass before committing. + +- [ ] **Step 8: Commit** + +```bash +git add backend/Dockerfile docker-compose.yml docker-compose.prod.yml .env.example DEPLOY.md CLAUDE.md +git commit -m "chore: build, route, and document the web UI" +``` + +--- + +## Self-Review Notes + +Spec coverage check against `docs/superpowers/specs/2026-07-25-web-ui-design.md`: + +| Spec section | Task | +| --- | --- | +| §3.1 all eight routes | 5 (`/`, `/login`, `/logout`, `/static/*`, `/ui/list`), 6 (three mutations) | +| §3.2 `Store.Get`, read-modify-write | 1, 6 | +| §4.1 `WEB_PASSWORD`, fail-closed 404 | 4, 5 | +| §4.2 cookie format, attributes, verify order | 2 | +| §4.3 CSRF via SameSite=Lax | 2 (attribute), no extra work | +| §4.4 rate limit, rightmost XFF | 3, 5 | +| §5.1 login page | 5 | +| §5.2 list page, strip, NEW badge, actions, search, empty state | 5, 6, 7 | +| §5.3 tabs with pushed URL | 5 | +| §6 test list | 1, 2, 3, 5, 6 | +| §7 deployment | 8 | + +One decision was added during planning and is not in the spec: **a manual chapter override clears `last_chapter_url`** (Task 6). Recorded in the task and covered by `TestChapterOverrideRejectsBadInput`'s sibling `TestChapterOverrideMovesUpdatedAt`.