Files
supermarket/internal/web/server.go
T
davidandClaude Opus 5.5 13bf18facc Phase 1, part 1: fetch, write and publish posts from the web app
Brings back posting, which Phase 0 removed with the terminal interface.

- Content page: per inventory entry, fetch its X account, X hashtag
  search, YouTube channel and RSS/Atom feeds (new), then select, dismiss
  or restore the fetched items, which are kept in the database.
- Writing: one AI call returns a draft per channel (X and LinkedIn),
  prompted from the company profile, the entry's relationship, talking
  points and mention policy, and each channel's rules. Fetched text is
  quoted as untrusted. An over-long X draft gets one request to shorten.
- Drafts page: edit with a live length counter that counts like X, then
  publish each draft on its own. A draft is claimed before posting so it
  can't go out twice; failures are kept on the draft for a retry; X
  tokens are refreshed and saved.
- Migration 2 adds content_items and drafts, and turns queued posts into
  drafts for the platforms they hadn't reached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:58:24 -07:00

280 lines
8.3 KiB
Go

// Package web is Supermarket's local web interface.
package web
import (
"embed"
"fmt"
"html/template"
"io/fs"
"log/slog"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
"supermarket/internal/api/twitter"
"supermarket/internal/core"
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
)
//go:embed templates/*.html
var templateFS embed.FS
//go:embed static
var staticFS embed.FS
// Server holds what the handlers need.
type Server struct {
DB *db.DB
Secrets *secrets.Store
Core *core.Core // nil without a Core
DataDir string
PublicURL string // e.g. http://localhost:8470, for OAuth redirect URIs
Version string
MCPToken string
MCPSocket string // the MCP socket's path on the host, for Hermes' config
MCP http.Handler
Log *slog.Logger
// What the legacy import did at startup, or why it failed.
ImportStatus *legacy.Status
ImportErr error
pages map[string]*template.Template
mu sync.Mutex
pending map[string]*oauth.Pending // OAuth flows by state
}
// Handler builds the routes.
func (s *Server) Handler() (http.Handler, error) {
if err := s.loadTemplates(); err != nil {
return nil, err
}
s.pending = map[string]*oauth.Pending{}
mux := http.NewServeMux()
static, _ := fs.Sub(staticFS, "static")
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static)))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "ok") })
if s.MCP != nil {
mux.Handle("/mcp", s.MCP)
}
mux.HandleFunc("GET /{$}", s.dashboard)
mux.HandleFunc("GET /profile", s.profilePage)
mux.HandleFunc("POST /profile", s.profileSave)
mux.HandleFunc("POST /profile/draft", s.profileDraft)
mux.HandleFunc("GET /inventory", s.inventoryList)
mux.HandleFunc("GET /inventory/new", s.inventoryEdit)
mux.HandleFunc("GET /inventory/{id}", s.inventoryEdit)
mux.HandleFunc("POST /inventory/save", s.inventorySave)
mux.HandleFunc("POST /inventory/{id}/delete", s.inventoryDelete)
mux.HandleFunc("GET /inventory/import", s.inventoryImportPage)
mux.HandleFunc("POST /inventory/import", s.inventoryImport)
mux.HandleFunc("GET /inventory/export", s.inventoryExport)
mux.HandleFunc("GET /settings/ai", s.aiPage)
mux.HandleFunc("POST /settings/ai", s.aiSave)
mux.HandleFunc("POST /settings/ai/test", s.aiTest)
mux.HandleFunc("GET /settings/ai/models", s.aiModels)
mux.HandleFunc("GET /settings/credentials", s.credentialsPage)
mux.HandleFunc("POST /settings/credentials", s.credentialsSave)
mux.HandleFunc("POST /auth/{provider}/start", s.oauthStart)
mux.HandleFunc("GET /auth/{provider}/callback", s.oauthCallback)
mux.HandleFunc("GET /content", s.contentIndex)
mux.HandleFunc("GET /content/{id}", s.contentEntry)
mux.HandleFunc("POST /content/{id}/fetch", s.contentFetch)
mux.HandleFunc("POST /content/{id}/items", s.contentItems)
mux.HandleFunc("GET /drafts", s.draftsPage)
mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction)
mux.HandleFunc("GET /core", s.corePage)
mux.HandleFunc("GET /core/checks", s.coreChecks)
return s.guard(mux), nil
}
// guard protects the app, which has no login because only this machine can
// reach it, from web pages open in the same browser:
// - DNS rebinding: a site whose name resolves to 127.0.0.1 would send its
// own Host header, so only local names are accepted.
// - Cross-site requests: a form on another site could POST here, so a
// browser request that changes something must come from this app's pages.
func (s *Server) guard(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !s.localHost(r.Host) {
http.Error(w, "Supermarket only answers at localhost.", http.StatusMisdirectedRequest)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.URL.Path != "/mcp" {
if !sameOrigin(r) {
http.Error(w, "Cross-site request refused.", http.StatusForbidden)
return
}
}
h := w.Header()
h.Set("X-Frame-Options", "DENY")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Referrer-Policy", "same-origin")
h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self' https://twitter.com https://x.com https://www.linkedin.com; frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}
func (s *Server) localHost(hostport string) bool {
host := hostport
if h, _, err := net.SplitHostPort(hostport); err == nil {
host = h
}
host = strings.Trim(strings.ToLower(host), "[]")
switch host {
case "localhost", "127.0.0.1", "::1":
return true
}
if u, err := url.Parse(s.PublicURL); err == nil && strings.EqualFold(u.Hostname(), host) {
return true
}
return false
}
func sameOrigin(r *http.Request) bool {
if origin := r.Header.Get("Origin"); origin != "" {
u, err := url.Parse(origin)
return err == nil && strings.EqualFold(u.Host, r.Host)
}
switch r.Header.Get("Sec-Fetch-Site") {
case "", "same-origin", "none":
return true // non-browser clients send neither header
}
return false
}
func (s *Server) loadTemplates() error {
funcs := template.FuncMap{
"lines": func(v []string) string { return strings.Join(v, "\n") },
"join": strings.Join,
"ago": ago,
"add": func(a, b int) int { return a + b },
"xreserve": twitter.URLReserve,
"truncate": func(n int, s string) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
},
}
names, err := fs.Glob(templateFS, "templates/*.html")
if err != nil {
return err
}
s.pages = map[string]*template.Template{}
for _, name := range names {
base := strings.TrimSuffix(strings.TrimPrefix(name, "templates/"), ".html")
if base == "layout" {
continue
}
t, err := template.New("layout.html").Funcs(funcs).ParseFS(templateFS, "templates/layout.html", name)
if err != nil {
return fmt.Errorf("template %s: %w", name, err)
}
s.pages[base] = t
}
return nil
}
// page is what every template gets.
type page struct {
Title string
Nav string // which nav item is current
Version string
Flash string
Error string
Data any
}
// render writes a full page, or only its "content" block for htmx requests
// that ask for a fragment.
func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p page) {
t, ok := s.pages[name]
if !ok {
http.Error(w, "no template "+name, http.StatusInternalServerError)
return
}
p.Version = s.Version
if p.Flash == "" {
p.Flash = flashes[r.URL.Query().Get("msg")]
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, "layout.html", p); err != nil {
s.Log.Error("render", "page", name, "err", err)
}
}
// fragment writes one named template (for htmx swaps).
func (s *Server) fragment(w http.ResponseWriter, page, name string, data any) {
t, ok := s.pages[page]
if !ok {
http.Error(w, "no template "+page, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.ExecuteTemplate(w, name, data); err != nil {
s.Log.Error("render fragment", "page", page, "name", name, "err", err)
}
}
// Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{
"saved": "Saved.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"imported": "Imported.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
"drafted": "Drafts written. Review them below.",
"published": "Published.",
"discarded": "Discarded.",
}
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
if msg != "" {
path += "?msg=" + url.QueryEscape(msg)
}
http.Redirect(w, r, path, http.StatusSeeOther)
}
func (s *Server) serverError(w http.ResponseWriter, err error) {
s.Log.Error("request failed", "err", err)
http.Error(w, "Something went wrong: "+err.Error(), http.StatusInternalServerError)
}
func ago(t time.Time) string {
if t.IsZero() {
return "never"
}
d := time.Since(t)
switch {
case d < time.Minute:
return "just now"
case d < time.Hour:
return fmt.Sprintf("%d min ago", int(d.Minutes()))
case d < 48*time.Hour:
return fmt.Sprintf("%d h ago", int(d.Hours()))
default:
return t.Local().Format("2 Jan 2006")
}
}