diff --git a/.env.example b/.env.example index f8b418e..1f13f52 100644 --- a/.env.example +++ b/.env.example @@ -15,8 +15,11 @@ EMAIL_AGENT_LOG_LEVEL=info EMAIL_AGENT_PUBLIC_BASE_URL=https://mail.lab.audasmedia.com.au # --- Session / auth -------------------------------------------------------- -# Generate with: openssl rand -hex 32 +# Session cookie signing key. Generate with: python3 -c 'import secrets;print(secrets.token_hex(32))' EMAIL_AGENT_SESSION_SECRET=change-me +# Login password for the single user (Sam). If unset, the session secret above +# doubles as the password. +EMAIL_AGENT_PASSWORD= # --- Integrations (used from later phases) --------------------------------- JEV_BASE_URL= diff --git a/README.md b/README.md index 0d9bdde..486ccbf 100644 --- a/README.md +++ b/README.md @@ -9,19 +9,22 @@ pre-planning material and is not authoritative. ## Status -**Phase 1.1 — Go service skeleton.** Complete when this file was written: -config from the environment, SQLite schema init, `GET /health`, Dockerfile and -docker-compose. Mail fetch, classification, login, and the HTMX screens come in -later phases. +**Phase 1.2 — Session login + empty dashboard.** The Go skeleton (Phase 1.1) +plus a single-user session login, a copied Family Home Lab `tokens.css`, and an +HTMX dashboard shell (left nav, centre list, right detail pane) with dark mode. +Mail fetch, classification, and the rest come in later phases. ## Layout ``` cmd/email-agent/ service entry point internal/config/ environment-driven configuration +internal/session/ server-side session store + signed cookie values internal/store/ SQLite open + schema (internal/store/schema.sql) -internal/server/ HTTP routes and middleware +internal/server/ HTTP routes, auth middleware, HTMX handlers internal/version/ build metadata (set via -ldflags) +web/static/ embedded design tokens, Inter fonts, htmx, app.css +web/templates/ embedded server-rendered HTML Dockerfile multi-stage, CGO-free build docker-compose.yml this project's own container and image ``` @@ -42,7 +45,8 @@ Key variables: | `EMAIL_AGENT_PORT` | `8790` | Listen port (used when `EMAIL_AGENT_ADDR` is unset) | | `EMAIL_AGENT_DB_PATH` | `data/email_agent.db` | SQLite file | | `EMAIL_AGENT_LOG_LEVEL` | `info` | `debug`, `info`, `warn`, `error` | -| `EMAIL_AGENT_SESSION_SECRET` | _(empty)_ | Session cookie signing key (Phase 1.2) | +| `EMAIL_AGENT_SESSION_SECRET` | _(empty)_ | Session cookie signing key. If unset, an ephemeral key is used (sessions reset on restart) | +| `EMAIL_AGENT_PASSWORD` | _(empty)_ | Login password for Sam. If unset, `EMAIL_AGENT_SESSION_SECRET` doubles as the password | ## Run locally @@ -65,11 +69,20 @@ Caddy on `.35` proxies `mail.lab.audasmedia.com.au` to this port. ## Endpoints (Phase 1) -| Method | Path | Purpose | -|---|---|---| -| `GET` | `/health` | Liveness + database check, JSON | -| `GET` | `/readyz` | Readiness, JSON | -| `GET` | `/` | Placeholder dashboard (real screens in Phase 1.2) | +| Method | Path | Auth | Purpose | +|---|---|---|---| +| `GET` | `/health` | public | Liveness + database check, JSON | +| `GET` | `/readyz` | public | Readiness, JSON | +| `GET` | `/login` | public | Sign-in form (deep-indigo band) | +| `POST` | `/login` | public | CSRF-checked password sign-in, sets the session cookie | +| `POST` | `/logout` | session | Destroys the session, returns to `/login` | +| `GET` | `/` | session | Empty dashboard shell | +| `GET` | `/partials/inbox` | session | HTMX fragment for the centre list | +| `GET` | `/static/…` | public | Embedded `tokens.css`, `app.css`, Inter fonts, `htmx.min.js` | + +Unauthenticated requests to `/` and `/partials/…` redirect to `/login?next=…`. +Form posts use a double-submit CSRF token (`email_agent_csrf` cookie plus a +hidden `csrf` field). ## Database diff --git a/cmd/email-agent/main.go b/cmd/email-agent/main.go index 7025622..f27ba1f 100644 --- a/cmd/email-agent/main.go +++ b/cmd/email-agent/main.go @@ -60,8 +60,8 @@ func run(cfg *config.Config, logger *slog.Logger) error { "env", cfg.Env, ) - if cfg.SessionSecret == "" { - logger.Warn("EMAIL_AGENT_SESSION_SECRET is not set; set it before enabling login") + if cfg.SessionSecret == "" && cfg.Password == "" { + logger.Warn("no EMAIL_AGENT_PASSWORD or EMAIL_AGENT_SESSION_SECRET set; login is disabled until one is configured") } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) diff --git a/docker-compose.yml b/docker-compose.yml index 7760bf3..57a0a94 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -30,6 +30,7 @@ services: # (see ~/.config/environment.d/10-secrets.conf) or a gitignored .env file, # and are never committed. EMAIL_AGENT_SESSION_SECRET: ${EMAIL_AGENT_SESSION_SECRET:-} + EMAIL_AGENT_PASSWORD: ${EMAIL_AGENT_PASSWORD:-} JEV_BASE_URL: ${JEV_BASE_URL:-} JEV_API_KEY: ${JEV_API_KEY:-} OMNIROUTE_BASE_URL: ${OMNIROUTE_BASE_URL:-} diff --git a/internal/config/config.go b/internal/config/config.go index f244e5a..a19e371 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -42,6 +42,10 @@ type Config struct { // service has a single configuration surface. SessionSecret string + // Password is the single-user login password. When it is empty the service + // falls back to SessionSecret so one configured secret is enough. Secret. + Password string + // LogLevel controls slog verbosity: debug, info, warn, error. LogLevel string @@ -75,6 +79,7 @@ func Load() (*Config, error) { c := &Config{ Env: getenvDefault("EMAIL_AGENT_ENV", DefaultEnv), SessionSecret: os.Getenv("EMAIL_AGENT_SESSION_SECRET"), + Password: os.Getenv("EMAIL_AGENT_PASSWORD"), LogLevel: strings.ToLower(getenvDefault("EMAIL_AGENT_LOG_LEVEL", "info")), PublicBaseURL: strings.TrimRight(getenvDefault("EMAIL_AGENT_PUBLIC_BASE_URL", "http://localhost:8790"), "/"), JEVBaseURL: strings.TrimRight(os.Getenv("JEV_BASE_URL"), "/"), diff --git a/internal/server/auth.go b/internal/server/auth.go new file mode 100644 index 0000000..c0ff3d3 --- /dev/null +++ b/internal/server/auth.go @@ -0,0 +1,284 @@ +package server + +import ( + "context" + "crypto/subtle" + "net/http" + "net/url" + "strings" + "time" + + "gitea.lab.audasmedia.com.au/sam/email_agent/internal/session" + "gitea.lab.audasmedia.com.au/sam/email_agent/internal/version" +) + +const ( + // csrfCookieName holds the double-submit CSRF token. It is independent of + // the session so the login form (which has no session yet) is protected too. + csrfCookieName = "email_agent_csrf" + sessionTTL = session.DefaultTTL +) + +// ctxKey is the private context key type for request-scoped values. +type ctxKey int + +const sessionCtxKey ctxKey = iota + +// requireAuth redirects unauthenticated requests to the login screen and +// otherwise puts the session on the request context. +func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + sess, ok := s.currentSession(r) + if !ok { + target := "/login?next=" + url.QueryEscape(r.URL.RequestURI()) + http.Redirect(w, r, target, http.StatusSeeOther) + return + } + next(w, r.WithContext(context.WithValue(r.Context(), sessionCtxKey, sess))) + } +} + +func (s *Server) currentSession(r *http.Request) (session.Session, bool) { + c, err := r.Cookie(session.CookieName) + if err != nil || c.Value == "" { + return session.Session{}, false + } + return s.sessions.Lookup(c.Value) +} + +func sessionFrom(r *http.Request) session.Session { + sess, _ := r.Context().Value(sessionCtxKey).(session.Session) + return sess +} + +// loginSecret is the password the single user must supply. EMAIL_AGENT_PASSWORD +// wins; otherwise the session secret doubles as the password so a single +// configured secret is enough. +func (s *Server) loginSecret() string { + if s.cfg.Password != "" { + return s.cfg.Password + } + return s.cfg.SessionSecret +} + +// csrfToken returns the current double-submit token, minting one when absent. +func (s *Server) csrfToken(w http.ResponseWriter, r *http.Request) string { + if c, err := r.Cookie(csrfCookieName); err == nil && c.Value != "" { + return c.Value + } + tok, err := session.RandomToken(32) + if err != nil { + // crypto/rand failing is fatal for security; surface it rather than + // issuing an unprotected form. + s.logger.Error("csrf token generation failed", "error", err) + return "" + } + http.SetCookie(w, &http.Cookie{ + Name: csrfCookieName, + Value: tok, + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.cfg.IsProduction(), + MaxAge: int(sessionTTL.Seconds()), + }) + return tok +} + +// csrfOK verifies the double-submit token from the form or the X-CSRF-Token +// header. +func (s *Server) csrfOK(r *http.Request) bool { + c, err := r.Cookie(csrfCookieName) + if err != nil || c.Value == "" { + return false + } + tok := r.FormValue("csrf") + if tok == "" { + tok = r.Header.Get("X-CSRF-Token") + } + return subtle.ConstantTimeCompare([]byte(tok), []byte(c.Value)) == 1 +} + +func (s *Server) setSessionCookie(w http.ResponseWriter, value string, expires time.Time) { + http.SetCookie(w, &http.Cookie{ + Name: session.CookieName, + Value: value, + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.cfg.IsProduction(), + Expires: expires, + MaxAge: int(sessionTTL.Seconds()), + }) +} + +func (s *Server) clearSessionCookie(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: session.CookieName, + Value: "", + Path: "/", + HttpOnly: true, + SameSite: http.SameSiteLaxMode, + Secure: s.cfg.IsProduction(), + MaxAge: -1, + }) +} + +type loginData struct { + PartOfDay string + Error string + Next string + CSRFToken string + Configured bool +} + +func (s *Server) renderLogin(w http.ResponseWriter, r *http.Request, code int, errMsg, next string) { + // Mint the CSRF cookie before the status line, or Set-Cookie is dropped. + csrf := s.csrfToken(w, r) + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(code) + data := loginData{ + PartOfDay: partOfDay(time.Now()), + Error: errMsg, + Next: next, + CSRFToken: csrf, + Configured: s.loginSecret() != "", + } + if err := s.tmpl.ExecuteTemplate(w, "login.html", data); err != nil { + s.logger.Error("render login", "error", err) + } +} + +// handleLoginGet renders the sign-in form. +func (s *Server) handleLoginGet(w http.ResponseWriter, r *http.Request) { + if _, ok := s.currentSession(r); ok { + http.Redirect(w, r, cleanNext(r.URL.Query().Get("next")), http.StatusSeeOther) + return + } + s.renderLogin(w, r, http.StatusOK, "", cleanNext(r.URL.Query().Get("next"))) +} + +// handleLoginPost validates the CSRF token and password, then starts a session. +// POST (not GET) means the password is never placed in the URL or browser +// history. +func (s *Server) handleLoginPost(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + s.renderLogin(w, r, http.StatusBadRequest, "Could not read the sign-in form.", "/") + return + } + next := cleanNext(r.FormValue("next")) + + if !s.csrfOK(r) { + s.renderLogin(w, r, http.StatusForbidden, "Your sign-in page expired. Please try again.", next) + return + } + + secret := s.loginSecret() + if secret == "" { + s.renderLogin(w, r, http.StatusServiceUnavailable, "Login is not configured yet.", next) + return + } + + if subtle.ConstantTimeCompare([]byte(r.FormValue("password")), []byte(secret)) != 1 { + s.logger.Warn("login failed", "remote", r.RemoteAddr) + s.renderLogin(w, r, http.StatusUnauthorized, "Incorrect password.", next) + return + } + + sess, cookie, err := s.sessions.New("Sam") + if err != nil { + s.logger.Error("create session", "error", err) + http.Error(w, "could not start a session", http.StatusInternalServerError) + return + } + s.setSessionCookie(w, cookie, sess.ExpiresAt) + s.logger.Info("login ok", "user", sess.User, "remote", r.RemoteAddr) + http.Redirect(w, r, next, http.StatusSeeOther) +} + +// handleLogout destroys the session and returns to the login screen. +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + _ = r.ParseForm() + if !s.csrfOK(r) { + http.Error(w, "invalid CSRF token", http.StatusForbidden) + return + } + if c, err := r.Cookie(session.CookieName); err == nil && c.Value != "" { + s.sessions.Destroy(c.Value) + } + s.clearSessionCookie(w) + http.Redirect(w, r, "/login", http.StatusSeeOther) +} + +type navItem struct { + Name string + Color string +} + +type dashboardData struct { + Greeting string + User string + CSRFToken string + Version string + Categories []navItem + Folders []navItem +} + +// handleDashboard renders the empty inbox shell. +func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { + sess := sessionFrom(r) + data := dashboardData{ + Greeting: partOfDay(time.Now()), + User: sess.User, + CSRFToken: s.csrfToken(w, r), + Version: version.Version, + // Placeholders until FR-14 (editable categories) and FR-9 (folders) + // land. Colours are the design system's decorative sticker palette. + Categories: []navItem{ + {Name: "Action", Color: "var(--primary)"}, + {Name: "Important", Color: "var(--sticker-orange)"}, + {Name: "Info", Color: "var(--sticker-sky)"}, + {Name: "Spam", Color: "var(--sticker-red)"}, + {Name: "Newsletter", Color: "var(--sticker-purple)"}, + {Name: "Auto-reply", Color: "var(--sticker-teal)"}, + }, + Folders: []navItem{ + {Name: "Replied-to", Color: "var(--sticker-green)"}, + {Name: "Delete", Color: "var(--sticker-red)"}, + {Name: "Saved", Color: "var(--sticker-teal)"}, + }, + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := s.tmpl.ExecuteTemplate(w, "dashboard.html", data); err != nil { + s.logger.Error("render dashboard", "error", err) + } +} + +// handleInboxPartial is the HTMX fragment for the centre list. Phase 1.2 has no +// mail yet, so it renders the empty state. +func (s *Server) handleInboxPartial(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := s.tmpl.ExecuteTemplate(w, "inbox.html", nil); err != nil { + s.logger.Error("render inbox partial", "error", err) + } +} + +// cleanNext only allows same-site, absolute-path redirects. +func cleanNext(next string) string { + if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") { + return "/" + } + return next +} + +// partOfDay returns the time-aware greeting prefix. +func partOfDay(t time.Time) string { + switch h := t.Hour(); { + case h < 12: + return "Good morning" + case h < 18: + return "Good afternoon" + default: + return "Good evening" + } +} diff --git a/internal/server/server.go b/internal/server/server.go index b078024..67f7097 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -1,45 +1,66 @@ // Package server wires the HTTP surface of the Email Agent. // -// Phase 1 exposes liveness/readiness endpoints and a placeholder dashboard. -// Login and the real HTMX screens arrive in Phase 1.2. +// Phase 1.2 exposes a session login and an empty HTMX dashboard shell in the +// Family Home Lab design system. Mail fetch arrives in Phase 2. package server import ( "context" + "crypto/rand" "encoding/json" "errors" "fmt" "html/template" + "io/fs" "log/slog" + "mime" "net/http" "time" "gitea.lab.audasmedia.com.au/sam/email_agent/internal/config" + "gitea.lab.audasmedia.com.au/sam/email_agent/internal/session" "gitea.lab.audasmedia.com.au/sam/email_agent/internal/store" "gitea.lab.audasmedia.com.au/sam/email_agent/internal/version" + "gitea.lab.audasmedia.com.au/sam/email_agent/web" ) +func init() { + // Go's mime table has no woff2 entry; the self-hosted Inter fonts need it. + _ = mime.AddExtensionType(".woff2", "font/woff2") +} + // Server holds the HTTP dependencies. type Server struct { - cfg *config.Config - store *store.Store - logger *slog.Logger - http *http.Server - index *template.Template + cfg *config.Config + store *store.Store + logger *slog.Logger + http *http.Server + tmpl *template.Template + sessions *session.Manager } // New builds a Server. It does not start listening. func New(cfg *config.Config, st *store.Store, logger *slog.Logger) (*Server, error) { - index, err := template.New("index").Parse(indexHTML) + tmpl, err := template.ParseFS(web.TemplateFS, "templates/*.html") if err != nil { - return nil, fmt.Errorf("parse index template: %w", err) + return nil, fmt.Errorf("parse templates: %w", err) + } + + key, err := sessionKey(cfg, logger) + if err != nil { + return nil, fmt.Errorf("session key: %w", err) + } + sessions, err := session.NewManager(key, session.DefaultTTL) + if err != nil { + return nil, fmt.Errorf("session manager: %w", err) } s := &Server{ - cfg: cfg, - store: st, - logger: logger, - index: index, + cfg: cfg, + store: st, + logger: logger, + tmpl: tmpl, + sessions: sessions, } s.http = &http.Server{ Addr: cfg.Addr, @@ -52,12 +73,43 @@ func New(cfg *config.Config, st *store.Store, logger *slog.Logger) (*Server, err return s, nil } +// sessionKey returns the cookie signing key. In production it comes from +// EMAIL_AGENT_SESSION_SECRET; with no secret configured the service still +// starts with an ephemeral key so it is usable, but sessions do not survive a +// restart and the operator sees a warning. +func sessionKey(cfg *config.Config, logger *slog.Logger) ([]byte, error) { + if cfg.SessionSecret != "" { + return []byte(cfg.SessionSecret), nil + } + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + return nil, err + } + logger.Warn("EMAIL_AGENT_SESSION_SECRET is not set; using an ephemeral session key (sessions reset on restart)") + return key, nil +} + // Handler returns the root HTTP handler with middleware applied. func (s *Server) Handler() http.Handler { + staticFS, err := fs.Sub(web.StaticFS, "static") + if err != nil { + // web.StaticFS is a compile-time constant; this cannot fail at runtime. + panic(fmt.Sprintf("static assets: %v", err)) + } + static := http.StripPrefix("/static/", http.FileServer(http.FS(staticFS))) + mux := http.NewServeMux() mux.HandleFunc("GET /health", s.handleHealth) mux.HandleFunc("GET /readyz", s.handleReady) - mux.HandleFunc("GET /{$}", s.handleIndex) + mux.Handle("GET /static/", static) + + mux.HandleFunc("GET /login", s.handleLoginGet) + mux.HandleFunc("POST /login", s.handleLoginPost) + mux.HandleFunc("POST /logout", s.handleLogout) + + mux.HandleFunc("GET /{$}", s.requireAuth(s.handleDashboard)) + mux.HandleFunc("GET /partials/inbox", s.requireAuth(s.handleInboxPartial)) + return s.recoverPanic(s.logRequests(mux)) } @@ -138,19 +190,6 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]string{"status": "ready"}) } -// handleIndex renders a placeholder dashboard. The real login + inbox screens -// are Phase 1.2. -func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/html; charset=utf-8") - data := struct { - Version string - Env string - }{Version: version.Version, Env: s.cfg.Env} - if err := s.index.Execute(w, data); err != nil { - s.logger.Error("render index", "error", err) - } -} - func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(code) @@ -195,34 +234,3 @@ func (r *statusRecorder) WriteHeader(code int) { r.status = code r.ResponseWriter.WriteHeader(code) } - -const indexHTML = ` - - - - -Email Agent - - - -
-
-

Email Agent

-

Phase 1 skeleton is running. Version {{.Version}} ({{.Env}}).

-
-

Login and the inbox arrive in Phase 1.2. Liveness is at - /health.

-
- - -` diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 4a0f8f6..3d3d0c7 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -6,20 +6,28 @@ import ( "log/slog" "net/http" "net/http/httptest" + "net/url" "path/filepath" + "regexp" + "strings" "testing" "gitea.lab.audasmedia.com.au/sam/email_agent/internal/config" + "gitea.lab.audasmedia.com.au/sam/email_agent/internal/session" "gitea.lab.audasmedia.com.au/sam/email_agent/internal/store" ) +const testPassword = "test-password" + func newTestServer(t *testing.T) *Server { t.Helper() cfg := &config.Config{ - Env: "test", - Addr: ":0", - DBPath: filepath.Join(t.TempDir(), "email_agent.db"), - LogLevel: "error", + Env: "test", + Addr: ":0", + DBPath: filepath.Join(t.TempDir(), "email_agent.db"), + LogLevel: "error", + SessionSecret: "test-session-secret", + Password: testPassword, } st, err := store.Open(context.Background(), cfg.DBPath) if err != nil { @@ -65,9 +73,9 @@ func TestReadyz(t *testing.T) { } } -func TestIndexRendersHTML(t *testing.T) { +func TestStaticTokensServed(t *testing.T) { srv := newTestServer(t) - req := httptest.NewRequest(http.MethodGet, "/", nil) + req := httptest.NewRequest(http.MethodGet, "/static/tokens.css", nil) rec := httptest.NewRecorder() srv.Handler().ServeHTTP(rec, req) @@ -75,7 +83,180 @@ func TestIndexRendersHTML(t *testing.T) { if rec.Code != http.StatusOK { t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) } - if ct := rec.Header().Get("Content-Type"); ct == "" { - t.Error("Content-Type header is empty") + if !strings.Contains(rec.Body.String(), "--canvas-soft") { + t.Error("tokens.css does not contain the design tokens") } } + +func TestUnauthenticatedRedirectsToLogin(t *testing.T) { + srv := newTestServer(t) + req := httptest.NewRequest(http.MethodGet, "/", nil) + rec := httptest.NewRecorder() + + srv.Handler().ServeHTTP(rec, req) + + if rec.Code != http.StatusSeeOther { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusSeeOther) + } + if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/login") { + t.Errorf("Location = %q, want /login…", loc) + } +} + +func TestLoginPageRenders(t *testing.T) { + srv := newTestServer(t) + req := httptest.NewRequest(http.MethodGet, "/login", nil) + rec := httptest.NewRecorder() + + srv.Handler().ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK) + } + body := rec.Body.String() + if !strings.Contains(body, "Sign in") || !strings.Contains(body, `name="csrf"`) { + t.Error("login page is missing the form or CSRF field") + } + if findCookie(t, rec.Result().Cookies(), csrfCookieName) == nil { + t.Error("login page did not set the CSRF cookie") + } +} + +func TestLoginFlowAndDashboard(t *testing.T) { + srv := newTestServer(t) + h := srv.Handler() + + // 1. Load the login page to obtain the CSRF token. + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil)) + csrf := csrfFromBody(t, rec.Body.String()) + csrfCookie := findCookie(t, rec.Result().Cookies(), csrfCookieName) + + // 2. Sign in with the right password. + rec = httptest.NewRecorder() + h.ServeHTTP(rec, loginRequest(csrf, testPassword, csrfCookie)) + if rec.Code != http.StatusSeeOther { + t.Fatalf("login status = %d, want %d (body: %s)", rec.Code, http.StatusSeeOther, rec.Body.String()) + } + sessionCookie := findCookie(t, rec.Result().Cookies(), session.CookieName) + if sessionCookie == nil { + t.Fatal("login did not set the session cookie") + } + + // 3. The dashboard renders with the session cookie. + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.AddCookie(sessionCookie) + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("dashboard status = %d, want %d", rec.Code, http.StatusOK) + } + body := rec.Body.String() + for _, want := range []string{"Good ", "Inbox", "Categories", "Folders", "Log out"} { + if !strings.Contains(body, want) { + t.Errorf("dashboard body missing %q", want) + } + } +} + +func TestLoginWrongPassword(t *testing.T) { + srv := newTestServer(t) + h := srv.Handler() + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil)) + csrf := csrfFromBody(t, rec.Body.String()) + csrfCookie := findCookie(t, rec.Result().Cookies(), csrfCookieName) + + rec = httptest.NewRecorder() + h.ServeHTTP(rec, loginRequest(csrf, "wrong-password", csrfCookie)) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized) + } + if findCookie(t, rec.Result().Cookies(), session.CookieName) != nil { + t.Error("a session cookie was issued for a failed login") + } +} + +func TestLoginRejectsMissingCSRF(t *testing.T) { + srv := newTestServer(t) + + form := url.Values{"password": {testPassword}} + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, req) + + if rec.Code != http.StatusForbidden { + t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden) + } +} + +func TestLogoutDestroysSession(t *testing.T) { + srv := newTestServer(t) + h := srv.Handler() + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil)) + csrf := csrfFromBody(t, rec.Body.String()) + csrfCookie := findCookie(t, rec.Result().Cookies(), csrfCookieName) + + rec = httptest.NewRecorder() + h.ServeHTTP(rec, loginRequest(csrf, testPassword, csrfCookie)) + sessionCookie := findCookie(t, rec.Result().Cookies(), session.CookieName) + if sessionCookie == nil { + t.Fatal("login did not set the session cookie") + } + + // Log out, carrying both the CSRF and session cookies. + form := url.Values{"csrf": {csrf}} + req := httptest.NewRequest(http.MethodPost, "/logout", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.AddCookie(csrfCookie) + req.AddCookie(sessionCookie) + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("logout status = %d, want %d", rec.Code, http.StatusSeeOther) + } + + // The old session no longer reaches the dashboard. + req = httptest.NewRequest(http.MethodGet, "/", nil) + req.AddCookie(sessionCookie) + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("dashboard after logout = %d, want %d", rec.Code, http.StatusSeeOther) + } +} + +func loginRequest(csrf, password string, csrfCookie *http.Cookie) *http.Request { + form := url.Values{"password": {password}, "csrf": {csrf}} + req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + if csrfCookie != nil { + req.AddCookie(csrfCookie) + } + return req +} + +var csrfFieldRE = regexp.MustCompile(`name="csrf" value="([^"]*)"`) + +func csrfFromBody(t *testing.T, body string) string { + t.Helper() + m := csrfFieldRE.FindStringSubmatch(body) + if len(m) < 2 || m[1] == "" { + t.Fatalf("no CSRF token in body") + } + return m[1] +} + +func findCookie(t *testing.T, cookies []*http.Cookie, name string) *http.Cookie { + t.Helper() + for _, c := range cookies { + if c.Name == name && c.Value != "" { + return c + } + } + return nil +} diff --git a/internal/session/session.go b/internal/session/session.go new file mode 100644 index 0000000..4ec2755 --- /dev/null +++ b/internal/session/session.go @@ -0,0 +1,196 @@ +// Package session implements the Email Agent's server-side session store and +// the signed cookie format used to reference a session. +// +// Sessions live in the process (there is one user and one container), so the +// cookie only ever carries an opaque, HMAC-signed identifier. Nothing about the +// user or the session state is stored client-side. +package session + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/base64" + "encoding/hex" + "strings" + "sync" + "time" +) + +// CookieName is the name of the session cookie. +const CookieName = "email_agent_session" + +// DefaultTTL is how long a session stays valid. +const DefaultTTL = 30 * 24 * time.Hour + +// Session is a single logged-in session. +type Session struct { + ID string + User string + CreatedAt time.Time + ExpiresAt time.Time +} + +// Store is an in-memory, concurrency-safe session store with lazy expiry. +type Store struct { + mu sync.Mutex + sessions map[string]Session + ttl time.Duration + now func() time.Time +} + +// NewStore returns an empty store. A non-positive ttl falls back to DefaultTTL. +func NewStore(ttl time.Duration) *Store { + if ttl <= 0 { + ttl = DefaultTTL + } + return &Store{ + sessions: make(map[string]Session), + ttl: ttl, + now: time.Now, + } +} + +// Create makes a new session for user and returns it. +func (s *Store) Create(user string) (Session, error) { + id, err := RandomToken(32) + if err != nil { + return Session{}, err + } + now := s.now() + sess := Session{ + ID: id, + User: user, + CreatedAt: now, + ExpiresAt: now.Add(s.ttl), + } + s.mu.Lock() + defer s.mu.Unlock() + s.gcLocked() + s.sessions[id] = sess + return sess, nil +} + +// Get returns the session for id if it exists and has not expired. +func (s *Store) Get(id string) (Session, bool) { + s.mu.Lock() + defer s.mu.Unlock() + sess, ok := s.sessions[id] + if !ok { + return Session{}, false + } + if s.now().After(sess.ExpiresAt) { + delete(s.sessions, id) + return Session{}, false + } + return sess, true +} + +// Delete removes a session. +func (s *Store) Delete(id string) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.sessions, id) +} + +// Len returns the number of live (not-yet-swept) sessions. +func (s *Store) Len() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.sessions) +} + +func (s *Store) gcLocked() { + now := s.now() + for id, sess := range s.sessions { + if now.After(sess.ExpiresAt) { + delete(s.sessions, id) + } + } +} + +// Manager pairs a session store with the HMAC key that signs cookie values. +type Manager struct { + store *Store + key []byte +} + +// NewManager builds a Manager. An empty key is replaced with a random key so +// the manager is always safe to use; the caller should normally supply one. +func NewManager(key []byte, ttl time.Duration) (*Manager, error) { + if len(key) == 0 { + k, err := randomBytes(32) + if err != nil { + return nil, err + } + key = k + } + return &Manager{store: NewStore(ttl), key: key}, nil +} + +// New creates a session and returns it with the signed cookie value to set. +func (m *Manager) New(user string) (Session, string, error) { + sess, err := m.store.Create(user) + if err != nil { + return Session{}, "", err + } + return sess, m.sign(sess.ID), nil +} + +// Lookup resolves a signed cookie value to a live session. +func (m *Manager) Lookup(cookieValue string) (Session, bool) { + id, ok := m.verify(cookieValue) + if !ok { + return Session{}, false + } + return m.store.Get(id) +} + +// Destroy deletes the session referenced by a signed cookie value. +func (m *Manager) Destroy(cookieValue string) { + if id, ok := m.verify(cookieValue); ok { + m.store.Delete(id) + } +} + +func (m *Manager) sign(id string) string { + mac := hmac.New(sha256.New, m.key) + mac.Write([]byte(id)) + return id + "." + hex.EncodeToString(mac.Sum(nil)) +} + +func (m *Manager) verify(value string) (string, bool) { + i := strings.LastIndexByte(value, '.') + if i <= 0 || i == len(value)-1 { + return "", false + } + id, sigHex := value[:i], value[i+1:] + sig, err := hex.DecodeString(sigHex) + if err != nil { + return "", false + } + mac := hmac.New(sha256.New, m.key) + mac.Write([]byte(id)) + if subtle.ConstantTimeCompare(sig, mac.Sum(nil)) != 1 { + return "", false + } + return id, true +} + +// RandomToken returns a URL-safe random string carrying n bytes of entropy. +func RandomToken(n int) (string, error) { + b, err := randomBytes(n) + if err != nil { + return "", err + } + return base64.RawURLEncoding.EncodeToString(b), nil +} + +func randomBytes(n int) ([]byte, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return nil, err + } + return b, nil +} diff --git a/internal/session/session_test.go b/internal/session/session_test.go new file mode 100644 index 0000000..7ab8807 --- /dev/null +++ b/internal/session/session_test.go @@ -0,0 +1,78 @@ +package session + +import ( + "testing" + "time" +) + +func TestManagerRoundTrip(t *testing.T) { + m, err := NewManager([]byte("test-key"), time.Hour) + if err != nil { + t.Fatalf("NewManager() error = %v", err) + } + + sess, cookie, err := m.New("Sam") + if err != nil { + t.Fatalf("New() error = %v", err) + } + if sess.User != "Sam" { + t.Errorf("User = %q, want Sam", sess.User) + } + + got, ok := m.Lookup(cookie) + if !ok { + t.Fatal("Lookup() = not ok, want a live session") + } + if got.ID != sess.ID { + t.Errorf("Lookup ID = %q, want %q", got.ID, sess.ID) + } + + m.Destroy(cookie) + if _, ok := m.Lookup(cookie); ok { + t.Error("Lookup() after Destroy() = ok, want expired") + } +} + +func TestManagerRejectsTamperedCookie(t *testing.T) { + m, err := NewManager([]byte("key-a"), time.Hour) + if err != nil { + t.Fatalf("NewManager() error = %v", err) + } + _, cookie, err := m.New("Sam") + if err != nil { + t.Fatalf("New() error = %v", err) + } + + other, err := NewManager([]byte("key-b"), time.Hour) + if err != nil { + t.Fatalf("NewManager() error = %v", err) + } + if _, ok := other.Lookup(cookie); ok { + t.Error("Lookup() with a different key = ok, want rejected") + } + + for _, bad := range []string{"", "garbage", "abc.", ".abc", "a.b.c", cookie + "x"} { + if _, ok := m.Lookup(bad); ok { + t.Errorf("Lookup(%q) = ok, want rejected", bad) + } + } +} + +func TestStoreExpiry(t *testing.T) { + st := NewStore(time.Minute) + base := time.Now() + st.now = func() time.Time { return base } + + sess, err := st.Create("Sam") + if err != nil { + t.Fatalf("Create() error = %v", err) + } + if _, ok := st.Get(sess.ID); !ok { + t.Fatal("Get() = not ok before expiry") + } + + st.now = func() time.Time { return base.Add(2 * time.Minute) } + if _, ok := st.Get(sess.ID); ok { + t.Error("Get() = ok after expiry, want expired") + } +} diff --git a/web/embed.go b/web/embed.go new file mode 100644 index 0000000..be68476 --- /dev/null +++ b/web/embed.go @@ -0,0 +1,23 @@ +// Package web holds the server-rendered templates and static assets for the +// Email Agent UI. +// +// The assets are embedded in the binary so the container image needs no +// separate file tree and cannot drift from the code. +// +// tokens.css and the Inter woff2 files are copied verbatim from the Family Home +// Lab design system (AGENTS.md §6); they are compiled into this project rather +// than imported across projects. +package web + +import "embed" + +// StaticFS holds the /static tree: design tokens, self-hosted Inter fonts, +// htmx, and the application stylesheet. +// +//go:embed static +var StaticFS embed.FS + +// TemplateFS holds the server-rendered HTML templates. +// +//go:embed templates +var TemplateFS embed.FS diff --git a/web/static/app.css b/web/static/app.css new file mode 100644 index 0000000..d0ca346 --- /dev/null +++ b/web/static/app.css @@ -0,0 +1,293 @@ +/* ============================================================ + Email Agent — application styles + Built on Family Home Lab tokens.css (do not edit tokens here). + Base unit: 8px. Touch targets >= 44px. Pill CTAs, 4px inputs. + ============================================================ */ + +*, +*::before, +*::after { box-sizing: border-box; } + +html, body { height: 100%; } + +body { + margin: 0; + font: var(--type-body-md); + color: var(--ink-secondary); + background: var(--canvas-soft); + -webkit-font-smoothing: antialiased; +} + +h1, h2, h3, p { margin: 0; } + +a { color: var(--primary); text-decoration: none; } +a:hover { text-decoration: underline; } + +:focus-visible { + outline: 2px solid var(--primary); + outline-offset: 2px; +} + +/* ---------- primitives ---------- */ + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: var(--space-xs); + min-height: 44px; + padding: 0 var(--space-lg); + border: 1px solid transparent; + border-radius: var(--rounded-full); + font: var(--type-button); + cursor: pointer; + transition: transform .08s ease, background-color .15s ease, box-shadow .15s ease; + white-space: nowrap; +} +.btn:active { transform: scale(.97); } + +.btn-primary { + background: var(--primary); + color: var(--on-primary); +} +.btn-primary:hover { background: var(--primary-active); } + +.btn-utility { + background: var(--surface); + color: var(--ink); + border-radius: var(--rounded-md); + min-height: 44px; + padding: 0 var(--space-md); + box-shadow: var(--shadow-level-1); + border: 1px solid var(--hairline); +} +.btn-utility:hover { background: var(--surface-2); } + +.btn-block { width: 100%; } + +.text-input { + width: 100%; + min-height: 44px; + padding: var(--space-xs) var(--space-sm); + background: var(--surface); + color: var(--ink); + font: var(--type-body-md); + border: 1px solid var(--hairline); + border-radius: var(--rounded-xs); +} +.text-input:focus { + outline: none; + border-color: var(--primary); + box-shadow: var(--shadow-level-1); +} + +.field { display: flex; flex-direction: column; gap: var(--space-xxs); } +.field > label { font: var(--type-caption); color: var(--ink-muted); } + +.pill { + display: inline-flex; + align-items: center; + gap: var(--space-xxs); + padding: 4px 8px; + border-radius: var(--rounded-full); + font: var(--type-eyebrow); + background: var(--surface); + border: 1px solid var(--hairline); + color: var(--ink-muted); +} + +.hairline { border: 1px solid var(--hairline); } + +.muted { color: var(--ink-muted); } +.faint { color: var(--ink-faint); } + +/* ---------- login ---------- */ + +.login-body { + background: var(--secondary); +} + +.login-wrap { + min-height: 100dvh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: var(--space-xl); + padding: var(--space-lg); +} + +.login-greeting { + font: var(--type-display-1); + color: #fff; + text-align: center; + letter-spacing: -1.5px; +} + +.auth-card { + width: 100%; + max-width: 400px; + background: var(--surface); + border-radius: var(--rounded-lg); + box-shadow: var(--shadow-level-2); + padding: var(--space-xxl) var(--space-lg); + display: flex; + flex-direction: column; + gap: var(--space-lg); +} + +.auth-brand { + font: var(--type-eyebrow); + color: var(--ink-faint); + letter-spacing: .125px; + text-transform: uppercase; +} + +.auth-card h1, .auth-card h2 { + font: var(--type-heading-1); + color: var(--ink); +} +.auth-card h2 { font: var(--type-heading-2); } + +.auth-card p { font: var(--type-body-sm); color: var(--ink-muted); } + +.auth-form { display: flex; flex-direction: column; gap: var(--space-md); } + +.alert { + padding: var(--space-xs) var(--space-sm); + border-radius: var(--rounded-xs); + font: var(--type-body-sm); + border: 1px solid var(--hairline); + background: var(--surface-2); + color: var(--ink-secondary); +} +.alert-error { border-color: var(--sticker-red); color: var(--sticker-red); } + +/* ---------- dashboard chrome ---------- */ + +.nav-bar { + position: sticky; + top: 0; + z-index: 10; + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-md); + padding: var(--space-xs) var(--space-md); + min-height: 56px; + background: var(--surface); + border-bottom: 1px solid var(--hairline); +} +.nav-bar .wordmark { font: var(--type-title); color: var(--ink); } +.nav-bar .nav-actions { display: flex; align-items: center; gap: var(--space-xs); } + +.page { max-width: var(--container-max); margin: 0 auto; padding: var(--space-lg) var(--space-md); } + +.greeting { font: var(--type-heading-1); color: var(--ink); margin-bottom: var(--space-lg); } + +.shell { + display: grid; + grid-template-columns: 1fr; + gap: var(--space-md); + align-items: start; +} + +@media (min-width: 760px) { + .shell { grid-template-columns: 220px minmax(0, 1fr); } +} +@media (min-width: 1080px) { + .shell { grid-template-columns: 220px minmax(0, 1fr) 340px; } +} + +.panel { + background: var(--surface); + border: 1px solid var(--hairline); + border-radius: var(--rounded-lg); + overflow: hidden; +} + +.panel-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-xs); + padding: var(--space-sm) var(--space-md); + border-bottom: 1px solid var(--hairline); +} +.panel-head h2 { font: var(--type-title); color: var(--ink); } + +.panel-body { padding: var(--space-md); } + +/* left nav: vertical list on desktop, horizontal scroller on phone */ +.nav-groups { display: flex; flex-direction: column; gap: var(--space-md); padding: var(--space-md); } + +@media (max-width: 759px) { + .nav-groups { + flex-direction: row; + overflow-x: auto; + gap: var(--space-md); + padding: var(--space-xs) var(--space-sm); + -webkit-overflow-scrolling: touch; + } + .nav-group { min-width: max-content; } + .nav-group-items { flex-direction: row; } +} + +.nav-group-title { + font: var(--type-eyebrow); + color: var(--ink-faint); + text-transform: uppercase; + letter-spacing: .125px; + margin-bottom: var(--space-xs); +} +.nav-group-items { display: flex; flex-direction: column; gap: 2px; } + +.nav-item { + display: flex; + align-items: center; + gap: var(--space-xs); + min-height: 44px; + padding: 0 var(--space-sm); + border-radius: var(--rounded-sm); + font: var(--type-body-sm); + color: var(--ink-secondary); +} +.nav-item:hover { background: var(--surface-2); text-decoration: none; } +.nav-item .dot { + width: 8px; height: 8px; border-radius: var(--rounded-full); + background: var(--ink-faint); flex: 0 0 auto; +} +.nav-item .count { margin-left: auto; font: var(--type-caption); color: var(--ink-faint); } + +/* centre list */ +.msg-list { display: flex; flex-direction: column; } +.msg-row { + display: flex; + align-items: center; + gap: var(--space-sm); + min-height: 64px; + padding: var(--space-sm) var(--space-md); + border-bottom: 1px solid var(--hairline); +} +.msg-row:last-child { border-bottom: 0; } + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-sm); + text-align: center; + padding: var(--space-xxl) var(--space-lg); +} +.empty-state .empty-title { font: var(--type-title); color: var(--ink); } +.empty-state .empty-copy { font: var(--type-body-sm); color: var(--ink-muted); max-width: 32ch; } + +.detail-body { padding: var(--space-lg) var(--space-md); } + +/* dark-mode toggle shows the right glyph */ +.theme-toggle .icon-dark { display: none; } +[data-theme="dark"] .theme-toggle .icon-dark { display: inline; } +[data-theme="dark"] .theme-toggle .icon-light { display: none; } + +/* subtle, non-decorative loading pulse (no spinners) */ +.htmx-request .empty-state { opacity: .55; transition: opacity .15s ease; } diff --git a/web/static/fonts/inter-400.woff2 b/web/static/fonts/inter-400.woff2 new file mode 100644 index 0000000..33002f1 Binary files /dev/null and b/web/static/fonts/inter-400.woff2 differ diff --git a/web/static/fonts/inter-500.woff2 b/web/static/fonts/inter-500.woff2 new file mode 100644 index 0000000..03aaea1 Binary files /dev/null and b/web/static/fonts/inter-500.woff2 differ diff --git a/web/static/fonts/inter-600.woff2 b/web/static/fonts/inter-600.woff2 new file mode 100644 index 0000000..fb50a02 Binary files /dev/null and b/web/static/fonts/inter-600.woff2 differ diff --git a/web/static/fonts/inter-700.woff2 b/web/static/fonts/inter-700.woff2 new file mode 100644 index 0000000..12b51d7 Binary files /dev/null and b/web/static/fonts/inter-700.woff2 differ diff --git a/web/static/htmx.min.js b/web/static/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/web/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/web/static/tokens.css b/web/static/tokens.css new file mode 100644 index 0000000..1516a04 --- /dev/null +++ b/web/static/tokens.css @@ -0,0 +1,110 @@ +/* ============================================================ + Family Home Lab — Design Tokens + Source: DESIGN.md (Notion design language) + Only structural/semantic tokens here. All values map 1:1. + ============================================================ */ + +/* Inter (@fontsource) — self-hosted substitute for NotionInter */ +@font-face { font-family: "Inter"; font-style: normal; font-weight: 400; font-display: swap; src: url("/static/fonts/inter-400.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 500; font-display: swap; src: url("/static/fonts/inter-500.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 600; font-display: swap; src: url("/static/fonts/inter-600.woff2") format("woff2"); } +@font-face { font-family: "Inter"; font-style: normal; font-weight: 700; font-display: swap; src: url("/static/fonts/inter-700.woff2") format("woff2"); } + +:root { + /* --- Surface --- */ + --canvas-soft: #f6f5f4; + --surface: #ffffff; + --surface-2: #f2f2f1; + --hairline: #e6e6e6; + + /* --- Text --- */ + --ink: #000000; + --ink-secondary: #31302e; + --ink-muted: #615d59; + --ink-faint: #a39e98; + + /* --- Structural accents --- */ + --primary: #0075de; /* the ONLY action colour */ + --primary-active: #005bab; + --on-primary: #ffffff; + --secondary: #213183; /* deep indigo — login band + greeting only */ + + /* --- Sticker palette (decorative only) --- */ + --sticker-sky: #62aef0; /* chat */ + --sticker-purple: #d6b6f6; /* image */ + --sticker-pink: #ff64c8; /* video */ + --sticker-orange: #dd5b00; /* audio */ + --sticker-teal: #2a9d99; /* docs */ + --sticker-green: #1aae39; /* status: online/saved */ + --sticker-red: #d33a2b; /* status: failed / error (ON_OFF.md decision) */ + --sticker-purple-deep: #391c57; /* illustration only */ + --sticker-orange-deep: #793400; /* illustration only */ + + /* --- Typography (Inter, self-hosted via @font-face) --- */ + --font-family: "Inter", -apple-system, system-ui, "Segoe UI", + Helvetica, Arial, sans-serif; + + /* Font-family is baked into each token below: the CSS `font` shorthand + resets font-family to the UA default (serif) unless a family is written, + and it cannot carry letter-spacing — so weights/sizes ship inline and the + family is appended per token. */ + --type-display-1: 700 48px/1.05 var(--font-family); + --type-heading-1: 700 32px/1.1 var(--font-family); + --type-heading-2: 700 22px/1.27 var(--font-family); + --type-title: 600 17px/1.4 var(--font-family); + --type-body-md: 400 15px/1.5 var(--font-family); + --type-body-sm: 400 14px/1.4 var(--font-family); + --type-button: 500 15px/1.4 var(--font-family); + --type-caption: 400 13px/1.43 var(--font-family); + --type-eyebrow: 600 12px/1.33 var(--font-family); + + /* --- Layout (base unit 8px) --- */ + --space-xxs: 4px; + --space-xs: 8px; + --space-sm: 12px; + --space-md: 16px; + --space-lg: 24px; + --space-xl: 28px; + --space-xxl: 32px; + + --container-max: 1200px; + + /* --- Elevation --- */ + --shadow-level-1: rgba(0, 0, 0, 0.01) 0 0.175px 1px, + rgba(0, 0, 0, 0.02) 0 0.8px 3px, + rgba(0, 0, 0, 0.027) 0 2px 8px, + rgba(0, 0, 0, 0.04) 0 4px 18px; + --shadow-level-2: rgba(0, 0, 0, 0.0122) 0 0.175px 1px, + rgba(0, 0, 0, 0.024) 0 0.8px 3px, + rgba(0, 0, 0, 0.032) 0 2px 8px, + rgba(0, 0, 0, 0.047) 0 4px 18px, + rgba(0, 0, 0, 0.05) 0 23px 52px; + + /* --- Shapes --- */ + --rounded-xs: 4px; + --rounded-sm: 5px; + --rounded-md: 8px; + --rounded-lg: 12px; + --rounded-full: 9999px; +} + +/* Dark mode — flip the semantic tokens only (components use var(--…)). */ +[data-theme="dark"] { + --canvas-soft: #141518; + --surface: #1c1e22; + --surface-2: #24262c; + --hairline: #33363d; + --ink: #f5f6f7; + --ink-secondary: #dcdee2; + --ink-muted: #a9adb6; + --ink-faint: #727680; + --primary: #3d8be0; + --primary-active: #5d9ff0; + --on-primary: #ffffff; + --secondary: #10142a; + --shadow-level-1: rgba(0, 0, 0, 0.45) 0 1px 3px; + --shadow-level-2: rgba(0, 0, 0, 0.55) 0 5px 22px; +} + +/* Numerals: enable OpenType lnum */ +html { font-feature-settings: "lnum" 1; } \ No newline at end of file diff --git a/web/templates/dashboard.html b/web/templates/dashboard.html new file mode 100644 index 0000000..ddda854 --- /dev/null +++ b/web/templates/dashboard.html @@ -0,0 +1,97 @@ + + + + + + Email Agent + + + + + + + +
+

{{.Greeting}}, Sam

+ +
+ + +
+
+

Inbox

+ +
+
+
+ + +
+
+ + + + diff --git a/web/templates/inbox.html b/web/templates/inbox.html new file mode 100644 index 0000000..09b7388 --- /dev/null +++ b/web/templates/inbox.html @@ -0,0 +1,5 @@ +
+
No messages yet
+

Mail fetch arrives in Phase 2. New messages will appear here, grouped by category, with a recommended action on each row.

+ IMAP scan not connected +
diff --git a/web/templates/login.html b/web/templates/login.html new file mode 100644 index 0000000..8a31624 --- /dev/null +++ b/web/templates/login.html @@ -0,0 +1,45 @@ + + + + + + Sign in · Email Agent + + + + + +
+

{{.PartOfDay}}, Sam

+
+
+

Email Agent

+

Sign in

+

The family inbox triage desk.

+
+ + {{if .Error}}{{end}} + {{if not .Configured}}
Login is not configured. Set EMAIL_AGENT_PASSWORD (or EMAIL_AGENT_SESSION_SECRET) on the host.
{{end}} + + + + +
+ + +
+ + +
+
+ +