Phase 0: turn Supermarket into a Dockerized local web app

Replace the old Go TUI with a web app (port 8470) that runs in a
container as a CoreDesktop sibling:

- cmd/supermarket server with htmx web UI: dashboard, company profile,
  inventory (partners/competitors), AI and credential settings, and a
  Core & Hermes page
- SQLite storage and a secrets store under ~/.local/share/supermarket
- AI providers (Anthropic, OpenAI-compatible) behind one interface
- MCP server and a Hermes bridge to the Federated Core MCP hub
- Import of the old Coremarketing TUI's state
- install.sh / update.sh / lib.sh, Dockerfile, compose.yaml, the
  bin/supermarket launcher and hermes/setup.sh

Posting is not wired back up yet; that comes in Phase 1. See PLAN.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 08:38:09 -07:00
co-authored by Claude Opus 5.5
parent 4d304cd65b
commit d039484a4a
68 changed files with 6288 additions and 2914 deletions
+179
View File
@@ -0,0 +1,179 @@
package web
import (
"errors"
"io"
"net/http"
"strconv"
"strings"
"supermarket/examples"
"supermarket/internal/inventory"
"supermarket/internal/profile"
)
func (s *Server) inventoryList(w http.ResponseWriter, r *http.Request) {
rel := r.URL.Query().Get("relationship")
entries, err := inventory.List(s.DB, rel)
if err != nil {
s.serverError(w, err)
return
}
s.render(w, r, "inventory", page{Title: "Inventory", Nav: "inventory", Data: map[string]any{
"Entries": entries,
"Relationship": rel,
"Relationships": inventory.Relationships,
}})
}
type entryData struct {
E *inventory.Entry
Relationships []string
}
func (s *Server) inventoryEdit(w http.ResponseWriter, r *http.Request) {
e := &inventory.Entry{Relationship: inventory.Partner}
if idStr := r.PathValue("id"); idStr != "" {
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
e, err = inventory.Get(s.DB, id)
if err != nil {
s.serverError(w, err)
return
}
if e == nil {
http.NotFound(w, r)
return
}
}
title := "New entry"
if e.ID != 0 {
title = e.Name
}
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Data: entryData{E: e, Relationships: inventory.Relationships}})
}
func (s *Server) inventorySave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
f := r.PostForm
id, _ := strconv.ParseInt(f.Get("id"), 10, 64)
e := &inventory.Entry{
ID: id,
Name: f.Get("name"),
Relationship: f.Get("relationship"),
Description: f.Get("description"),
Websites: profile.Lines(f.Get("websites")),
TwitterHandle: f.Get("twitter_handle"),
YouTubeChannelID: f.Get("youtube_channel_id"),
InstagramHandle: f.Get("instagram_handle"),
LinkedIn: f.Get("linkedin"),
Subreddits: profile.Lines(f.Get("subreddits")),
RSS: profile.Lines(f.Get("rss")),
Hashtags: strings.Fields(strings.ReplaceAll(f.Get("hashtags"), ",", " ")),
Keywords: profile.Lines(f.Get("keywords")),
TalkingPoints: f.Get("talking_points"),
MentionPolicy: f.Get("mention_policy"),
}
if err := inventory.Save(s.DB, e); err != nil {
title := e.Name
if title == "" {
title = "New entry"
}
s.render(w, r, "entry", page{Title: title, Nav: "inventory", Error: err.Error(),
Data: entryData{E: e, Relationships: inventory.Relationships}})
return
}
redirect(w, r, "/inventory", "saved")
}
func (s *Server) inventoryDelete(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.NotFound(w, r)
return
}
if err := inventory.Delete(s.DB, id); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/inventory", "deleted")
}
func (s *Server) inventoryImportPage(w http.ResponseWriter, r *http.Request) {
s.render(w, r, "import", page{Title: "Import inventory", Nav: "inventory", Data: map[string]any{
"Relationships": inventory.Relationships,
}})
}
const maxImportBytes = 4 << 20
func (s *Server) inventoryImport(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxImportBytes+64<<10)
if err := r.ParseMultipartForm(maxImportBytes); err != nil && !errors.Is(err, http.ErrNotMultipart) {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
rel := r.FormValue("relationship")
overwrite := r.FormValue("overwrite") == "on"
show := func(errMsg string, res *inventory.ImportResult) {
s.render(w, r, "import", page{Title: "Import inventory", Nav: "inventory", Error: errMsg, Data: map[string]any{
"Relationships": inventory.Relationships,
"Result": res,
"YAML": r.FormValue("yaml"),
}})
}
var data []byte
switch {
case r.FormValue("example") == "federated":
data = examples.FederatedInventory
case r.MultipartForm != nil && len(r.MultipartForm.File["file"]) > 0:
f, err := r.MultipartForm.File["file"][0].Open()
if err != nil {
show(err.Error(), nil)
return
}
data, err = io.ReadAll(io.LimitReader(f, maxImportBytes))
f.Close()
if err != nil {
show(err.Error(), nil)
return
}
default:
data = []byte(r.FormValue("yaml"))
}
if len(strings.TrimSpace(string(data))) == 0 {
show("Paste a list, choose a file, or load the example.", nil)
return
}
entries, err := inventory.ParseYAML(data, rel)
if err != nil {
show(err.Error(), nil)
return
}
res := inventory.Import(s.DB, entries, overwrite)
show("", &res)
}
func (s *Server) inventoryExport(w http.ResponseWriter, r *http.Request) {
entries, err := inventory.List(s.DB, "")
if err != nil {
s.serverError(w, err)
return
}
data, err := inventory.ExportYAML(entries)
if err != nil {
s.serverError(w, err)
return
}
w.Header().Set("Content-Type", "application/yaml")
w.Header().Set("Content-Disposition", `attachment; filename="supermarket-inventory.yaml"`)
w.Write(data)
}
+314
View File
@@ -0,0 +1,314 @@
package web
import (
"context"
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"supermarket/internal/ai"
"supermarket/internal/bridge"
"supermarket/internal/core"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
// Connection is a social account the user signed in to.
type Connection struct {
Account string `json:"account"`
At time.Time `json:"at"`
}
const connectionsKey = "connections"
func (s *Server) connections() map[string]Connection {
c := map[string]Connection{}
if _, err := s.DB.GetJSON(connectionsKey, &c); err != nil {
s.Log.Error("loading connections", "err", err)
}
return c
}
func (s *Server) saveConnection(provider string, c Connection) error {
all := s.connections()
all[provider] = c
return s.DB.PutJSON(connectionsKey, all)
}
type step struct {
Label string
Done bool
Detail string
Link string
}
type module struct {
Name, Phase, Body string
}
func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) {
p, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
entries, err := inventory.List(s.DB, "")
if err != nil {
s.serverError(w, err)
return
}
counts := map[string]int{}
for _, e := range entries {
counts[e.Relationship]++
}
aiCfg, err := ai.LoadConfig(s.DB)
if err != nil {
s.serverError(w, err)
return
}
_, aiErr := ai.New(aiCfg, s.Secrets)
last, err := bridge.Last(s.DB)
if err != nil {
s.serverError(w, err)
return
}
conns := s.connections()
steps := []step{
{Label: "Company profile", Done: p.IsSet(), Link: "/profile",
Detail: ifElse(p.IsSet(), p.Name, "Describe the company, its products and its customers")},
{Label: "AI provider", Done: aiErr == nil, Link: "/settings/ai",
Detail: ifElse(aiErr == nil, aiCfg.Provider+" · "+aiCfg.Model, "Choose Anthropic or a server on your network")},
{Label: "Inventory", Done: len(entries) > 0, Link: "/inventory",
Detail: inventorySummary(counts)},
{Label: "Social accounts", Done: s.Secrets.Has(secrets.XAccessToken) || s.Secrets.Has(secrets.LinkedInAccessToken),
Link: "/settings/credentials", Detail: s.connectionSummary(conns)},
{Label: "Federated Core", Done: s.Core != nil, Link: "/core",
Detail: ifElse(s.Core != nil, coreDomain(s.Core), "No Core found; run `configure core` in CoreDesktop")},
{Label: "Hermes bridge", Done: last != nil, Link: "/core",
Detail: ifElse(last != nil, "Last check-in "+ago(atOf(last)), "Hermes hasn't checked in yet")},
}
modules := []module{
{"Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit."},
{"Prospects", "Phase 2", "Find companies and people who fit your targets, and add the ones you approve to EspoCRM through Hermes."},
{"SEO", "Phase 3", "Audit your websites and open fixes as pull requests on your Hugo repositories."},
{"Metrics", "Phase 4", "Pipeline influence, CAC, CLV and NRR from Stripe, EspoCRM and Plausible."},
{"Sites", "Phase 5", "Build pages and sites from a component library and publish them through Gitea."},
}
var queued int
_ = s.DB.QueryRow(`SELECT count(*) FROM posts`).Scan(&queued)
s.render(w, r, "dashboard", page{Title: "Overview", Nav: "home", Data: map[string]any{
"Steps": steps,
"Modules": modules,
"ImportStatus": s.ImportStatus,
"ImportErr": errString(s.ImportErr),
"QueuedPosts": queued,
}})
}
func ifElse(cond bool, a, b string) string {
if cond {
return a
}
return b
}
func errString(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func atOf(c *bridge.Checkin) time.Time {
if c == nil {
return time.Time{}
}
return c.At
}
func coreDomain(c *core.Core) string {
if c == nil {
return ""
}
return c.Domain
}
func inventorySummary(c map[string]int) string {
if c[inventory.Partner]+c[inventory.Competitor]+c[inventory.Watch] == 0 {
return "Add the partners and competitors you post about"
}
return plural(c[inventory.Partner], "partner") + ", " + plural(c[inventory.Competitor], "competitor") + ", " + plural(c[inventory.Watch], "watched")
}
func (s *Server) connectionSummary(c map[string]Connection) string {
var parts []string
if a := c["x"].Account; a != "" {
parts = append(parts, "X @"+a)
} else if s.Secrets.Has(secrets.XAccessToken) {
parts = append(parts, "X")
}
if s.Secrets.Has(secrets.LinkedInAccessToken) {
parts = append(parts, "LinkedIn")
}
if len(parts) == 0 {
return "Connect X and LinkedIn"
}
return strings.Join(parts, ", ")
}
func plural(n int, word string) string {
if word == "watched" {
return strconv.Itoa(n) + " watched"
}
if n == 1 {
return "1 " + word
}
return strconv.Itoa(n) + " " + word + "s"
}
// --- Core & Hermes ---
type coreData struct {
Core *core.Core
User string
HubURL string
MCPURL string
MCPToken string
Last *bridge.Checkin
Prompt string
HermesConfig string
HermesEnv string
}
func (s *Server) corePage(w http.ResponseWriter, r *http.Request) {
last, err := bridge.Last(s.DB)
if err != nil {
s.serverError(w, err)
return
}
d := coreData{
Core: s.Core,
MCPURL: "http://127.0.0.1:" + publicPort(s.PublicURL) + "/mcp",
MCPToken: s.MCPToken,
Last: last,
Prompt: bridge.CheckinPrompt,
}
hub := "https://mcphub.<your Core's domain>/sse?as_user=<your user name>"
if s.Core != nil {
d.User = s.Core.User()
hub = s.Core.MCPHubURL()
}
d.HubURL = hub
d.HermesConfig = `mcp_servers:
mcphub:
url: "` + hub + `"
headers:
Authorization: "Basic ${MCPHUB_AUTH}"
supermarket:
url: "` + d.MCPURL + `"
headers:
Authorization: "Bearer ${SUPERMARKET_MCP_TOKEN}"`
d.HermesEnv = `MCPHUB_AUTH=<base64 of user:password>
SUPERMARKET_MCP_TOKEN=<the token below>`
s.render(w, r, "core", page{Title: "Core & Hermes", Nav: "core", Data: d})
}
func publicPort(u string) string {
if i := strings.LastIndex(u, ":"); i > strings.Index(u, "://")+2 {
return strings.TrimRight(u[i+1:], "/")
}
return "8470"
}
type serviceCheck struct {
Name, URL, Status string
OK bool
}
// coreChecks asks each Core service whether it answers. It's an htmx
// fragment, loaded after the page so a slow service doesn't hold it up.
func (s *Server) coreChecks(w http.ResponseWriter, r *http.Request) {
if s.Core == nil {
s.fragment(w, "core", "checks", nil)
return
}
services := s.Core.Services()
checks := make([]serviceCheck, len(services))
client := &http.Client{
Timeout: 6 * time.Second,
// A redirect (e.g. to a login page) means the service is there.
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
var wg sync.WaitGroup
for i, svc := range services {
wg.Add(1)
go func(i int, svc core.Service) {
defer wg.Done()
c := serviceCheck{Name: svc.Name, URL: svc.URL}
ctx, cancel := context.WithTimeout(r.Context(), 6*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, svc.URL, nil)
res, err := client.Do(req)
switch {
case err != nil:
c.Status = "doesn't answer"
var dnsErr interface{ Timeout() bool }
if errors.As(err, &dnsErr) && dnsErr.Timeout() {
c.Status = "timed out"
}
case res.StatusCode >= 500:
c.Status = "error " + res.Status
res.Body.Close()
default:
c.OK = true
c.Status = "answers (" + res.Status + ")"
res.Body.Close()
}
checks[i] = c
}(i, svc)
}
wg.Wait()
s.fragment(w, "core", "checks", checks)
}
// --- AI servers CoreDesktop found ---
// AIServer is an LLM server from CoreDesktop's `configure ai-servers`, as
// install.sh found it in opencode's settings.
type AIServer struct {
Name string `json:"name"`
BaseURL string `json:"base_url"`
}
func (s *Server) aiServers() []AIServer {
raw, err := os.ReadFile(filepath.Join(s.DataDir, "ai-servers.json"))
if err != nil {
return nil
}
var out []AIServer
if err := json.Unmarshal(raw, &out); err != nil {
s.Log.Warn("ai-servers.json", "err", err)
return nil
}
return out
}
// secretState says whether a secret is set, for forms that never show values.
func (s *Server) secretState(names ...string) map[string]bool {
m := map[string]bool{}
for _, n := range names {
m[n] = s.Secrets.Has(n)
}
return m
}
+191
View File
@@ -0,0 +1,191 @@
package web
import (
"context"
"net/http"
"time"
"supermarket/internal/ai"
"supermarket/internal/profile"
)
type profileData struct {
P *profile.Profile
Products []profile.Product // existing plus one blank row
Websites []profile.Website // existing plus one blank row
Drafted bool
DraftURL string
}
func withBlankRows(p *profile.Profile) profileData {
d := profileData{P: p}
d.Products = append(append([]profile.Product{}, p.Products...), profile.Product{})
d.Websites = append(append([]profile.Website{}, p.Websites...), profile.Website{})
return d
}
func (s *Server) profilePage(w http.ResponseWriter, r *http.Request) {
p, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
d := withBlankRows(p)
if len(p.Websites) > 0 {
d.DraftURL = p.Websites[0].URL
}
s.render(w, r, "profile", page{Title: "Company profile", Nav: "profile", Data: d})
}
// profileFromForm reads the profile form. Repeated rows (products, websites)
// arrive as parallel lists, one value per row for each field.
func profileFromForm(r *http.Request) *profile.Profile {
f := r.PostForm
p := &profile.Profile{
Name: f.Get("name"),
Description: f.Get("description"),
Positioning: f.Get("positioning"),
Voice: f.Get("voice"),
Avoid: profile.Lines(f.Get("avoid")),
Keywords: profile.Lines(f.Get("keywords")),
Targets: profile.Targets{
Industries: profile.Lines(f.Get("industries")),
CompanySizes: profile.Lines(f.Get("company_sizes")),
Roles: profile.Lines(f.Get("roles")),
Regions: profile.Lines(f.Get("regions")),
Problems: profile.Lines(f.Get("problems")),
BuyingSignals: profile.Lines(f.Get("buying_signals")),
Technologies: profile.Lines(f.Get("technologies")),
},
Accounts: profile.Accounts{
X: f.Get("account_x"),
LinkedIn: f.Get("account_linkedin"),
Reddit: f.Get("account_reddit"),
Subreddits: profile.Lines(f.Get("subreddits")),
},
}
at := func(key string, i int) string {
if v := f[key]; i < len(v) {
return v[i]
}
return ""
}
for i := range f["product_name"] {
p.Products = append(p.Products, profile.Product{
Name: at("product_name", i),
Description: at("product_description", i),
URL: at("product_url", i),
Pricing: at("product_pricing", i),
Benefits: profile.Lines(at("product_benefits", i)),
})
}
for i := range f["website_url"] {
p.Websites = append(p.Websites, profile.Website{
URL: at("website_url", i),
Repo: at("website_repo", i),
Branch: at("website_branch", i),
PlausibleSite: at("website_plausible", i),
SearchConsoleProperty: at("website_gsc", i),
BingSite: at("website_bing", i),
})
}
return p
}
func (s *Server) profileSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
p := profileFromForm(r)
p.Clean()
if !p.IsSet() {
s.render(w, r, "profile", page{Title: "Company profile", Nav: "profile",
Error: "The company's name and description are required.", Data: withBlankRows(p)})
return
}
if err := profile.Save(s.DB, p); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/profile", "saved")
}
// profileDraft drafts the profile from a website and shows it in the form,
// unsaved. Fields the user already filled in keep their values.
func (s *Server) profileDraft(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
siteURL := r.PostForm.Get("draft_url")
current, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
show := func(p *profile.Profile, errMsg string, drafted bool) {
d := withBlankRows(p)
d.Drafted = drafted
d.DraftURL = siteURL
s.render(w, r, "profile", page{Title: "Company profile", Nav: "profile", Error: errMsg, Data: d})
}
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
s.serverError(w, err)
return
}
client, err := ai.New(cfg, s.Secrets)
if err != nil {
show(current, err.Error()+".", false)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
defer cancel()
draft, err := profile.Draft(ctx, client, siteURL)
if err != nil {
show(current, "Couldn't draft the profile: "+err.Error(), false)
return
}
show(merge(current, draft), "", true)
}
// merge keeps what the user already entered and fills the gaps from the draft.
func merge(cur, draft *profile.Profile) *profile.Profile {
out := *cur
pick := func(a, b string) string {
if a != "" {
return a
}
return b
}
pickList := func(a, b []string) []string {
if len(a) > 0 {
return a
}
return b
}
out.Name = pick(cur.Name, draft.Name)
out.Description = pick(cur.Description, draft.Description)
out.Positioning = pick(cur.Positioning, draft.Positioning)
out.Voice = pick(cur.Voice, draft.Voice)
out.Keywords = pickList(cur.Keywords, draft.Keywords)
if len(cur.Products) == 0 {
out.Products = draft.Products
}
if len(cur.Websites) == 0 {
out.Websites = draft.Websites
}
t, dt := &out.Targets, draft.Targets
t.Industries = pickList(t.Industries, dt.Industries)
t.CompanySizes = pickList(t.CompanySizes, dt.CompanySizes)
t.Roles = pickList(t.Roles, dt.Roles)
t.Regions = pickList(t.Regions, dt.Regions)
t.Problems = pickList(t.Problems, dt.Problems)
t.BuyingSignals = pickList(t.BuyingSignals, dt.BuyingSignals)
t.Technologies = pickList(t.Technologies, dt.Technologies)
out.Accounts.X = pick(cur.Accounts.X, draft.Accounts.X)
out.Accounts.LinkedIn = pick(cur.Accounts.LinkedIn, draft.Accounts.LinkedIn)
return &out
}
+264
View File
@@ -0,0 +1,264 @@
// 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/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
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 /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 },
"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.",
}
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")
}
}
+255
View File
@@ -0,0 +1,255 @@
package web
import (
"bytes"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"testing"
"supermarket/internal/bridge"
"supermarket/internal/core"
"supermarket/internal/db"
"supermarket/internal/inventory"
"supermarket/internal/mcpserver"
"supermarket/internal/profile"
"supermarket/internal/secrets"
)
const testToken = "0123456789abcdef0123456789abcdef"
func newTestServer(t *testing.T, c *core.Core) (*Server, http.Handler) {
t.Helper()
dir := t.TempDir()
d, err := db.Open(filepath.Join(dir, "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
sec, err := secrets.Open(filepath.Join(dir, "secrets.json"))
if err != nil {
t.Fatal(err)
}
s := &Server{
DB: d, Secrets: sec, Core: c, DataDir: dir,
PublicURL: "http://localhost:8470", Version: "test", MCPToken: testToken,
MCP: mcpserver.Handler(d, testToken, "test"),
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
h, err := s.Handler()
if err != nil {
t.Fatal(err)
}
return s, h
}
func do(h http.Handler, method, target string, body io.Reader, hdr map[string]string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, target, body)
req.Host = "localhost:8470"
for k, v := range hdr {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func postForm(h http.Handler, target string, form url.Values) *httptest.ResponseRecorder {
return do(h, http.MethodPost, target, strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "http://localhost:8470",
})
}
func TestEveryPageRenders(t *testing.T) {
for _, c := range []*core.Core{nil, {Domain: "example.com", Email: "pat@example.com", Name: "Pat"}} {
s, h := newTestServer(t, c)
// Some data, so templates' non-empty branches run too.
if err := profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.",
Products: []profile.Product{{Name: "Widget", Benefits: []string{"fast"}}},
Websites: []profile.Website{{URL: "https://acme.example", Repo: "r"}}}); err != nil {
t.Fatal(err)
}
e := &inventory.Entry{Name: "Rival", Relationship: "competitor", Hashtags: []string{"rival"}}
if err := inventory.Save(s.DB, e); err != nil {
t.Fatal(err)
}
if err := bridge.Record(s.DB, bridge.Checkin{Agent: "hermes", MCPHubTools: []string{"espocrm_create_lead"}}); err != nil {
t.Fatal(err)
}
if err := s.Secrets.Set(map[string]string{secrets.XAccessToken: "tok"}); err != nil {
t.Fatal(err)
}
for _, path := range []string{"/", "/?msg=saved", "/profile", "/inventory", "/inventory?relationship=partner",
"/inventory/new", "/inventory/1", "/inventory/import", "/inventory/export",
"/settings/ai", "/settings/credentials", "/core", "/static/app.css", "/static/htmx.min.js", "/healthz"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
t.Errorf("core=%v GET %s: %d %s", c != nil, path, rec.Code, rec.Body.String())
}
}
if rec := do(h, http.MethodGet, "/inventory/999", nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("missing entry: %d", rec.Code)
}
}
}
func TestGuardRejectsForeignHostsAndCrossSitePosts(t *testing.T) {
_, h := newTestServer(t, nil)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Host = "evil.example:8470" // DNS rebinding
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusMisdirectedRequest {
t.Errorf("foreign Host: got %d", rec.Code)
}
form := url.Values{"name": {"Acme"}, "description": {"x"}}
rec = do(h, http.MethodPost, "/profile", strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://evil.example",
})
if rec.Code != http.StatusForbidden {
t.Errorf("cross-origin POST: got %d", rec.Code)
}
rec = do(h, http.MethodPost, "/profile", strings.NewReader(form.Encode()), map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Sec-Fetch-Site": "cross-site",
})
if rec.Code != http.StatusForbidden {
t.Errorf("cross-site POST without Origin: got %d", rec.Code)
}
if rec := postForm(h, "/profile", form); rec.Code != http.StatusSeeOther {
t.Errorf("same-origin POST: got %d %s", rec.Code, rec.Body.String())
}
}
func TestProfileAndInventoryForms(t *testing.T) {
s, h := newTestServer(t, nil)
form := url.Values{
"name": {" Acme "}, "description": {"We make widgets."}, "keywords": {"widgets\n\nwidget software\nWidgets"},
"product_name": {"Widget", ""}, "product_url": {"https://a.example/w", ""},
"product_description": {"A widget", ""}, "product_pricing": {"$5", ""}, "product_benefits": {"cheap\nfast", ""},
"website_url": {"https://acme.example/", ""}, "website_repo": {"https://gitea.example/acme/site.git", ""},
"website_branch": {"", ""}, "website_plausible": {"", ""}, "website_gsc": {"", ""}, "website_bing": {"", ""},
"account_x": {"@acme"}, "subreddits": {"r/selfhosted\n/r/homelab"},
}
if rec := postForm(h, "/profile", form); rec.Code != http.StatusSeeOther {
t.Fatalf("save profile: %d %s", rec.Code, rec.Body.String())
}
p, _ := profile.Load(s.DB)
if p.Name != "Acme" || len(p.Products) != 1 || len(p.Products[0].Benefits) != 2 {
t.Errorf("profile products: %+v", p)
}
if len(p.Keywords) != 2 {
t.Errorf("keywords should be de-duplicated case-insensitively: %q", p.Keywords)
}
if len(p.Websites) != 1 || p.Websites[0].URL != "https://acme.example" || p.Websites[0].Branch != "main" {
t.Errorf("websites: %+v", p.Websites)
}
if p.Accounts.X != "acme" || strings.Join(p.Accounts.Subreddits, ",") != "selfhosted,homelab" {
t.Errorf("accounts: %+v", p.Accounts)
}
// Missing description: the form comes back with an error, nothing saved.
rec := postForm(h, "/profile", url.Values{"name": {"Other"}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "required") {
t.Errorf("invalid profile: %d", rec.Code)
}
entry := url.Values{"name": {"Rival"}, "relationship": {"competitor"}, "hashtags": {"rival, #Other"}, "twitter_handle": {"@rival"}}
if rec := postForm(h, "/inventory/save", entry); rec.Code != http.StatusSeeOther {
t.Fatalf("save entry: %d %s", rec.Code, rec.Body.String())
}
entries, _ := inventory.List(s.DB, "competitor")
if len(entries) != 1 || entries[0].TwitterHandle != "rival" || entries[0].MentionPolicy != "category" ||
strings.Join(entries[0].Hashtags, " ") != "#rival #Other" {
t.Fatalf("entry: %+v", entries)
}
// Same name, different case: refused.
rec = postForm(h, "/inventory/save", url.Values{"name": {"RIVAL"}, "relationship": {"partner"}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "already has that name") {
t.Errorf("duplicate: %d", rec.Code)
}
rec = postForm(h, "/inventory/import", url.Values{"example": {"federated"}, "relationship": {"watch"}})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "21 added") {
t.Errorf("import example: %d %s", rec.Code, rec.Body.String())
}
partners, _ := inventory.List(s.DB, "partner")
if len(partners) != 21 {
t.Errorf("example entries are partners: got %d", len(partners))
}
if rec := postForm(h, "/inventory/1/delete", nil); rec.Code != http.StatusSeeOther {
t.Errorf("delete: %d", rec.Code)
}
}
func TestCredentialsKeepAndRemove(t *testing.T) {
s, h := newTestServer(t, nil)
postForm(h, "/settings/credentials", url.Values{secrets.AnthropicAPIKey: {" sk-1 "}, secrets.YouTubeAPIKey: {"yt"}})
// Empty field keeps the value; remove clears it.
postForm(h, "/settings/credentials", url.Values{secrets.AnthropicAPIKey: {""}, "remove:" + secrets.YouTubeAPIKey: {"on"}})
if got := s.Secrets.Get(secrets.AnthropicAPIKey); got != "sk-1" {
t.Errorf("anthropic key = %q", got)
}
if s.Secrets.Has(secrets.YouTubeAPIKey) {
t.Error("youtube key should be removed")
}
page := do(h, http.MethodGet, "/settings/credentials", nil, nil).Body.String()
if strings.Contains(page, "sk-1") {
t.Error("the credentials page must never show a saved value")
}
}
func TestOAuthCallbackRejectsUnknownState(t *testing.T) {
_, h := newTestServer(t, nil)
rec := do(h, http.MethodGet, "/auth/x/callback?state=nope&code=c", nil, nil)
if rec.Code != http.StatusSeeOther || !strings.Contains(rec.Header().Get("Location"), "oauth-expired") {
t.Errorf("got %d %s", rec.Code, rec.Header().Get("Location"))
}
}
func TestMCPNeedsTokenAndChecksIn(t *testing.T) {
s, h := newTestServer(t, nil)
call := func(token string, body any) *httptest.ResponseRecorder {
raw, _ := json.Marshal(body)
hdr := map[string]string{"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
if token != "" {
hdr["Authorization"] = "Bearer " + token
}
return do(h, http.MethodPost, "/mcp", bytes.NewReader(raw), hdr)
}
list := map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
if rec := call("", list); rec.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", rec.Code)
}
if rec := call("wrong", list); rec.Code != http.StatusUnauthorized {
t.Errorf("wrong token: %d", rec.Code)
}
rec := call(testToken, list)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "bridge_checkin") {
t.Fatalf("tools/list: %d %s", rec.Code, rec.Body.String())
}
rec = call(testToken, map[string]any{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": map[string]any{
"name": "bridge_checkin",
"arguments": map[string]any{"agent": "hermes", "mcphub_tools": []string{"espocrm_list_leads"}},
}})
if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), `"isError":true`) {
t.Fatalf("checkin: %d %s", rec.Code, rec.Body.String())
}
last, err := bridge.Last(s.DB)
if err != nil || last == nil || last.Agent != "hermes" || len(last.MCPHubTools) != 1 {
t.Fatalf("checkin not recorded: %+v %v", last, err)
}
}
+308
View File
@@ -0,0 +1,308 @@
package web
import (
"context"
"net/http"
"strings"
"time"
"supermarket/internal/ai"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/api/twitter"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
)
// --- AI provider ---
// Anthropic models offered in the model field. Any model ID can be typed.
var anthropicModels = []string{"claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", "claude-fable-5-2"}
var efforts = []string{"low", "medium", "high", "xhigh", "max"}
func (s *Server) aiPage(w http.ResponseWriter, r *http.Request) {
cfg, err := ai.LoadConfig(s.DB)
if err != nil {
s.serverError(w, err)
return
}
s.renderAI(w, r, cfg, "")
}
func (s *Server) renderAI(w http.ResponseWriter, r *http.Request, cfg ai.Config, errMsg string) {
s.render(w, r, "ai", page{Title: "AI provider", Nav: "settings", Error: errMsg, Data: map[string]any{
"Cfg": cfg,
"AnthropicModels": anthropicModels,
"Efforts": efforts,
"Tasks": ai.Tasks,
"Servers": s.aiServers(),
"HasAnthropicKey": s.Secrets.Has(secrets.AnthropicAPIKey),
}})
}
func aiFromForm(r *http.Request) ai.Config {
f := r.PostForm
cfg := ai.Config{
Provider: f.Get("provider"),
Model: strings.TrimSpace(f.Get("model")),
BaseURL: ai.NormalizeBaseURL(f.Get("base_url")),
Effort: f.Get("effort"),
TaskModels: map[string]string{},
}
for _, t := range ai.Tasks {
if m := strings.TrimSpace(f.Get("task_" + t.ID)); m != "" {
cfg.TaskModels[t.ID] = m
}
}
if cfg.Provider != ai.ProviderOpenAI {
cfg.Provider = ai.ProviderAnthropic
cfg.BaseURL = ""
} else {
cfg.Effort = ""
}
return cfg
}
func (s *Server) aiSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cfg := aiFromForm(r)
switch {
case cfg.Model == "":
s.renderAI(w, r, cfg, "Choose a model.")
return
case cfg.Provider == ai.ProviderOpenAI && cfg.BaseURL == "":
s.renderAI(w, r, cfg, "Enter the server's address.")
return
}
if err := ai.SaveConfig(s.DB, cfg); err != nil {
s.serverError(w, err)
return
}
redirect(w, r, "/settings/ai", "saved")
}
// aiTest sends a short prompt with the form's (unsaved) settings and shows
// the reply. htmx swaps the result into the page.
func (s *Server) aiTest(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
cfg := aiFromForm(r)
result := map[string]any{}
client, err := ai.New(cfg, s.Secrets)
if err == nil {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
start := time.Now()
var reply string
reply, err = client.Generate(ctx, ai.Request{
Prompt: "Reply with one short sentence confirming you can help write marketing copy.",
MaxTokens: 2000,
})
result["Reply"] = reply
result["Took"] = time.Since(start).Round(100 * time.Millisecond).String()
}
if err != nil {
result["Error"] = err.Error()
}
s.fragment(w, "ai", "test-result", result)
}
// aiModels lists an OpenAI-compatible server's models (htmx fragment).
func (s *Server) aiModels(w http.ResponseWriter, r *http.Request) {
base := r.URL.Query().Get("base_url")
data := map[string]any{}
if strings.TrimSpace(base) == "" {
data["Error"] = "Enter the server's address first."
} else {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
models, err := ai.ListModels(ctx, base, s.Secrets.Get(secrets.OpenAIAPIKey))
if err != nil {
data["Error"] = err.Error()
}
data["Models"] = models
}
s.fragment(w, "ai", "model-list", data)
}
// --- Credentials ---
// credentialFields are the secrets the credentials form edits, in order.
var credentialFields = []struct {
Group, Name, Label, Help string
}{
{"AI", secrets.AnthropicAPIKey, "Anthropic API key", "From console.anthropic.com."},
{"AI", secrets.OpenAIAPIKey, "API key for an OpenAI-compatible server", "Only if your server asks for one (Ollama and LM Studio don't)."},
{"X", secrets.XBearerToken, "Bearer token", "For reading posts. Needs an X API plan with read access."},
{"X", secrets.XClientID, "OAuth 2.0 client ID", "For posting. From your app in the X developer portal."},
{"X", secrets.XClientSecret, "OAuth 2.0 client secret", "Only for confidential clients; leave empty for a public client."},
{"LinkedIn", secrets.LinkedInClientID, "Client ID", "From your app at linkedin.com/developers."},
{"LinkedIn", secrets.LinkedInClientSecret, "Client secret", ""},
{"YouTube", secrets.YouTubeAPIKey, "API key", "Free, from console.cloud.google.com (YouTube Data API v3)."},
}
func (s *Server) credentialsPage(w http.ResponseWriter, r *http.Request) {
names := make([]string, 0, len(credentialFields)+2)
for _, f := range credentialFields {
names = append(names, f.Name)
}
names = append(names, secrets.XAccessToken, secrets.LinkedInAccessToken)
s.render(w, r, "credentials", page{Title: "Credentials", Nav: "settings", Data: map[string]any{
"Fields": credentialFields,
"Set": s.secretState(names...),
"Connections": s.connections(),
"XRedirect": s.PublicURL + "/auth/x/callback",
"LIRedirect": s.PublicURL + "/auth/linkedin/callback",
"XToken": secrets.XAccessToken,
"LIToken": secrets.LinkedInAccessToken,
}})
}
// credentialsSave stores what was typed. An empty field keeps the saved
// value; "remove" clears it.
func (s *Server) credentialsSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
updates := map[string]string{}
for _, f := range credentialFields {
if r.PostForm.Get("remove:"+f.Name) == "on" {
updates[f.Name] = ""
continue
}
if v := strings.TrimSpace(r.PostForm.Get(f.Name)); v != "" {
updates[f.Name] = v
}
}
if len(updates) > 0 {
if err := s.Secrets.Set(updates); err != nil {
s.serverError(w, err)
return
}
}
redirect(w, r, "/settings/credentials", "saved")
}
// --- OAuth ---
const oauthTTL = 15 * time.Minute
func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
provider := r.PathValue("provider")
var (
authURL string
p *oauth.Pending
err error
)
switch provider {
case "x":
id := s.Secrets.Get(secrets.XClientID)
if id == "" {
http.Error(w, "Save X's OAuth client ID first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.XStart(id, s.PublicURL+"/auth/x/callback")
case "linkedin":
id := s.Secrets.Get(secrets.LinkedInClientID)
if id == "" || !s.Secrets.Has(secrets.LinkedInClientSecret) {
http.Error(w, "Save LinkedIn's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.LinkedInStart(id, s.PublicURL+"/auth/linkedin/callback")
default:
http.NotFound(w, r)
return
}
if err != nil {
s.serverError(w, err)
return
}
s.mu.Lock()
for state, old := range s.pending {
if time.Since(old.Started) > oauthTTL {
delete(s.pending, state)
}
}
s.pending[p.State] = p
s.mu.Unlock()
http.Redirect(w, r, authURL, http.StatusSeeOther)
}
func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
provider := r.PathValue("provider")
q := r.URL.Query()
s.mu.Lock()
p := s.pending[q.Get("state")]
delete(s.pending, q.Get("state")) // a state is good for one callback
s.mu.Unlock()
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL {
redirect(w, r, "/settings/credentials", "oauth-expired")
return
}
fail := func(msg string) {
s.render(w, r, "message", page{Title: "Sign-in failed", Nav: "settings", Error: msg,
Data: map[string]string{"Back": "/settings/credentials"}})
}
if e := q.Get("error"); e != "" {
fail("The provider said: " + e + " " + q.Get("error_description"))
return
}
code := q.Get("code")
if code == "" {
fail("The provider sent no authorization code.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
switch provider {
case "x":
res, err := oauth.XExchange(ctx, s.Secrets.Get(secrets.XClientID), s.Secrets.Get(secrets.XClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
account := ""
if name, err := twitter.New("", res.AccessToken, 0).VerifyCredentials(ctx); err == nil {
account = name
} else {
s.Log.Warn("x: couldn't verify the new token", "err", err)
}
if err := s.Secrets.Set(map[string]string{secrets.XAccessToken: res.AccessToken, secrets.XRefreshToken: res.RefreshToken}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
if err := s.saveConnection("x", Connection{Account: account, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/credentials", "x-connected")
case "linkedin":
res, err := oauth.LinkedInExchange(ctx, s.Secrets.Get(secrets.LinkedInClientID), s.Secrets.Get(secrets.LinkedInClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
urn, err := linkedinapi.GetAuthorURN(ctx, res.AccessToken)
if err != nil {
fail("Signed in, but couldn't find your LinkedIn member ID: " + err.Error())
return
}
if err := s.Secrets.Set(map[string]string{secrets.LinkedInAccessToken: res.AccessToken, secrets.LinkedInAuthorURN: urn}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
if err := s.saveConnection("linkedin", Connection{Account: urn, At: time.Now()}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/credentials", "li-connected")
default:
http.NotFound(w, r)
}
}
+122
View File
@@ -0,0 +1,122 @@
/* Supermarket. Colors follow the Federated sites: a navy bar, a magenta
accent and a cyan primary button. */
:root {
--navy: #0b1d3a;
--navy-2: #13294f;
--magenta: #c2187a;
--cyan: #0891b2;
--cyan-dark: #0e7490;
--ink: #1b2433;
--muted: #5b6577;
--line: #dde2ea;
--band: #f4f6f9;
--ok: #157f3b;
--bad: #b42318;
--warn-bg: #fff6e5;
--radius: 10px;
font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
color: var(--ink);
background: var(--band);
}
* { box-sizing: border-box; }
body { margin: 0; line-height: 1.5; }
a { color: var(--cyan-dark); }
code, pre { font-family: ui-monospace, "JetBrains Mono", Menlo, monospace; font-size: 0.9em; }
pre { background: var(--navy); color: #e6edf7; padding: 0.9rem 1rem; border-radius: 8px; overflow-x: auto; white-space: pre-wrap; }
.topbar { background: var(--navy); color: #fff; display: flex; align-items: center; gap: 2rem; padding: 0.8rem 1.5rem; flex-wrap: wrap; }
.brand { color: #fff; font-weight: 700; font-size: 1.15rem; text-decoration: none; letter-spacing: -0.01em; }
.brand span { color: #f472b6; }
.topbar nav { display: flex; gap: 0.25rem; flex-wrap: wrap; }
.topbar nav a { color: #c9d4e6; text-decoration: none; padding: 0.35rem 0.75rem; border-radius: 6px; }
.topbar nav a:hover { background: var(--navy-2); color: #fff; }
.topbar nav a[aria-current="page"] { background: var(--navy-2); color: #fff; box-shadow: inset 0 -2px 0 var(--magenta); }
main { max-width: 1080px; margin: 0 auto; padding: 1.5rem; }
footer { text-align: center; color: var(--muted); font-size: 0.85rem; padding: 2rem 0; }
h1 { font-size: 1.7rem; margin: 0.5rem 0 0.75rem; letter-spacing: -0.02em; }
h2 { font-size: 1.2rem; margin: 0 0 0.75rem; }
h3 { font-size: 1.05rem; margin: 0 0 0.5rem; }
.lede { color: var(--muted); margin-top: 0; }
.help { display: block; color: var(--muted); font-size: 0.85rem; font-weight: normal; margin-top: 0.2rem; }
.card { background: #fff; border: 1px solid var(--line); border-radius: var(--radius); padding: 1.25rem 1.4rem; margin: 0 0 1.25rem; }
.card.warn, .warn { background: var(--warn-bg); border-color: #f5d49a; }
.card.empty { text-align: center; color: var(--muted); }
details.card > summary { cursor: pointer; font-weight: 600; }
details.card[open] > summary { margin-bottom: 0.75rem; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 1rem; }
.module p { color: var(--muted); margin: 0; }
.heading { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
.buttons { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.flash { background: #e7f6ed; border: 1px solid #a8dcb9; color: #0f5a2a; padding: 0.6rem 0.9rem; border-radius: 8px; }
.error { background: #fdecea; border: 1px solid #f3b5ae; color: var(--bad); padding: 0.6rem 0.9rem; border-radius: 8px; }
.ok { color: var(--ok); }
.warn-text { color: #8a5300; }
.steps { list-style: none; margin: 0; padding: 0; }
.steps li { display: flex; gap: 1rem; align-items: baseline; padding: 0.55rem 0; border-bottom: 1px solid var(--line); }
.steps li:last-child { border-bottom: 0; }
.steps li::before { content: "○"; color: var(--muted); width: 1.2rem; flex: none; }
.steps li.done::before { content: "✓"; color: var(--ok); font-weight: 700; }
.steps li a { min-width: 11rem; color: var(--ink); text-decoration: none; }
.steps li span { color: var(--muted); }
.badge { display: inline-block; font-size: 0.75rem; font-weight: 600; padding: 0.1rem 0.5rem; border-radius: 999px; background: var(--band); color: var(--muted); vertical-align: middle; }
.badge.partner { background: #e0f2f7; color: var(--cyan-dark); }
.badge.competitor { background: #fbe4f0; color: var(--magenta); }
.badge.watch { background: #eef0f4; color: var(--muted); }
.tabs { display: flex; gap: 0.25rem; margin-bottom: 1rem; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
.tabs a { padding: 0.45rem 0.9rem; text-decoration: none; color: var(--muted); border-bottom: 2px solid transparent; text-transform: capitalize; }
.tabs a[aria-current="page"] { color: var(--ink); border-color: var(--magenta); font-weight: 600; }
table.list { width: 100%; border-collapse: collapse; background: #fff; border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
table.list th, table.list td { text-align: left; padding: 0.6rem 0.8rem; border-bottom: 1px solid var(--line); vertical-align: top; }
table.list th { background: var(--band); font-size: 0.85rem; color: var(--muted); font-weight: 600; }
table.list tr:last-child td { border-bottom: 0; }
label { display: block; font-weight: 600; font-size: 0.92rem; margin-bottom: 0.9rem; }
input, select, textarea { display: block; width: 100%; margin-top: 0.3rem; font: inherit; font-weight: normal; padding: 0.5rem 0.65rem; border: 1px solid #c5ccd8; border-radius: 7px; background: #fff; color: var(--ink); }
textarea { resize: vertical; }
input:focus, select:focus, textarea:focus { outline: 2px solid var(--cyan); outline-offset: 0; border-color: var(--cyan); }
input[type="checkbox"], input[type="radio"] { display: inline; width: auto; margin: 0 0.4rem 0 0; }
input[type="file"] { border: 0; padding-left: 0; }
label.check { font-weight: normal; display: flex; align-items: baseline; gap: 0.2rem; }
label.small { font-size: 0.85rem; color: var(--muted); }
fieldset { border: 1px solid var(--line); border-radius: 8px; padding: 0.9rem 1rem 0.2rem; margin: 0 0 1rem; }
fieldset.choice { border: 0; padding: 0; }
legend { font-weight: 600; padding: 0 0.3rem; }
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 0 1.25rem; }
.row { display: flex; gap: 0.5rem; align-items: center; }
.row input { margin: 0; }
.secret { display: flex; gap: 1rem; align-items: flex-end; }
.secret > label:first-child { flex: 1; }
.inline-form label { margin-bottom: 0.2rem; }
button, .button { display: inline-block; font: inherit; font-weight: 600; padding: 0.55rem 1.1rem; border-radius: 7px; border: 1px solid var(--cyan-dark); background: var(--cyan); color: #fff; cursor: pointer; text-decoration: none; white-space: nowrap; }
button:hover, .button:hover { background: var(--cyan-dark); }
button.secondary, .button.secondary { background: #fff; color: var(--cyan-dark); border-color: #b9c3d1; }
button.secondary:hover, .button.secondary:hover { background: var(--band); }
button.danger { background: #fff; color: var(--bad); border-color: #f3b5ae; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.actions { display: flex; gap: 0.75rem; align-items: center; margin: 1rem 0 1.5rem; flex-wrap: wrap; }
.danger-zone { margin-top: 2rem; }
.connect { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; }
.copy { position: relative; }
.copy button { position: absolute; top: 0.5rem; right: 0.5rem; padding: 0.25rem 0.7rem; font-size: 0.85rem; }
.pills { list-style: none; padding: 0; display: flex; flex-wrap: wrap; gap: 0.4rem; }
.pill { display: inline-block; background: var(--band); border: 1px solid var(--line); border-radius: 999px; padding: 0.15rem 0.7rem; font-size: 0.85rem; color: var(--ink); font-weight: normal; }
button.pill:hover { background: #e0f2f7; }
.checks { list-style: none; padding: 0; }
.checks li { padding: 0.25rem 0; }
.checks li::before { margin-right: 0.5rem; font-weight: 700; }
.checks li.ok::before { content: "✓"; color: var(--ok); }
.checks li.bad::before { content: "✗"; color: var(--bad); }
.checks li.ok { color: var(--ink); }
.htmx-indicator { display: none; color: var(--muted); }
.htmx-request .htmx-indicator, .htmx-request.htmx-indicator { display: inline; }
[hidden] { display: none !important; }
+51
View File
@@ -0,0 +1,51 @@
// Small behaviours for Supermarket's pages. Loaded as a file because the
// Content-Security-Policy allows no inline scripts.
(function () {
"use strict";
// Show the fields for the chosen AI provider ([data-show-for]).
function syncProvider() {
var chosen = document.querySelector('input[data-toggle="provider"]:checked');
if (!chosen) return;
document.querySelectorAll("[data-show-for]").forEach(function (el) {
el.hidden = el.getAttribute("data-show-for") !== chosen.value;
});
}
document.addEventListener("change", function (e) {
if (e.target.matches('input[data-toggle="provider"]')) syncProvider();
});
document.addEventListener("click", function (e) {
// Copy a <pre>'s text: <button data-copy="id-of-pre">
var copy = e.target.closest("[data-copy]");
if (copy) {
var src = document.getElementById(copy.getAttribute("data-copy"));
if (src && navigator.clipboard) {
navigator.clipboard.writeText(src.textContent).then(function () {
var label = copy.textContent;
copy.textContent = "Copied";
setTimeout(function () { copy.textContent = label; }, 1500);
});
}
return;
}
// Fill a field from a list: <button data-fill="field-name" data-value="v">
var fill = e.target.closest("[data-fill]");
if (fill) {
var field = document.querySelector('[name="' + fill.getAttribute("data-fill") + '"]');
if (field) {
field.value = fill.getAttribute("data-value");
field.focus();
}
}
});
// Ask before submitting a form with data-confirm.
document.addEventListener("submit", function (e) {
var msg = e.target.getAttribute("data-confirm");
if (msg && !window.confirm(msg)) e.preventDefault();
});
document.addEventListener("DOMContentLoaded", syncProvider);
})();
File diff suppressed because one or more lines are too long
+65
View File
@@ -0,0 +1,65 @@
{{define "content"}}{{with .Data}}{{$cfg := .Cfg}}
<nav class="tabs">
<a href="/settings/ai" aria-current="page">AI provider</a>
<a href="/settings/credentials">Credentials</a>
</nav>
<h1>AI provider</h1>
<form method="post" action="/settings/ai" id="ai-form">
<section class="card">
<fieldset class="choice">
<legend>Provider</legend>
<label class="check"><input type="radio" name="provider" value="anthropic" {{if ne $cfg.Provider "openai"}}checked{{end}} data-toggle="provider">
Anthropic (Claude) {{if not .HasAnthropicKey}}<span class="help">— add the API key under <a href="/settings/credentials">Credentials</a></span>{{end}}</label>
<label class="check"><input type="radio" name="provider" value="openai" {{if eq $cfg.Provider "openai"}}checked{{end}} data-toggle="provider">
A server on your network (Ollama, LM Studio, llama.cpp, vLLM) or another OpenAI-compatible service</label>
</fieldset>
<div data-show-for="openai">
<label>Server address <input name="base_url" id="base_url" value="{{$cfg.BaseURL}}" placeholder="http://192.168.1.20:11434" list="servers">
<span class="help">Supermarket runs in Docker: for a server on this computer use <code>http://host.docker.internal:11434</code>, and use an IP address rather than a <code>.local</code> name.</span></label>
<datalist id="servers">{{range .Servers}}<option value="{{.BaseURL}}">{{.Name}}</option>{{end}}</datalist>
{{if .Servers}}<p class="help">Found by CoreDesktop's <code>configure ai-servers</code>: {{range $i, $s := .Servers}}{{if $i}}, {{end}}{{$s.Name}} ({{$s.BaseURL}}){{end}}.</p>{{end}}
<button type="button" class="secondary" hx-get="/settings/ai/models" hx-include="#base_url" hx-target="#model-list">List its models</button>
<div id="model-list"></div>
</div>
<label>Model <input name="model" value="{{$cfg.Model}}" list="anthropic-models" required></label>
<datalist id="anthropic-models">{{range .AnthropicModels}}<option value="{{.}}">{{end}}</datalist>
<label data-show-for="anthropic">Effort
<select name="effort">
{{range .Efforts}}<option value="{{.}}" {{if eq $cfg.Effort .}}selected{{end}}>{{.}}</option>{{end}}
</select>
<span class="help">How hard the model thinks. Medium suits drafting; higher costs more and takes longer.</span>
</label>
</section>
<section class="card">
<h2>Model per task</h2>
<p class="help">Leave empty to use the model above. Same provider.</p>
{{range .Tasks}}
<label>{{.Label}} <input name="task_{{.ID}}" value="{{index $cfg.TaskModels .ID}}" list="anthropic-models"></label>
{{end}}
</section>
<div class="actions">
<button type="submit">Save</button>
<button type="button" class="secondary" hx-post="/settings/ai/test" hx-include="#ai-form" hx-target="#test-result" hx-indicator="#testing">Test</button>
<span id="testing" class="htmx-indicator">Asking the model…</span>
</div>
<div id="test-result"></div>
</form>
{{end}}{{end}}
{{define "test-result"}}
{{if .Error}}<p class="error">{{.Error}}</p>
{{else}}<p class="flash">The model answered in {{.Took}}: “{{.Reply}}”</p>{{end}}
{{end}}
{{define "model-list"}}
{{if .Error}}<p class="error">{{.Error}}</p>
{{else if .Models}}<p class="help">Models on this server (click one to use it):</p>
<ul class="pills">{{range .Models}}<li><button type="button" class="pill" data-fill="model" data-value="{{.}}">{{.}}</button></li>{{end}}</ul>
{{else}}<p class="help">The server has no models.</p>{{end}}
{{end}}
+53
View File
@@ -0,0 +1,53 @@
{{define "content"}}{{with .Data}}
<h1>Core &amp; Hermes</h1>
<section class="card">
<h2>Federated Core</h2>
{{if .Core}}
<p><strong>{{.Core.Domain}}</strong> · {{.Core.Email}}{{if .Core.Name}} · {{.Core.Name}}{{end}}</p>
<p class="help">From CoreDesktop's <code>configure core</code>. To use another Core, change it there and run <code>update</code>.</p>
<div hx-get="/core/checks" hx-trigger="load" hx-swap="outerHTML"><p class="help">Checking the Core's services…</p></div>
{{else}}
<p>No Core found. Run <code>configure core</code> in CoreDesktop, then <code>update</code>. Without a Core, everything works except EspoCRM, Plausible and publishing through Gitea.</p>
{{end}}
</section>
<section class="card">
<h2>Hermes bridge</h2>
<p>Hermes, CoreDesktop's agent, is the only thing that talks to your Core's MCP hub. It reaches Supermarket at <code>{{.MCPURL}}</code>.</p>
{{with .Last}}
<p class="ok">Hermes last checked in {{ago .At}}{{if .Note}}: “{{.Note}}”{{end}}.</p>
{{if .MCPHubTools}}
<details><summary>It can use {{len .MCPHubTools}} tools from the MCP hub</summary>
<ul class="pills">{{range .MCPHubTools}}<li><span class="pill">{{.}}</span></li>{{end}}</ul>
</details>
{{else}}<p class="warn-text">It reported no tools from the MCP hub: check the hub's address and password.</p>{{end}}
{{else}}
<p>Hermes hasn't checked in yet.</p>
{{end}}
<h3>Test the bridge</h3>
<p>Ask Hermes this, in its terminal or through Matrix:</p>
<div class="copy"><pre id="prompt">{{.Prompt}}</pre><button type="button" class="secondary" data-copy="prompt">Copy</button></div>
<p class="help">Then reload this page.</p>
</section>
<details class="card">
<summary>Set up Hermes by hand</summary>
<p><code>install.sh</code> does this for you. To do it yourself, add this to <code>~/.hermes/config.yaml</code>:</p>
<div class="copy"><pre id="hermes-config">{{.HermesConfig}}</pre><button type="button" class="secondary" data-copy="hermes-config">Copy</button></div>
<p>and this to <code>~/.hermes/.env</code>, so no password is in <code>config.yaml</code>:</p>
<pre>{{.HermesEnv}}</pre>
<p>Hermes runs in CoreDesktop's sandbox, so also let it reach both servers: add <code>mcphub.{{if .Core}}{{.Core.Domain}}{{else}}&lt;your Core's domain&gt;{{end}}</code> and <code>127.0.0.1:8470</code> to <code>network.allowedDomains</code> in <code>~/.config/coredesktop/sandbox/hermes.json</code>. Then restart Hermes' gateway: <code>systemctl --user restart hermes-gateway</code>.</p>
<details><summary>Show the MCP token</summary><pre>{{.MCPToken}}</pre><p class="help">Also in <code>mcp-token</code> in the data folder.</p></details>
</details>
{{end}}{{end}}
{{define "checks"}}
{{if .}}
<ul class="checks">
{{range .}}<li class="{{if .OK}}ok{{else}}bad{{end}}"><strong>{{.Name}}</strong> <code>{{.URL}}</code> {{.Status}}</li>{{end}}
</ul>
<p class="help">These are the usual addresses on a Federated Core.</p>
{{end}}
{{end}}
+44
View File
@@ -0,0 +1,44 @@
{{define "content"}}{{with .Data}}{{$set := .Set}}
<nav class="tabs">
<a href="/settings/ai">AI provider</a>
<a href="/settings/credentials" aria-current="page">Credentials</a>
</nav>
<h1>Credentials</h1>
<p class="lede">Kept in <code>secrets.json</code> in Supermarket's data folder, readable only by you. Saved values are never shown: leave a field empty to keep what's saved.</p>
<form method="post" action="/settings/credentials">
{{$group := ""}}
{{range .Fields}}
{{if ne .Group $group}}{{if $group}}</section>{{end}}{{$group = .Group}}<section class="card"><h2>{{.Group}}</h2>{{end}}
<div class="secret">
<label>{{.Label}}
<input type="password" name="{{.Name}}" autocomplete="off" placeholder="{{if index $set .Name}}saved — type to replace{{else}}not set{{end}}">
{{if .Help}}<span class="help">{{.Help}}</span>{{end}}
</label>
{{if index $set .Name}}<label class="check small"><input type="checkbox" name="remove:{{.Name}}"> remove</label>{{end}}
</div>
{{end}}
{{if $group}}</section>{{end}}
<div class="actions"><button type="submit">Save</button></div>
</form>
<section class="card">
<h2>Sign in to post</h2>
<div class="connect">
<div>
<h3>X</h3>
{{with index .Connections "x"}}{{if .Account}}<p>Connected as @{{.Account}}, {{ago .At}}.</p>{{end}}{{end}}
{{if and (index $set .XToken) (not (index .Connections "x").Account)}}<p>A token is saved.</p>{{end}}
<p class="help">In the X developer portal, add this callback URL to your app: <code>{{.XRedirect}}</code></p>
<form method="post" action="/auth/x/start"><button type="submit" {{if not (index $set "x.client_id")}}disabled{{end}}>{{if index $set .XToken}}Reconnect{{else}}Connect{{end}} X</button></form>
</div>
<div>
<h3>LinkedIn</h3>
{{with index .Connections "linkedin"}}{{if .Account}}<p>Connected, {{ago .At}}.</p>{{end}}{{end}}
{{if and (index $set .LIToken) (not (index .Connections "linkedin").Account)}}<p>A token is saved.</p>{{end}}
<p class="help">In your LinkedIn app's Auth settings, add this redirect URL: <code>{{.LIRedirect}}</code></p>
<form method="post" action="/auth/linkedin/start"><button type="submit" {{if not (and (index $set "linkedin.client_id") (index $set "linkedin.client_secret"))}}disabled{{end}}>{{if index $set .LIToken}}Reconnect{{else}}Connect{{end}} LinkedIn</button></form>
</div>
</div>
</section>
{{end}}{{end}}
+39
View File
@@ -0,0 +1,39 @@
{{define "content"}}{{with .Data}}
<h1>Overview</h1>
<section class="card">
<h2>Setup</h2>
<ul class="steps">
{{range .Steps}}
<li class="{{if .Done}}done{{else}}todo{{end}}">
<a href="{{.Link}}"><strong>{{.Label}}</strong></a>
<span>{{.Detail}}</span>
</li>
{{end}}
</ul>
</section>
{{if .ImportErr}}
<section class="card warn">
<h2>Import from the old app failed</h2>
<p>{{.ImportErr}}</p>
<p>The old files are untouched in the data folder's <code>import/</code> directory. Fix the file named above and restart Supermarket (<code>supermarket restart</code>) to try again.</p>
</section>
{{else if .ImportStatus}}
<details class="card">
<summary>Imported from the old terminal app {{ago .ImportStatus.At}}</summary>
<ul>{{range .ImportStatus.Summary}}<li>{{.}}</li>{{end}}</ul>
{{if .QueuedPosts}}<p>{{.QueuedPosts}} queued posts are kept for the Content module (Phase 1).</p>{{end}}
</details>
{{end}}
<h2>Modules</h2>
<div class="grid">
{{range .Modules}}
<section class="card module">
<h3>{{.Name}} <span class="badge">{{.Phase}}</span></h3>
<p>{{.Body}}</p>
</section>
{{end}}
</div>
{{end}}{{end}}
+51
View File
@@ -0,0 +1,51 @@
{{define "content"}}{{with .Data}}{{$e := .E}}
<p><a href="/inventory">← Inventory</a></p>
<h1>{{if $e.ID}}{{$e.Name}}{{else}}New entry{{end}}</h1>
<form method="post" action="/inventory/save">
<input type="hidden" name="id" value="{{$e.ID}}">
<section class="card">
<div class="cols">
<label>Name <input name="name" value="{{$e.Name}}" required></label>
<label>Relationship
<select name="relationship">
{{range .Relationships}}<option value="{{.}}" {{if eq $e.Relationship .}}selected{{end}}>{{.}}</option>{{end}}
</select>
</label>
</div>
<label>Description <textarea name="description" rows="2">{{$e.Description}}</textarea></label>
<label>Talking points <textarea name="talking_points" rows="4">{{$e.TalkingPoints}}</textarea>
<span class="help">Partners: how you work together. Competitors: how you differ, where you win, and what not to claim.</span></label>
<label>Naming them in posts (competitors only)
<select name="mention_policy">
<option value="category" {{if ne $e.MentionPolicy "name"}}selected{{end}}>Don't name them; talk about the category</option>
<option value="name" {{if eq $e.MentionPolicy "name"}}selected{{end}}>Posts may name them</option>
</select>
</label>
</section>
<section class="card">
<h2>Where to watch them</h2>
<div class="cols">
<label>X handle <input name="twitter_handle" value="{{$e.TwitterHandle}}" placeholder="without @"></label>
<label>YouTube channel ID <input name="youtube_channel_id" value="{{$e.YouTubeChannelID}}" placeholder="UC…"></label>
<label>Instagram handle <input name="instagram_handle" value="{{$e.InstagramHandle}}"></label>
<label>LinkedIn page <input name="linkedin" value="{{$e.LinkedIn}}"></label>
<label>Websites <textarea name="websites" rows="3">{{lines $e.Websites}}</textarea><span class="help">One per line.</span></label>
<label>RSS or Atom feeds <textarea name="rss" rows="3">{{lines $e.RSS}}</textarea><span class="help">One per line.</span></label>
<label>Subreddits <textarea name="subreddits" rows="3">{{lines $e.Subreddits}}</textarea><span class="help">One per line, without r/.</span></label>
<label>Hashtags <input name="hashtags" value="{{join $e.Hashtags " "}}" placeholder="#Example #OpenSource"></label>
</div>
<label>Keywords <textarea name="keywords" rows="3">{{lines $e.Keywords}}</textarea>
<span class="help">Terms they own or compete on, one per line.</span></label>
</section>
<div class="actions"><button type="submit">Save</button></div>
</form>
{{if $e.ID}}
<form method="post" action="/inventory/{{$e.ID}}/delete" class="danger-zone" data-confirm="Delete {{$e.Name}} from the inventory?">
<button type="submit" class="danger">Delete {{$e.Name}}</button>
</form>
{{end}}
{{end}}{{end}}
+33
View File
@@ -0,0 +1,33 @@
{{define "content"}}{{with .Data}}
<p><a href="/inventory">← Inventory</a></p>
<h1>Import inventory</h1>
{{with .Result}}
<section class="card {{if .Errors}}warn{{end}}">
<p>{{.Added}} added, {{.Updated}} updated, {{.Skipped}} skipped (already in the inventory).</p>
{{if .Errors}}<ul>{{range .Errors}}<li>{{.}}</li>{{end}}</ul>{{end}}
<p><a href="/inventory">See the inventory</a></p>
</section>
{{end}}
<form class="card" method="post" action="/inventory/import" enctype="multipart/form-data">
<p>YAML: a list of entries, or a document with an <code>inventory:</code> list. The old app's <code>config.yaml</code> works too (its <code>applications:</code> list).</p>
<label>Paste <textarea name="yaml" rows="12" placeholder="inventory:
- name: Example
relationship: competitor
twitter_handle: example
hashtags: ['#Example']">{{.YAML}}</textarea></label>
<label>…or choose a file <input type="file" name="file" accept=".yaml,.yml,text/yaml"></label>
<div class="cols">
<label>Relationship for entries without one
<select name="relationship">{{range .Relationships}}<option value="{{.}}">{{.}}</option>{{end}}</select>
</label>
<label class="check"><input type="checkbox" name="overwrite"> Replace entries that already exist</label>
</div>
<div class="actions">
<button type="submit">Import</button>
<button type="submit" name="example" value="federated" class="secondary">Load the Federated example</button>
</div>
<p class="help">The Federated example is the 21 open source applications on a Federated Core, as partners.</p>
</form>
{{end}}{{end}}
+40
View File
@@ -0,0 +1,40 @@
{{define "content"}}{{with .Data}}
<div class="heading">
<h1>Inventory</h1>
<div class="buttons">
<a class="button" href="/inventory/new">New entry</a>
<a class="button secondary" href="/inventory/import">Import</a>
<a class="button secondary" href="/inventory/export">Export</a>
</div>
</div>
<p class="lede"><strong>Partners</strong>: Supermarket amplifies their news.
<strong>Competitors</strong>: it positions your products against theirs.
<strong>Watch</strong>: news to curate, no promotion either way.</p>
<nav class="tabs">
<a href="/inventory" {{if eq .Relationship ""}}aria-current="page"{{end}}>All</a>
{{$cur := .Relationship}}
{{range .Relationships}}<a href="/inventory?relationship={{.}}" {{if eq $cur .}}aria-current="page"{{end}}>{{.}}</a>{{end}}
</nav>
{{if .Entries}}
<table class="list">
<thead><tr><th>Name</th><th>Relationship</th><th>X</th><th>YouTube</th><th>Description</th></tr></thead>
<tbody>
{{range .Entries}}
<tr>
<td><a href="/inventory/{{.ID}}">{{.Name}}</a></td>
<td><span class="badge {{.Relationship}}">{{.Relationship}}</span></td>
<td>{{if .TwitterHandle}}@{{.TwitterHandle}}{{end}}</td>
<td>{{if .YouTubeChannelID}}✓{{end}}</td>
<td>{{truncate 90 .Description}}</td>
</tr>
{{end}}
</tbody>
</table>
{{else}}
<section class="card empty">
<p>Nothing here yet. Add the partners and competitors you post about, or <a href="/inventory/import">import a list</a>.</p>
</section>
{{end}}
{{end}}{{end}}
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="htmx-config" content='{"includeIndicatorStyles": false}'>
<title>{{.Title}} · Supermarket</title>
<link rel="stylesheet" href="/static/app.css">
<script src="/static/htmx.min.js" defer></script>
<script src="/static/app.js" defer></script>
</head>
<body>
<header class="topbar">
<a class="brand" href="/">Core<span>marketing</span></a>
<nav>
<a href="/" {{if eq .Nav "home"}}aria-current="page"{{end}}>Overview</a>
<a href="/profile" {{if eq .Nav "profile"}}aria-current="page"{{end}}>Profile</a>
<a href="/inventory" {{if eq .Nav "inventory"}}aria-current="page"{{end}}>Inventory</a>
<a href="/settings/ai" {{if eq .Nav "settings"}}aria-current="page"{{end}}>Settings</a>
<a href="/core" {{if eq .Nav "core"}}aria-current="page"{{end}}>Core &amp; Hermes</a>
</nav>
</header>
<main>
{{if .Flash}}<p class="flash" role="status">{{.Flash}}</p>{{end}}
{{if .Error}}<p class="error" role="alert">{{.Error}}</p>{{end}}
{{template "content" .}}
</main>
<footer>Supermarket {{.Version}}</footer>
</body>
</html>
+4
View File
@@ -0,0 +1,4 @@
{{define "content"}}
<h1>{{.Title}}</h1>
{{with .Data}}<p><a href="{{.Back}}">← Back</a></p>{{end}}
{{end}}
+105
View File
@@ -0,0 +1,105 @@
{{define "content"}}{{with .Data}}
<h1>Company profile</h1>
<p class="lede">Everything Supermarket writes, targets and audits starts here.</p>
<form class="card inline-form" method="post" action="/profile/draft">
<label for="draft_url"><strong>Draft from your website</strong></label>
<p class="help">Reads your home page and a few pages it links to (about, products, pricing), and fills in what's empty below. Nothing is saved until you press Save.</p>
<div class="row">
<input id="draft_url" name="draft_url" type="url" placeholder="https://example.com" value="{{.DraftURL}}" required>
<button type="submit" class="secondary">Draft</button>
</div>
<p class="help">Takes up to a minute or two.</p>
</form>
{{if .Drafted}}<p class="flash">Here's a draft. Check every field, correct what's wrong, then Save.</p>{{end}}
<form method="post" action="/profile">
{{with .P}}
<section class="card">
<h2>The company</h2>
<label>Name <input name="name" value="{{.Name}}" required></label>
<label>What it does <textarea name="description" rows="3" required>{{.Description}}</textarea>
<span class="help">Two or three sentences: what you sell and to whom.</span></label>
<label>Positioning <textarea name="positioning" rows="2">{{.Positioning}}</textarea>
<span class="help">How you differ from the alternatives.</span></label>
<label>Voice <textarea name="voice" rows="2">{{.Voice}}</textarea>
<span class="help">How posts should sound, e.g. "plain, practical, friendly; no hype".</span></label>
<label>Words and claims to avoid <textarea name="avoid" rows="3">{{lines .Avoid}}</textarea>
<span class="help">One per line.</span></label>
<label>Keywords <textarea name="keywords" rows="4">{{lines .Keywords}}</textarea>
<span class="help">Search phrases you want to rank for, one per line.</span></label>
</section>
{{end}}
<section class="card">
<h2>Products</h2>
{{range $i, $p := .Products}}
<fieldset>
<legend>{{if $p.Name}}{{$p.Name}}{{else}}Add a product{{end}}</legend>
<div class="cols">
<label>Name <input name="product_name" value="{{$p.Name}}"></label>
<label>Page <input name="product_url" type="url" value="{{$p.URL}}" placeholder="https://"></label>
</div>
<label>Description <textarea name="product_description" rows="2">{{$p.Description}}</textarea></label>
<div class="cols">
<label>Pricing <input name="product_pricing" value="{{$p.Pricing}}" placeholder="e.g. from $15/month"></label>
<label>Benefits <textarea name="product_benefits" rows="3">{{lines $p.Benefits}}</textarea>
<span class="help">One per line.</span></label>
</div>
</fieldset>
{{end}}
<p class="help">To remove a product, clear its name. Save to get another empty row.</p>
</section>
{{with .P.Targets}}
<section class="card">
<h2>Targets</h2>
<p class="help">Your ideal customers. One entry per line in each box.</p>
<div class="cols">
<label>Industries <textarea name="industries" rows="4">{{lines .Industries}}</textarea></label>
<label>Company sizes <textarea name="company_sizes" rows="4">{{lines .CompanySizes}}</textarea></label>
<label>Roles you sell to <textarea name="roles" rows="4">{{lines .Roles}}</textarea></label>
<label>Regions <textarea name="regions" rows="4">{{lines .Regions}}</textarea></label>
<label>Problems you solve <textarea name="problems" rows="4">{{lines .Problems}}</textarea></label>
<label>Buying signals <textarea name="buying_signals" rows="4">{{lines .BuyingSignals}}</textarea>
<span class="help">e.g. "hiring a sysadmin", "asking for a Google Workspace alternative"</span></label>
<label>Technologies they use <textarea name="technologies" rows="4">{{lines .Technologies}}</textarea></label>
</div>
</section>
{{end}}
<section class="card">
<h2>Websites</h2>
{{range .Websites}}
<fieldset>
<legend>{{if .URL}}{{.URL}}{{else}}Add a website{{end}}</legend>
<div class="cols">
<label>Address <input name="website_url" type="url" value="{{.URL}}" placeholder="https://"></label>
<label>Hugo repository on Gitea <input name="website_repo" value="{{.Repo}}" placeholder="https://gitea.example.com/org/site.git"></label>
<label>Branch that gets published <input name="website_branch" value="{{.Branch}}" placeholder="main"></label>
<label>Plausible site <input name="website_plausible" value="{{.PlausibleSite}}" placeholder="example.com"></label>
<label>Google Search Console property <input name="website_gsc" value="{{.SearchConsoleProperty}}" placeholder="sc-domain:example.com"></label>
<label>Bing Webmaster site <input name="website_bing" value="{{.BingSite}}" placeholder="https://example.com/"></label>
</div>
</fieldset>
{{end}}
<p class="help">To remove a website, clear its address.</p>
</section>
{{with .P.Accounts}}
<section class="card">
<h2>Accounts</h2>
<div class="cols">
<label>X handle <input name="account_x" value="{{.X}}" placeholder="without @"></label>
<label>LinkedIn page <input name="account_linkedin" value="{{.LinkedIn}}" placeholder="https://www.linkedin.com/company/…"></label>
<label>Reddit user <input name="account_reddit" value="{{.Reddit}}" placeholder="without u/"></label>
<label>Subreddits <textarea name="subreddits" rows="3">{{lines .Subreddits}}</textarea>
<span class="help">Where your customers talk, one per line, without r/.</span></label>
</div>
</section>
{{end}}
<div class="actions"><button type="submit">Save</button></div>
</form>
{{end}}{{end}}