// Package web is Supermarket's local web interface. package web import ( "bytes" "context" "embed" "fmt" "html/template" "io/fs" "log/slog" "math" "net" "net/http" "net/url" "regexp" "strconv" "strings" "supermarket/internal/config" "supermarket/internal/jobs" "supermarket/internal/storage" "sync" "sync/atomic" "time" "unicode" "unicode/utf8" "supermarket/internal/api/reddit" "supermarket/internal/api/twitter" "supermarket/internal/appmail" "supermarket/internal/billing" "supermarket/internal/content" "supermarket/internal/core" "supermarket/internal/db" "supermarket/internal/legacy" "supermarket/internal/metrics" "supermarket/internal/oidc" "supermarket/internal/posting" "supermarket/internal/prospects" "supermarket/internal/secrets" "supermarket/internal/seo" "supermarket/internal/signals" "supermarket/internal/sites" "supermarket/internal/tracking" "supermarket/internal/users" ) //go:embed templates/*.html var templateFS embed.FS //go:embed static var staticFS embed.FS // Server holds what the handlers need. type Server struct { Config *config.Config // how it's run; nil in tests: the local edition DB *db.DB Secrets *secrets.Store Core *core.Core // nil without a Core DataDir string Files storage.Store // exports and uploads: a folder or S3; nil in tests Jobs *jobs.Runner // this copy of the app, for locks shared with others; made on first use in tests 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 Mail appmail.Sender // the app's own mail (invitations, resets); nil on local Restart func() // stops the app so Docker starts it again; nil in tests Log *slog.Logger // What the legacy import did at startup, or why it failed. ImportStatus *legacy.Status ImportErr error // Team is the team this Server works for: 1 on the local and server // editions. On the multi-tenant edition each request is served by a // copy for the viewer's team (forTeam), whose DB is that team's schema. Team int64 // Teams opens each team's database (multi-tenant); nil otherwise. Teams *db.Teams // Platform is the database every team shares: people, sessions, keys, // locks. On the local and server editions, DB itself. Platform *db.DB // Plans are the multi-tenant edition's billing; nil: no billing, every // team has everything. Plans *billing.Plans testPublisher func(*posting.Account) content.Publisher // tests: posts nowhere // What a Server and its teams' copies share. *state } // state is what a Server and its copies for each team share. type state struct { pages map[string]*template.Template jobsOnce sync.Once runner *jobs.Runner setupDone atomic.Bool // the team has its owner (server edition) rotation atomic.Uint64 // which team's turn comes first (eachTeam) patterns []string // every route's pattern stripe *billing.Stripe // the platform's Stripe account (billing) mu sync.Mutex copies map[int64]*Server // each team's Server caches map[int64]*teamCache // each team's tokens and lists kept a while } // teamCache is what's kept in memory for a team. type teamCache struct { mu sync.Mutex // Reddit: an app-only token for reading rules before sign-in, and the // account's recent posts for the warnings. redditAppToken string redditAppTokenExp time.Time redditHist []reddit.Submission redditHistAt time.Time // Google's access token, which lasts an hour. googleToken string googleExpires time.Time // The Core's Authelia: its discovery document, kept a while. provider *oidc.Provider providerAt time.Time } // st is the shared state, made on first use. func (s *Server) st() *state { if s.state == nil { s.state = &state{copies: map[int64]*Server{}, caches: map[int64]*teamCache{}} } return s.state } // cache is the team's. func (s *Server) cache() *teamCache { st := s.st() st.mu.Lock() defer st.mu.Unlock() c := st.caches[s.Team] if c == nil { c = &teamCache{} st.caches[s.Team] = c } return c } // multi says whether this is the multi-tenant edition. func (s *Server) multi() bool { return s.Teams != nil } // platform is the shared database. func (s *Server) platform() *db.DB { if s.Platform != nil { return s.Platform } return s.DB } // forTeam is the Server for a team: itself on the local and server // editions; on the multi-tenant edition a copy with the team's database, // secrets and files. Copies are kept. func (s *Server) forTeam(team int64) (*Server, error) { if !s.multi() || team == s.Team { return s, nil } st := s.st() st.mu.Lock() c := st.copies[team] st.mu.Unlock() if c != nil { return c, nil } d, err := s.Teams.Open(team) if err != nil { return nil, err } key := []byte(nil) if s.Config != nil { key = s.Config.SecretKey } if key == nil { key = testSecretKey // tests without a Config } sec, err := secrets.OpenDB(d, key, nil) if err != nil { return nil, err } cp := *s cp.Team, cp.DB, cp.Secrets = team, d, sec cp.Platform = s.platform() if s.Files != nil { cp.Files = storage.Under(s.Files, teamFilesPrefix(team)) } st.mu.Lock() defer st.mu.Unlock() if c := st.copies[team]; c != nil { return c, nil } st.copies[team] = &cp return &cp, nil } // testSecretKey seals teams' secrets in tests, which have no Config. var testSecretKey = []byte("0123456789abcdef0123456789abcdef") // jobs is this copy of the app, for the locks it shares with the others. func (s *Server) jobs() *jobs.Runner { st := s.st() st.jobsOnce.Do(func() { st.runner = s.Jobs if st.runner == nil { r, err := jobs.New(s.platform(), s.Version, s.Log) if err != nil { panic(fmt.Sprintf("jobs: %v", err)) // only without a Runner from main: tests } st.runner = r } }) return st.runner } // alone says whether no other copy of the app is running: only then is // work marked "running" really interrupted, and safe to mark so. func (s *Server) alone() bool { ok, err := s.jobs().Alone() if err != nil { s.Log.Warn("jobs: looking for other copies", "err", err) return false } return ok } // jobDo runs one turn of a background job under its lock, job:: // with several copies of the app, one of them does it. // // On the multi-tenant edition it runs the turn for each active team, on // that team's Server, under the team's own lock (team::job:), so // copies of the app share the teams between them. A few teams at a time, // starting from another one each round, so one team's long turn doesn't // hold up the others'. fn's Server is the team's. func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context, *Server)) { if !s.multi() { if _, err := s.jobs().Do(ctx, "job:"+name, func(c context.Context) { fn(c, s) }); err != nil { s.Log.Warn("jobs: taking the lock", "job", name, "err", err) } return } s.eachTeam(ctx, func(ctx context.Context, ts *Server) { if name == "seo" && !ts.domainProved() { return // nothing crawled or read before the domain is proved } if !ts.jobAllowed(name) { return // its module isn't in the team's plan, or the team has lapsed } if _, err := ts.jobs().Do(ctx, ts.lockName("job:"+name), func(c context.Context) { fn(c, ts) }); err != nil { ts.Log.Warn("jobs: taking the lock", "job", name, "team", ts.team(), "err", err) } }) } // teamsAtOnce is how many teams' turns run together, in one copy. const teamsAtOnce = 4 // eachTeam runs fn for every active team (multi-tenant), a few at once, // from a different team each time. func (s *Server) eachTeam(ctx context.Context, fn func(context.Context, *Server)) { if !s.multi() { fn(ctx, s) return } list, err := users.ListTeams(s.platform()) if err != nil { s.Log.Error("jobs: listing teams", "err", err) return } var ids []int64 for _, t := range list { if t.Status == users.TeamActive { ids = append(ids, t.ID) } } if len(ids) == 0 { return } start := int(s.st().rotation.Add(1) % uint64(len(ids))) sem := make(chan struct{}, teamsAtOnce) var wg sync.WaitGroup for i := range ids { id := ids[(start+i)%len(ids)] ts, err := s.forTeam(id) if err != nil { s.Log.Error("jobs: opening a team", "team", id, "err", err) continue } select { case sem <- struct{}{}: case <-ctx.Done(): wg.Wait() return } wg.Add(1) go func() { defer wg.Done() defer func() { <-sem }() fn(ctx, ts) }() } wg.Wait() } // lockName is a lock's name for this team: shared by every copy of the // app, and apart from other teams' on the multi-tenant edition. func (s *Server) lockName(name string) string { if !s.multi() { return name } return fmt.Sprintf("team:%d:%s", s.team(), name) } // sendLock is held while an email goes out, from the queue or Send now: // one at a time, across every copy of the app. const sendLock = "outreach:send" // Handler builds the routes. func (s *Server) Handler() (http.Handler, error) { if err := s.loadTemplates(); err != nil { return nil, err } mux := &routes{s: s, mux: http.NewServeMux()} static, _ := fs.Sub(staticFS, "static") mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServerFS(static))) // Browsers ask for /favicon.ico whatever the page says. mux.HandleFunc("GET /favicon.ico", func(w http.ResponseWriter, r *http.Request) { http.ServeFileFS(w, r, static, "favicon.ico") }) 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 /{$}", (*Server).dashboard) // Signing in (the server edition). mux.HandleFunc("GET /setup/{token}", (*Server).setupPage) mux.HandleFunc("POST /setup/{token}", (*Server).setupSave) mux.HandleFunc("POST /billing/stripe", (*Server).stripeWebhook) mux.HandleFunc("GET /settings/billing", (*Server).billingPage) mux.HandleFunc("POST /settings/billing/checkout", (*Server).billingCheckout) mux.HandleFunc("POST /settings/billing/portal", (*Server).billingPortal) mux.HandleFunc("POST /settings/billing/keep", (*Server).billingKeep) mux.HandleFunc("GET /settings/data", (*Server).dataPage) mux.HandleFunc("POST /settings/data/export", (*Server).dataExport) mux.HandleFunc("GET /settings/data/exports/{name}", (*Server).dataDownload) mux.HandleFunc("POST /settings/data/exports/{name}/delete", (*Server).dataExportDelete) mux.HandleFunc("POST /settings/data/delete-team", (*Server).teamDelete) mux.HandleFunc("POST /teams/undelete", (*Server).teamUndelete) mux.HandleFunc("GET /platform", (*Server).platformPage) mux.HandleFunc("POST /platform/stop-viewing", (*Server).platformStopViewing) mux.HandleFunc("POST /platform/teams/{id}/{action}", (*Server).platformAction) mux.HandleFunc("GET /signup", (*Server).signupPage) mux.HandleFunc("POST /signup", (*Server).signup) mux.HandleFunc("POST /teams/switch", (*Server).teamSwitch) mux.HandleFunc("GET /teams/new", (*Server).teamNewPage) mux.HandleFunc("POST /teams/new", (*Server).teamNew) mux.HandleFunc("POST /signin/core", (*Server).signinCore) mux.HandleFunc("GET /auth/core/callback", (*Server).coreCallbackPage) mux.HandleFunc("GET /settings/signin", (*Server).signinSettingsPage) mux.HandleFunc("POST /settings/signin/{action}", (*Server).signinSettingsAction) mux.HandleFunc("GET /signin", (*Server).signinPage) mux.HandleFunc("POST /signin", (*Server).signin) mux.HandleFunc("POST /signin/code", (*Server).signinCode) mux.HandleFunc("POST /signout", (*Server).signout) mux.HandleFunc("GET /forgot", (*Server).forgotPage) mux.HandleFunc("POST /forgot", (*Server).forgot) mux.HandleFunc("GET /reset/{token}", (*Server).resetPage) mux.HandleFunc("POST /reset/{token}", (*Server).reset) mux.HandleFunc("GET /settings/account", (*Server).accountPage) mux.HandleFunc("POST /settings/account/profile", (*Server).accountProfile) mux.HandleFunc("POST /settings/account/password", (*Server).accountPassword) mux.HandleFunc("POST /settings/account/sessions/end-others", (*Server).accountEndOthers) mux.HandleFunc("POST /settings/account/sessions/{id}/end", (*Server).accountEndSession) mux.HandleFunc("GET /settings/account/two-factor", (*Server).twoFactorPage) mux.HandleFunc("POST /settings/account/two-factor", (*Server).twoFactorOn) mux.HandleFunc("POST /settings/account/two-factor/off", (*Server).twoFactorOff) mux.HandleFunc("POST /settings/account/recovery-codes", (*Server).recoveryCodes) mux.HandleFunc("POST /settings/account/photo", (*Server).accountPhoto) mux.HandleFunc("GET /users/{id}/photo", (*Server).userPhoto) mux.HandleFunc("GET /settings/users", (*Server).usersPage) mux.HandleFunc("POST /settings/users", (*Server).userInvite) mux.HandleFunc("GET /settings/users/{id}", (*Server).userPage) mux.HandleFunc("POST /settings/users/{id}/{action}", (*Server).userAction) mux.HandleFunc("GET /invite/{token}", (*Server).invitePage) mux.HandleFunc("POST /invite/{token}", (*Server).inviteAccept) mux.HandleFunc("GET /search", (*Server).searchPage) mux.HandleFunc("GET /market", (*Server).inventoryList) mux.HandleFunc("GET /market/new", (*Server).inventoryEdit) mux.HandleFunc("GET /market/{id}", (*Server).inventoryEdit) mux.HandleFunc("POST /market/save", (*Server).inventorySave) mux.HandleFunc("POST /market/fill", (*Server).inventoryFill) mux.HandleFunc("POST /market/{id}/delete", (*Server).inventoryDelete) mux.HandleFunc("GET /market/import", (*Server).inventoryImportPage) mux.HandleFunc("POST /market/import", (*Server).inventoryImport) mux.HandleFunc("GET /market/export", (*Server).inventoryExport) // The Market was the Inventory: its old addresses lead to the new ones // (308 keeps a form's POST a POST). mux.HandleFunc("/inventory", marketMoved) mux.HandleFunc("/inventory/", marketMoved) // Settings: the profile, social accounts, AI, and the Core & Hermes. mux.HandleFunc("GET /settings", func(w http.ResponseWriter, r *http.Request) { if !viewerOf(r).Member.Admin() { http.Redirect(w, r, "/settings/account", http.StatusSeeOther) return } http.Redirect(w, r, "/settings/profile", http.StatusSeeOther) }) mux.HandleFunc("GET /settings/profile", (*Server).profilePage) mux.HandleFunc("POST /settings/profile", (*Server).profileSave) mux.HandleFunc("POST /settings/profile/draft", (*Server).profileDraft) mux.HandleFunc("GET /settings/ai", (*Server).aiPage) mux.HandleFunc("POST /settings/ai", (*Server).aiSave) mux.HandleFunc("POST /settings/ai/test", (*Server).aiTest) mux.HandleFunc("GET /settings/ai/models", (*Server).aiModels) mux.HandleFunc("GET /settings/accounts", (*Server).accountsPage) mux.HandleFunc("POST /settings/accounts", (*Server).accountsSave) mux.HandleFunc("POST /settings/accounts/linkedin-page", (*Server).linkedInPageSave) mux.HandleFunc("POST /auth/{provider}/start", (*Server).oauthStart) mux.HandleFunc("GET /auth/{provider}/callback", (*Server).oauthCallback) mux.HandleFunc("GET /content", (*Server).contentIndex) mux.HandleFunc("GET /content/{id}", (*Server).contentEntry) mux.HandleFunc("POST /content/{id}/fetch", (*Server).contentFetch) mux.HandleFunc("POST /content/{id}/items", (*Server).contentItems) mux.HandleFunc("GET /content/scheduled", (*Server).scheduledPage) mux.HandleFunc("GET /content/published", (*Server).publishedPage) mux.HandleFunc("GET /posts", (*Server).inboxPage) // Posts was called the Inbox, and before that Drafts. mux.HandleFunc("GET /inbox", func(w http.ResponseWriter, r *http.Request) { redirect(w, r, "/posts", r.URL.Query().Get("msg")) }) mux.HandleFunc("GET /drafts", func(w http.ResponseWriter, r *http.Request) { redirect(w, r, "/posts", r.URL.Query().Get("msg")) }) mux.HandleFunc("POST /drafts/{id}/{action}", (*Server).draftAction) mux.HandleFunc("POST /reddit/rules/{name}", (*Server).refreshRules) mux.HandleFunc("GET /prospects", (*Server).prospectsPage) mux.HandleFunc("GET /prospects/new", (*Server).prospectForm) mux.HandleFunc("POST /prospects/new", (*Server).prospectAdd) mux.HandleFunc("GET /prospects/suppressed", (*Server).suppressedPage) mux.HandleFunc("POST /prospects/suppressed", (*Server).suppressedAction) mux.HandleFunc("POST /prospects/verify", (*Server).prospectsVerify) mux.HandleFunc("POST /prospects/{kind}/{id}/{action}", (*Server).prospectAction) mux.HandleFunc("GET /signals", (*Server).signalsPage) mux.HandleFunc("GET /signals/new", (*Server).signalPage) mux.HandleFunc("POST /signals/new", (*Server).signalSave) mux.HandleFunc("POST /signals/campaigns", (*Server).signalCampaign) mux.HandleFunc("POST /lead-sources/{source}/import", (*Server).importSource) mux.HandleFunc("GET /signals/{id}", (*Server).signalPage) mux.HandleFunc("POST /signals/{id}", (*Server).signalSave) mux.HandleFunc("POST /signals/{id}/delete", (*Server).signalDelete) mux.HandleFunc("POST /signals/{id}/discover/{source}", (*Server).signalDiscover) mux.HandleFunc("GET /signals/{id}/runs", (*Server).signalRuns) mux.HandleFunc("POST /funnel/{id}/delete", (*Server).funnelDelete) mux.HandleFunc("GET /settings/sources", (*Server).sourcesPage) mux.HandleFunc("POST /settings/sources", (*Server).sourcesSave) mux.HandleFunc("POST /settings/sources/test/{source}", (*Server).sourcesTest) mux.HandleFunc("GET /settings/email", (*Server).emailPage) mux.HandleFunc("POST /settings/email", (*Server).emailSave) mux.HandleFunc("POST /settings/email/test", (*Server).emailTest) mux.HandleFunc("POST /settings/email/send-test", (*Server).emailSendTest) mux.HandleFunc("GET /metrics", (*Server).metricsPage) mux.HandleFunc("POST /metrics/sync", (*Server).metricsSync) mux.HandleFunc("POST /metrics/margins", (*Server).metricsMargins) mux.HandleFunc("POST /metrics/start", (*Server).metricsStart) mux.HandleFunc("GET /metrics/month/{month}", (*Server).metricsMonth) mux.HandleFunc("GET /metrics/customers", (*Server).metricsCustomers) mux.HandleFunc("GET /metrics/spend", (*Server).metricsSpend) mux.HandleFunc("GET /metrics/clv", (*Server).metricsCLV) mux.HandleFunc("GET /metrics/export/{name}", (*Server).metricsExport) mux.HandleFunc("GET /metrics/publish", (*Server).metricsPublishPage) mux.HandleFunc("POST /metrics/publish", (*Server).metricsPublish) mux.HandleFunc("POST /metrics/spend", (*Server).metricsSpendAdd) mux.HandleFunc("POST /metrics/spend/{id}/delete", (*Server).metricsSpendDelete) mux.HandleFunc("POST /metrics/customers/{id}", (*Server).metricsCustomerMatch) mux.HandleFunc("GET /sites", (*Server).sitesPage) mux.HandleFunc("POST /sites/sync", (*Server).sitesSync) mux.HandleFunc("GET /sites/pages", (*Server).sitePagesPage) mux.HandleFunc("POST /sites/pages", (*Server).sitePageNew) mux.HandleFunc("GET /sites/pages/{id}", (*Server).sitePagePage) mux.HandleFunc("POST /sites/pages/{id}/{action}", (*Server).sitePageAction) mux.HandleFunc("GET /sites/publishing", (*Server).sitesPublishingPage) mux.HandleFunc("POST /sites/theme/update", (*Server).sitesThemeUpdate) mux.HandleFunc("GET /sites/new", (*Server).newSitePage) mux.HandleFunc("POST /sites/new", (*Server).newSiteCreate) mux.HandleFunc("GET /sites/forms", (*Server).sitesFormsPage) mux.HandleFunc("POST /sites/forms/{action}", (*Server).sitesFormsAction) mux.HandleFunc("GET /sites/previews", (*Server).sitesPreviewsPage) mux.HandleFunc("POST /sites/previews/build", (*Server).sitesPreviewBuild) mux.HandleFunc("POST /sites/previews/delete", (*Server).sitesPreviewDelete) mux.HandleFunc("GET /preview/{site}/{slug}/{path...}", (*Server).previewServe) mux.HandleFunc("GET /preview/{site}/{slug}", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently) }) mux.HandleFunc("GET /seo", (*Server).seoPage) mux.HandleFunc("GET /seo/check", (*Server).seoCheckPage) mux.HandleFunc("GET /seo/engines", (*Server).seoEnginesPage) mux.HandleFunc("POST /seo/engines/setup", (*Server).seoEnginesSetup) mux.HandleFunc("POST /seo/engines/ping", (*Server).seoEnginesPing) mux.HandleFunc("GET /seo/briefs", (*Server).seoBriefsPage) mux.HandleFunc("POST /seo/briefs", (*Server).seoBriefNew) mux.HandleFunc("GET /seo/briefs/{id}", (*Server).seoBriefPage) mux.HandleFunc("POST /seo/briefs/{id}/{action}", (*Server).seoBriefAction) mux.HandleFunc("GET /seo/keywords", (*Server).seoKeywordsPage) mux.HandleFunc("POST /seo/keywords", (*Server).seoKeywordsFind) mux.HandleFunc("POST /seo/keywords/{id}/{action}", (*Server).seoKeywordAction) mux.HandleFunc("GET /seo/changes", (*Server).seoChangesPage) mux.HandleFunc("POST /seo/changes/suggest", (*Server).seoChangesSuggest) mux.HandleFunc("POST /seo/changes/page", (*Server).seoChangeForPage) mux.HandleFunc("POST /seo/changes/{id}/{action}", (*Server).seoChangeAction) mux.HandleFunc("POST /settings/search/test/gitea", (*Server).giteaTest) mux.HandleFunc("GET /seo/audit", (*Server).seoAuditPage) mux.HandleFunc("POST /seo/audit", (*Server).seoAuditRun) mux.HandleFunc("GET /seo/audit/status", (*Server).seoAuditStatus) mux.HandleFunc("GET /seo/report", (*Server).seoReportPage) mux.HandleFunc("GET /seo/next", (*Server).seoNextPage) mux.HandleFunc("POST /settings/email/listmonk", (*Server).listmonkSave) mux.HandleFunc("POST /settings/email/listmonk/test", (*Server).listmonkTest) mux.HandleFunc("POST /settings/email/listmonk/sync", (*Server).listmonkSync) mux.HandleFunc("GET /seo/links", (*Server).seoLinksPage) mux.HandleFunc("POST /seo/links/bing", (*Server).seoLinksBing) mux.HandleFunc("POST /seo/links/{action}", (*Server).seoLinksAction) mux.HandleFunc("GET /sites/pages/add", (*Server).sitesAddPage) mux.HandleFunc("POST /sites/pages/add", (*Server).sitesAdd) mux.HandleFunc("POST /seo/next/dismiss", (*Server).seoNextDismiss) mux.HandleFunc("POST /seo/report", (*Server).seoReportWrite) mux.HandleFunc("GET /settings/search", (*Server).searchSettingsPage) mux.HandleFunc("POST /settings/search", (*Server).searchSettingsSave) mux.HandleFunc("POST /settings/search/sync", (*Server).seoSync) mux.HandleFunc("GET /settings/tracking", (*Server).trackingPage) mux.HandleFunc("POST /settings/tracking", (*Server).trackingSave) mux.HandleFunc("POST /settings/tracking/test/{source}", (*Server).trackingTest) mux.HandleFunc("POST /settings/tracking/signups", (*Server).trackingSignups) mux.HandleFunc("POST /settings/tracking/run/{source}", (*Server).trackingRun) mux.HandleFunc("GET /outreach", (*Server).outreachPage) mux.HandleFunc("POST /outreach/draft", (*Server).outreachDraft) mux.HandleFunc("POST /outreach/draft-many", (*Server).outreachDraftMany) mux.HandleFunc("POST /outreach/check", (*Server).outreachCheck) mux.HandleFunc("POST /outreach/{id}/{action}", (*Server).outreachAction) mux.HandleFunc("GET /crm", (*Server).crmPage) mux.HandleFunc("GET /crm/reach", (*Server).crmReach) mux.HandleFunc("POST /crm/{action}", (*Server).crmAction) mux.HandleFunc("POST /crm/{id}/{action}", (*Server).crmAction) mux.HandleFunc("GET /settings/backups", (*Server).backupsPage) mux.HandleFunc("POST /settings/backups/{action}", (*Server).backupsAction) mux.HandleFunc("GET /settings/backups/file/{name}", (*Server).backupDownload) mux.HandleFunc("POST /settings/backups/upload", (*Server).backupUpload) mux.HandleFunc("GET /settings/about", (*Server).aboutPage) mux.HandleFunc("GET /settings/connections", (*Server).connectionsPage) mux.HandleFunc("GET /settings/domain", (*Server).domainPage) mux.HandleFunc("POST /settings/domain/check/{method}", (*Server).domainCheck) mux.HandleFunc("GET /settings/activity", (*Server).activityPage) mux.HandleFunc("GET /api/v1/docs", (*Server).apiDocs) mux.HandleFunc("GET /api/v1/tools", (*Server).apiTools) mux.HandleFunc("POST /api/v1/{tool}", (*Server).apiCall) mux.HandleFunc("GET /approvals", (*Server).approvalsPage) mux.HandleFunc("POST /approvals/allowed/withdraw", (*Server).approvalWithdraw) mux.HandleFunc("POST /approvals/{id}/{action}", (*Server).approvalAction) mux.HandleFunc("GET /settings/agents", (*Server).agentsPage) mux.HandleFunc("POST /settings/agents", (*Server).agentCreate) mux.HandleFunc("GET /settings/agents/{id}", (*Server).agentPage) mux.HandleFunc("POST /settings/agents/{id}/{action}", (*Server).agentAction) mux.HandleFunc("GET /settings/posting", (*Server).postingPage) mux.HandleFunc("POST /settings/posting", (*Server).postingSave) mux.HandleFunc("POST /settings/posting/{id}/remove", (*Server).postingRemove) mux.HandleFunc("POST /settings/account/posting/{id}/remove", (*Server).postingRemove) mux.HandleFunc("GET /settings/core", (*Server).corePage) mux.HandleFunc("POST /settings/core", (*Server).coreSave) mux.HandleFunc("GET /settings/core/checks", (*Server).coreChecks) // Where these pages used to be, for bookmarks. for old, now := range map[string]string{ "/profile": "/settings/profile", "/core": "/settings/core", "/settings/credentials": "/settings/accounts", } { mux.HandleFunc("GET "+old, func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, now, http.StatusMovedPermanently) }) } if err := mux.err(); err != nil { return nil, err } s.st().patterns = mux.patterns return s.guard(s.csrf(s.sessions(mux.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 https://www.reddit.com https://old.reddit.com https://accounts.google.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 } // humanBytes is a file size for people: "840 KB", "12.3 MB". func humanBytes(n int64) string { switch { case n >= 1<<30: return fmt.Sprintf("%.1f GB", float64(n)/(1<<30)) case n >= 1<<20: return fmt.Sprintf("%.1f MB", float64(n)/(1<<20)) case n >= 1<<10: return fmt.Sprintf("%d KB", n>>10) } return fmt.Sprintf("%d bytes", n) } var backticks = regexp.MustCompile("`([^`]+)`") // ticks shows Markdown's `code` spans as code, the rest as plain text. func ticks(s string) template.HTML { return template.HTML(backticks.ReplaceAllString(template.HTMLEscapeString(s), "$1")) } func (s *Server) loadTemplates() error { funcs := template.FuncMap{ "lines": func(v []string) string { return strings.Join(v, "\n") }, "join": strings.Join, "ago": ago, "ticks": ticks, "bytes": humanBytes, "kindLabel": sites.KindLabel, "add": func(a, b int) int { return a + b }, "hasPrefix": strings.HasPrefix, "sourceLabel": prospects.SourceLabel, "has": func(list []string, v string) bool { for _, x := range list { if x == v { return true } } return false }, // dict builds a map from key, value pairs, to pass several values // to a template. "dict": func(kv ...any) (map[string]any, error) { if len(kv)%2 != 0 { return nil, fmt.Errorf("dict: odd number of arguments") } m := make(map[string]any, len(kv)/2) for i := 0; i < len(kv); i += 2 { k, ok := kv[i].(string) if !ok { return nil, fmt.Errorf("dict: key %v isn't a string", kv[i]) } m[k] = kv[i+1] } return m, nil }, "xreserve": twitter.URLReserve, // money shows cents as dollars: $1,234 or $12.50. "money": money, "int64": func(n int) int64 { return int64(n) }, // usd shows float cents as whole dollars: $9,835. "usd": func(cents float64) string { return money(int64(math.Round(cents/100)) * 100) }, "mul12": func(f float64) float64 { return 12 * f }, "sub": func(a, b float64) float64 { return a - b }, "pct": func(f float64) string { if f < 0 { return "·" } return strconv.FormatFloat(f, 'f', 0, 64) + "%" }, "spendChannel": metrics.ChannelName, "dec1f": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) }, "actionLabel": actionLabel, // by is "by Jane" for something a person made; "" if unknown. "by": func(id int64) string { if id == 0 { return "" } if u, err := users.ByID(s.DB, id); err == nil { return "by " + displayName(u) } return "by someone since removed" }, "cents": func(f float64) string { if f < 0 { return "·" } return money(int64(math.Round(f))) }, "num": seo.Thousands, "cls": func(x100 int) float64 { return float64(x100) / 100 }, "dec1": func(f float64) string { return strconv.FormatFloat(f, 'f', 1, 64) }, "pagePath": pagePath, "change": seo.Percent, "inc": func(i int) int { return i + 1 }, // statusesFor are the moves an opportunity can make next. "statusesFor": func(status string) []string { switch status { case "open": return []string{"asked", "dismissed"} case "asked": return []string{"won", "dismissed"} case "dismissed", "won": return []string{"open"} } return nil }, "flagOf": func(m map[string]string, page string) string { return m[seo.PathKey(page)] }, "conv": func(m map[string]tracking.PageNumbers, page string) tracking.PageNumbers { return m[tracking.PathOf(page)] }, "stage": signals.StageLabel, "channel": signals.ChannelLabel, "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.st().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.st().pages[base] = t } return nil } // page is what every template gets. type page struct { Title string Nav string // which menu item is current: "home", "content/posts", "settings/ai"… Version string Flash string Error string Data any Inbox int // drafts waiting for review, shown in the menu Query string // the search box's text NewProspects int // companies and people waiting for review, shown in the menu Drafts int // outreach drafts waiting, shown in the menu Bare bool // no sidebar: pages before signing in CSRF string // the form token, for htmx (app.js) Approvals int // agents' requests waiting for this viewer Teams []users.TeamInfo // the viewer\'s teams (multi-tenant), for the switcher TeamID int64 // the team they\'re working in Multi bool // the multi-tenant edition Billing bool // teams are billed (multi-tenant) Lapse string // the team\'s payment is overdue: what the banner says Viewer *viewer // who's looking } // Section is the top bar's first breadcrumb, from Nav. func (p page) Section() string { switch { case p.Nav == "home": return "" case strings.HasPrefix(p.Nav, "content"): return "Content" case strings.HasPrefix(p.Nav, "prospects"): return "Prospects" case strings.HasPrefix(p.Nav, "settings"): return "Settings" case p.Nav == "inventory": return "Market" case strings.HasPrefix(p.Nav, "sites"): return "Sites" } return "" } // Modules are the app's modules, in the menu and on the Overview. One // without a Link isn't built yet. type module struct { ID, Name, Phase, Body, Link string } var modules = []module{ {"content", "Content", "Phase 1", "Draft posts from partner and competitor news and your own products; review and publish to X, LinkedIn and Reddit.", "/posts"}, {"prospects", "Prospects", "Phase 2", "Test buying signals through the whole funnel, from finding prospects to payment; add the people you approve to EspoCRM through Hermes.", "/signals"}, {"seo", "SEO", "Phase 3", "Run the weekly SEO loop from Search Console: what ranks, what moved, and the changes waiting for your yes, opened as pull requests on your Hugo repositories.", "/seo/check"}, {"sites", "Sites", "Phase 5", "Build pages from your website's own sections, preview them, and publish them as pull requests on Gitea.", "/sites"}, {"metrics", "Metrics", "Phase 4", "MRR, NRR, CAC and CLV from Stripe, with pipeline influence from EspoCRM.", "/metrics"}, } // Modules is for the menu: the viewer's. func (p page) Modules() []module { return visibleModules(p.Viewer) } // visibleModules are the modules a viewer may see. func visibleModules(v *viewer) []module { if v == nil { return modules } out := make([]module, 0, len(modules)) for _, m := range modules { if v.can(m.ID, false) { out = append(out, m) } } return out } // Can is for templates: whether the viewer may see an area. func (p page) Can(area string) bool { return p.Viewer == nil || p.Viewer.can(area, false) } // 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.st().pages[name] if !ok { http.Error(w, "no template "+name, http.StatusInternalServerError) return } p.Version = s.Version if !p.Bare { p.Inbox = s.inboxCount() p.NewProspects = s.newProspects() p.Drafts = s.outreachDrafts() } if p.Flash == "" { p.Flash = flashText(r.URL.Query()) } p.Error = sentence(p.Error) p.CSRF = csrfToken(r) p.Viewer = viewerOf(r) if !p.Bare { p.Approvals = s.waitingFor(p.Viewer) p.Teams, p.TeamID = s.teamsOf(p.Viewer), s.team() p.Lapse = s.lapseBanner() } p.Multi, p.Billing = s.multi(), s.billingOn() out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, "layout.html", p) }) if err != nil { s.Log.Error("render", "page", name, "err", err) http.Error(w, "The page couldn't be shown: "+err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write(out) } // fragment writes one named template (for htmx swaps). func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name string, data any) { t, ok := s.st().pages[page] if !ok { http.Error(w, "no template "+page, http.StatusInternalServerError) return } out, err := withCSRF(r, func(b *bytes.Buffer) error { return t.ExecuteTemplate(b, name, data) }) if err != nil { s.Log.Error("render fragment", "page", page, "name", name, "err", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write(out) } // Messages shown after a redirect, by code, so no user text is reflected. var flashes = map[string]string{ "saved": "Saved.", "welcome": "Welcome: you're the owner. Start with the company's profile.", "signed-out": "Signed out.", "password-reset": "Your new password is saved: sign in with it.", "password-changed": "Password changed. You're signed out everywhere else.", "session-ended": "Signed out there.", "sessions-ended": "Signed out everywhere else.", "two-factor-off": "Two-factor sign-in is off.", "codes-low": "You're running out of recovery codes: make new ones below.", "invited": "Invitation sent.", "withdrawn": "Invitation withdrawn.", "disabled": "The account is turned off, and signed out.", "enabled": "The account is back on.", "unlocked": "Unlocked.", "two-factor-reset": "Two-factor sign-in is reset: they sign in with their password, then can turn it on again.", "signed-out-user": "Signed out everywhere.", "removed": "Removed.", "joined": "Welcome to Supermarket.", "key-revoked": "Revoked: that key no longer works.", "agent-off": "Turned off: none of its keys work.", "refused": "Refused: the agent is told.", "approved-request": "Approved, and done.", "withdrawn-class": "Withdrawn: it asks again from now on.", "agent-paused": "Paused: every call it makes is refused until you resume it.", "agent-resumed": "Resumed.", "team-created": "Your team is set up. Start with the company's profile.", "added": "Added: they're told by email, and sign in as they do.", "prove-first": "First prove the team's domain is yours: Supermarket only crawls, reads or publishes to a website its team has proved.", "domain-proved": "Proved: the domain is the team's.", "team-suspended": "Suspended: its people see that it is, and its work waits.", "team-restored": "Restored.", "exported": "Exported: %d rows. Download it below.", "undeleted": "The team won't be deleted: it's back as it was.", "secret-made": "The client's secret is made: add the entry below to the Core, then Test.", "subscribed": "Thank you: the subscription starts as soon as Stripe confirms it, in a minute.", "domain-released": "Released: another team can prove the domain now.", "invitations-resent": "Sent %d invitations again.", "view-needs-reason": "Give a reason and how long: it's recorded in the team's own log.", "account-removed": "Signed out: posts scheduled to it are back in Posts.", "own-account-connected": "Connected: you can post as it, and an admin can let others.", "deleted": "Deleted.", "x-connected": "X is connected.", "li-connected": "LinkedIn is connected.", "site-created": "The site is started: its first commit is on Gitea. Build its first pages below.", "li-page-connected": "The LinkedIn page app is connected.", "google-connected": "Search Console is connected. Choose each website's property below, then sync.", "synced": "Synced from Search Console.", "report-written": "This week's report is written.", "setup-opened": "Pull request opened: read it on Gitea, then merge it.", "pinged": "Sent to IndexNow.", "brief-written": "Brief written. Read it, answer its questions, then write the page.", "page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.", "keywords-found": "Looked for keywords: the candidates are below.", "top-read": "Read the live top results.", "proposed": "Proposed: read each one, edit it if you like, then say yes or no.", "approved": "Approved: Supermarket is making the pull request; it shows here in a minute.", "declined": "Declined.", "keyword-picked": "Picked. Write its brief when you're ready.", "keyword-dismissed": "Dismissed: it's under Dismissed if you change your mind.", "keyword-back": "Back among the candidates.", "signups-saved": "Saved. The pages' sign-ups were read again with it.", "next-dismissed": "Hidden for 90 days.", "link-added": "Added, and checked.", "links-checked": "Checked %d links.", "link-forgotten": "Forgotten.", "partners-read": "Looked at the partners' pages: %d new places to ask for a link.", "alternatives-read": "Searched: %d new lists that leave you out.", "optouts-synced": "Synced: %d new on the suppression list.", "listed": "Added to the mailing list.", "bing-read": "Read the links from Bing.", "audited": "The audit is done.", "auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.", "no-data": "There isn't two weeks of Search Console data yet.", "reddit-connected": "Reddit is connected.", "crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).", "crm-sync": "Sync requested: Hermes copies CRM records on its next run.", "accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.", "rejected": "Set aside.", "reconsidered": "Back in New.", "suppressed": "Added to the suppression list.", "unsuppressed": "Taken off the suppression list.", "prospect-added": "Added. Review it below.", "crm-retried": "Queued again: Hermes tries it on its next run.", "crm-cancelled": "Taken back: Hermes won't do it.", "prospect-exists": "Already there: nothing new was added. It's in the list below.", "outcome": "Outcome recorded.", "discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.", "rules-refreshed": "Rules refreshed.", "imported": "Imported.", "imported-counts": "Imported: %d new steps in the funnel, %d new people to review, %d new on the suppression list.", "hunter-done": "Hunter.io search done: the result is on the card.", "verified": "Checked with Hunter.io: the result is on each person.", "drafted-outreach": "Drafted. Read it, edit it, then queue it to send.", "queued": "Queued: it goes out in turn, within your sending hours.", "unqueued": "Back in Drafts.", "sent": "Sent.", "marked-sent": "Marked as sent.", "reply-recorded": "Reply recorded.", "checked": "Inbox checked: what it found is above.", "test-sent": "Test email sent: check your inbox.", "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.", "scheduled": "Scheduled.", "posted": "Marked as posted: it's under Content → Published.", "unscheduled": "Back in Posts: edit it, then publish or schedule it again.", } // sentence starts a message with a capital letter: errors from deeper // down are written in lower case, to be wrapped. func sentence(msg string) string { r, n := utf8.DecodeRuneInString(msg) if n == 0 || !unicode.IsLower(r) { return msg } return string(unicode.ToUpper(r)) + msg[n:] } // flashText is the message a redirect asked for (?msg=), from the fixed // list. A message with %d verbs takes its numbers from n1, n2… (digits // only), so nothing but a number can be put into it from the address. func flashText(q url.Values) string { msg := flashes[q.Get("msg")] if n := strings.Count(msg, "%d"); n > 0 { args := make([]any, n) for i := range args { v, _ := strconv.Atoi(q.Get("n" + strconv.Itoa(i+1))) args[i] = v } msg = fmt.Sprintf(msg, args...) } return msg } // redirectCounts redirects with a message that has numbers in it. func redirectCounts(w http.ResponseWriter, r *http.Request, path, msg string, counts ...int) { base, frag, hasFrag := strings.Cut(path, "#") for i, c := range counts { sep := "?" if strings.Contains(base, "?") { sep = "&" } base += sep + "n" + strconv.Itoa(i+1) + "=" + strconv.Itoa(c) } if hasFrag { base += "#" + frag } redirect(w, r, base, msg) } func redirect(w http.ResponseWriter, r *http.Request, path, msg string) { if msg != "" { // The message goes in the query, before any #fragment. base, frag, hasFrag := strings.Cut(path, "#") sep := "?" if strings.Contains(base, "?") { sep = "&" } path = base + sep + "msg=" + url.QueryEscape(msg) if hasFrag { path += "#" + frag } } 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 money(cents int64) string { neg := cents < 0 if neg { cents = -cents } whole := strconv.FormatInt(cents/100, 10) for i := len(whole) - 3; i > 0; i -= 3 { whole = whole[:i] + "," + whole[i:] } out := "$" + whole if c := cents % 100; c != 0 { out += fmt.Sprintf(".%02d", c) } if neg { out = "-" + out } return out } 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") } } // marketMoved sends an old /inventory address to its /market one. func marketMoved(w http.ResponseWriter, r *http.Request) { u := *r.URL u.Path = "/market" + strings.TrimPrefix(r.URL.Path, "/inventory") http.Redirect(w, r, u.RequestURI(), http.StatusPermanentRedirect) }