Files
supermarket/cmd/supermarket/main.go
T
davidandClaude Opus 5.5 da16736fb4 Phase 10, part 9: the server package
compose.server.yaml runs Supermarket behind Caddy (HTTPS from Let's
Encrypt, Caddy's own CA or the team's), with Postgres on an internal
network and a nightly pg_dump kept two weeks. install-server.sh asks for
the domain, certificate and mail server, makes the secret key and database
password, starts it all and prints the setup link. Settings → Backups lists
the dumps on a server, and how the operator restores one. Checked end to
end in Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:37:34 -07:00

706 lines
21 KiB
Go

// Supermarket serves the marketing suite's web app. It's meant to run in
// its Docker container (see compose.yaml), with its data folder at /data.
//
// Environment (see internal/config):
//
// SUPERMARKET_MODE the edition: local (default), server or multi
// SUPERMARKET_DATA data folder (default /data)
// SUPERMARKET_ADDR listen address (default :8080)
// SUPERMARKET_PUBLIC_URL the address the browser uses (default http://localhost:8470)
// SUPERMARKET_CORE_CONF CoreDesktop's core.conf (default <data>/core.conf)
// SUPERMARKET_MCP_SOCKET Unix socket for agents' MCP (default <data>/mcp.sock)
// SUPERMARKET_HOST_DATA the data folder's path on the host, to show in
// setup instructions (default: same as the data folder)
//
// The server and multi-tenant editions also need SUPERMARKET_DATABASE_URL,
// SUPERMARKET_SECRET_KEY and SUPERMARKET_MAIL_URL, and multi-tenant needs
// SUPERMARKET_STORAGE (s3://…) with SUPERMARKET_S3_*. `supermarket config`
// checks them; `supermarket secret-key` makes a key.
package main
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"supermarket/internal/ai"
"supermarket/internal/appmail"
"supermarket/internal/backup"
"supermarket/internal/config"
"supermarket/internal/content"
"supermarket/internal/core"
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/fileutil"
"supermarket/internal/jobs"
"supermarket/internal/legacy"
"supermarket/internal/mcpserver"
"supermarket/internal/secrets"
"supermarket/internal/storage"
"supermarket/internal/transfer"
"supermarket/internal/users"
"supermarket/internal/web"
)
// version is set at build time (-ldflags "-X main.version=...").
var version = "dev"
func main() {
if len(os.Args) > 1 && (os.Args[1] == "version" || os.Args[1] == "--version") {
fmt.Println(version)
return
}
if len(os.Args) > 1 && os.Args[1] == "secret-key" {
k, err := config.NewKey()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(k)
return
}
if len(os.Args) > 1 && os.Args[1] == "config" {
os.Exit(configCommand())
}
if len(os.Args) > 1 && os.Args[1] == "setup-link" {
if err := setupLinkCommand(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if len(os.Args) > 1 && (os.Args[1] == "export" || os.Args[1] == "import") {
if err := transferCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups" || os.Args[1] == "restore") {
if err := backupCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
if err := run(log); err != nil {
log.Error("stopped", "err", err)
os.Exit(1)
}
}
func env(key, def string) string {
if v := strings.TrimSpace(os.Getenv(key)); v != "" {
return v
}
return def
}
// configCommand prints the settings, without passwords or keys, and any
// problems with them. It exits 1 if there are some.
func configCommand() int {
cfg, err := config.Load(os.Getenv)
for _, it := range cfg.Summary() {
fmt.Printf("%-9s %s\n", it.Name+":", it.Value)
}
if err == nil {
fmt.Println()
err = liveChecks(cfg)
}
if err == nil {
err = cfg.Ready()
}
if err != nil {
fmt.Println()
fmt.Println("Problems:")
for _, line := range strings.Split(err.Error(), "\n") {
fmt.Println(" - " + line)
}
return 1
}
fmt.Println("\nThe settings are fine.")
return 0
}
// liveChecks reaches what the settings name: Postgres, and file storage
// (writing, reading and deleting a small file).
func liveChecks(cfg *config.Config) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
var problems []string
if cfg.DatabaseURL != "" {
fmt.Print("Checking the database… ")
d, err := sql.Open("pgx", cfg.DatabaseURL)
if err == nil {
err = d.PingContext(ctx)
d.Close()
}
if err != nil {
fmt.Println("no")
problems = append(problems, "Postgres can't be reached: "+err.Error())
} else {
fmt.Println("reachable")
}
}
fmt.Print("Checking the file storage… ")
st, err := storage.Open(cfg.Storage)
if err == nil {
err = storage.Check(ctx, st)
}
if err != nil {
fmt.Println("no")
problems = append(problems, "The file storage doesn't work: "+err.Error())
} else {
fmt.Println("writable")
}
if len(problems) > 0 {
return errors.New(strings.Join(problems, "\n"))
}
return nil
}
func run(log *slog.Logger) error {
cfg, err := config.Load(os.Getenv)
if err != nil {
for _, problem := range strings.Split(err.Error(), "\n") {
log.Error("settings: " + problem)
}
return errors.New("the settings need fixing: supermarket config shows them")
}
if err := cfg.Ready(); err != nil {
return err
}
dataDir, addr, publicURL := cfg.DataDir, cfg.Addr, cfg.PublicURL
coreConf, mcpSocket, hostData := cfg.CoreConf, cfg.MCPSocket, cfg.HostData
// Everything the app writes (database, secrets, clones) is for this user
// only: it will hold contacts and credentials.
syscall.Umask(0o077)
if err := os.MkdirAll(dataDir, 0700); err != nil {
return err
}
// A restore staged before the restart is swapped in before the
// database opens.
if r, err := backup.ApplyPending(dataDir, time.Now()); err != nil {
log.Error("backups: the restore wasn't applied", "err", err)
} else if r != nil {
log.Info("backups: restored", "from", r.From, "secrets", r.Secrets, "previous database", r.Backup)
}
// Old hand-made copies (app.db.pre-*) join the backups.
if n := backup.AdoptLegacy(dataDir, func(name string, err error) {
log.Warn("backups: an old copy was left where it is", "file", name, "err", err)
}); n > 0 {
log.Info("backups: moved old copies into the backups folder", "count", n)
}
if n := backup.RemoveOrphans(backup.Dir(dataDir)); n > 0 {
log.Info("backups: removed -wal and -shm files of deleted backups", "count", n)
}
db.BeforeMigrate = func(d *sql.DB, from, to int) error {
b, err := backup.Make(d, backup.Dir(dataDir), backup.Migration, fmt.Sprintf("before-schema-%d", to), time.Now())
if err == nil {
log.Info("backups: backed up before migrating", "from", from, "to", to, "file", b.Name)
}
return err
}
db.AppVersion = version
var database *db.DB
if cfg.DatabaseURL != "" {
database, err = db.OpenPostgres(cfg.DatabaseURL)
} else {
database, err = db.Open(filepath.Join(dataDir, "app.db"))
}
if err != nil {
return err
}
defer database.Close()
if database.MigratedFrom > 0 {
log.Info("database: migrated", "database", database.Dialect, "from", database.MigratedFrom, "to", db.Schema())
}
// This copy of the app, for the locks it shares with any others.
runner, err := jobs.New(database, version, log)
if err != nil {
return err
}
defer runner.Stop() // before the database closes
alone, err := runner.Alone()
if err != nil {
return err
}
if !alone {
log.Info("jobs: other copies of Supermarket are running; work they have under way is left to them")
} else if n, err := content.RecoverInterrupted(database); err != nil {
return err
} else if n > 0 {
log.Warn("drafts were being published when Supermarket stopped; marked failed for review", "count", n)
}
// Hermes' Anthropic key and model, if the user chose to share them
ai.SharedFile = filepath.Join(dataDir, "hermes-ai.json")
// What Hermes' CRM job checks before it runs; see internal/crm.
local := cfg.Edition == config.Local
if local {
crm.StateFile = filepath.Join(dataDir, "crm-state")
if err := crm.WriteState(database, time.Now()); err != nil {
log.Error("writing the CRM state file", "err", err)
}
}
// The local edition keeps its keys and tokens in a file beside the
// database; the others, in the database, encrypted.
var sec *secrets.Store
if cfg.Edition == config.Local {
sec, err = secrets.Open(filepath.Join(dataDir, "secrets.json"))
} else {
sec, err = secrets.OpenDB(database, cfg.SecretKey, cfg.OldKey)
if err == nil && cfg.OldKey != nil {
log.Warn("secrets: encrypted with the new key; unset " + config.EnvOldKey)
}
}
if err != nil {
return err
}
// Files that must outlast this copy of the app: a folder, or S3,
// checked now so a wrong key is found at the start.
files, err := storage.Open(cfg.Storage)
if err != nil {
return err
}
if cfg.Storage.S3() {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
err = storage.Check(ctx, files)
cancel()
if err != nil {
return err
}
}
token, err := mcpToken(filepath.Join(dataDir, "mcp-token"))
if err != nil {
return err
}
c, err := core.Load(coreConf)
if err != nil {
log.Warn("couldn't read the Core's settings", "file", coreConf, "err", err)
}
// The import never stops the app: a bad old file is reported on the
// overview page instead.
status, importErr := legacy.Import(database, sec, filepath.Join(dataDir, "import"))
if importErr != nil {
log.Error("importing the old app's data", "err", importErr)
} else if status != nil {
log.Info("imported the old app's data", "summary", strings.Join(status.Summary, "; "))
}
if status == nil && importErr == nil {
status, _ = legacy.LoadStatus(database)
}
srv := &web.Server{
Config: cfg,
DB: database,
Secrets: sec,
Core: c,
DataDir: dataDir,
Files: files,
Jobs: runner,
PublicURL: publicURL,
Version: version,
MCPToken: token,
MCPSocket: filepath.Join(hostData, filepath.Base(mcpSocket)),
MCP: mcpserver.Handler(database, token, version),
Mail: appMail(cfg),
Log: log,
ImportStatus: status,
ImportErr: importErr,
}
handler, err := srv.Handler()
if err != nil {
return err
}
// A new server has no owner yet: a link to create one.
if cfg.Edition != config.Local {
if link, err := setupLink(database, publicURL); err != nil {
return err
} else if link != "" {
log.Warn("Supermarket isn't set up yet. To create its owner, open this link (it works once, for a day): " + link)
}
}
httpServer := &http.Server{
Addr: addr,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// A restore from the browser stops the app; Docker starts it again
// (restart: unless-stopped), and the restore is applied on the way up.
srv.Restart = stop
errCh := make(chan error, 2)
// Hermes on this computer reaches the app through a socket in the data
// folder; on a server, agents use /mcp (Phase 11).
if local {
go func() {
if err := mcpserver.ServeSocket(ctx, database, version, mcpSocket, log); err != nil {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
}
go runner.CheckIns(ctx)
go srv.RunScheduler(ctx)
go srv.RunImports(ctx)
go srv.RunDiscovery(ctx)
go srv.RunOutreach(ctx)
go srv.RunTracking(ctx)
go srv.RunSEO(ctx)
go srv.RunMetrics(ctx)
go srv.RunBackups(ctx)
go srv.RunAccounts(ctx)
// A sync falls due, and a claim times out, without anything being
// written: refresh the state file each minute.
go func() {
if !local {
return
}
t := time.NewTicker(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
if err := crm.WriteState(database, now); err != nil {
log.Error("writing the CRM state file", "err", err)
}
}
}
}()
go func() {
log.Info("Supermarket is running", "version", version, "edition", cfg.Edition, "listen", addr, "open", publicURL)
errCh <- httpServer.ListenAndServe()
}()
select {
case err := <-errCh:
if !errors.Is(err, http.ErrServerClosed) {
return err
}
case <-ctx.Done():
log.Info("shutting down")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(shutdownCtx); err != nil {
return err
}
}
return nil
}
// appMail sends the app's own mail, where there's a mail server.
func appMail(cfg *config.Config) appmail.Sender {
if cfg.Mail == nil {
return nil
}
return &appmail.SMTP{Conf: cfg.Mail}
}
// setupLink makes a new one-time link to create the owner, or returns ""
// if there's an owner already.
func setupLink(d *db.DB, publicURL string) (string, error) {
done, err := users.HasOwner(d, users.Team)
if err != nil || done {
return "", err
}
token, err := users.NewLink(d, users.SetupLink, 0, time.Now())
if err != nil {
return "", err
}
return publicURL + "/setup/" + token, nil
}
// setupLinkCommand runs `supermarket setup-link`: a new link to create the
// owner, replacing the one in the start-up log.
func setupLinkCommand() error {
cfg, err := config.Load(os.Getenv)
if err != nil {
return fmt.Errorf("the settings need fixing (supermarket config shows them):\n%w", err)
}
if cfg.Edition == config.Local {
return errors.New("the local edition has no sign-in, so nothing to set up: open " + cfg.PublicURL)
}
d, _, err := openForCommand(cfg)
if err != nil {
return err
}
defer d.Close()
link, err := setupLink(d, cfg.PublicURL)
if err != nil {
return err
}
if link == "" {
return errors.New("Supermarket is set up already: its owner signs in, and invites the others (Settings → Users)")
}
fmt.Println("Open this link to create Supermarket's owner. It works once, for a day, and replaces any earlier link:")
fmt.Println(link)
return nil
}
// mcpToken reads the bearer token agents use for /mcp, creating it if there
// is none. install.sh may create it first, to give it to Hermes.
func mcpToken(path string) (string, error) {
raw, err := os.ReadFile(path)
if err == nil {
if t := strings.TrimSpace(string(raw)); len(t) >= 32 {
return t, nil
}
} else if !errors.Is(err, os.ErrNotExist) {
return "", err
}
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
t := hex.EncodeToString(b)
if err := fileutil.WriteFileAtomic(path, []byte(t+"\n"), 0600); err != nil {
return "", err
}
return t, nil
}
// backupCommand runs `supermarket backup [note]` and `supermarket backups`
// (inside the container: the host's command runs them with docker exec).
// It reads the database beside the running app, which WAL allows; it
// never migrates it.
func backupCommand(cmd string, args []string) error {
dataDir := env("SUPERMARKET_DATA", "/data")
dir := backup.Dir(dataDir)
if cmd == "backups" {
bs, err := backup.List(dir)
if err != nil {
return err
}
if len(bs) == 0 {
fmt.Println("No backups yet.")
return nil
}
for _, b := range bs {
schema := fmt.Sprintf("schema %d", b.Schema)
if b.Schema < 0 {
schema = "unreadable"
}
fmt.Printf("%-60s %8.1f MB %s\n", b.Name, float64(b.Size)/(1<<20), schema)
}
return nil
}
path := filepath.Join(dataDir, "app.db")
if _, err := os.Stat(path); err != nil {
return fmt.Errorf("no database at %s", path)
}
d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(10000)")
if err != nil {
return err
}
defer d.Close()
if cmd == "restore" {
if len(args) != 1 {
return errors.New("usage: supermarket restore <backup name or file>")
}
src := args[0]
if !filepath.IsAbs(src) {
src = filepath.Join(dir, src)
}
r, err := backup.Stage(d, dataDir, src, db.Schema(), time.Now())
if err != nil {
return err
}
fmt.Printf("Ready to restore %s; the current database is backed up as %s.\n", r.From, r.Backup)
if r.Secrets {
fmt.Println("Its secrets.json (keys and tokens) will replace this one; the current one is kept in the backups folder.")
}
fmt.Println("It's applied when Supermarket restarts.")
return nil
}
if len(args) > 0 && args[0] == "--with-secrets" {
p, err := backup.Archive(d, dataDir, time.Now())
if err != nil {
return err
}
fmt.Printf("Backed up, with secrets, to backups/%s\n", filepath.Base(p))
fmt.Println("It holds your keys and tokens: keep it as safe as they are, and delete it once you've moved.")
return nil
}
b, err := backup.Make(d, dir, backup.Manual, strings.Join(args, " "), time.Now())
if err != nil {
return err
}
fmt.Printf("Backed up to %s (%.1f MB)\n", b.Name, float64(b.Size)/(1<<20))
return nil
}
// openForCommand opens the edition's database and secrets, for commands
// run beside the app (export, import).
func openForCommand(cfg *config.Config) (*db.DB, *secrets.Store, error) {
if cfg.Edition == config.Local {
d, err := db.OpenSQLite(filepath.Join(cfg.DataDir, "app.db"))
if err != nil {
return nil, nil, err
}
sec, err := secrets.Open(filepath.Join(cfg.DataDir, "secrets.json"))
if err != nil {
d.Close()
return nil, nil, err
}
return d, sec, nil
}
db.AppVersion = version
d, err := db.OpenPostgres(cfg.DatabaseURL)
if err != nil {
return nil, nil, err
}
sec, err := secrets.OpenDB(d, cfg.SecretKey, cfg.OldKey)
if err != nil {
d.Close()
return nil, nil, err
}
return d, sec, nil
}
// hostPath is where a stored file is on the host, for the local edition's
// folder; else its name in the store.
func hostPath(cfg *config.Config, key string) string {
if !cfg.Storage.S3() && cfg.Storage.Dir == filepath.Join(cfg.DataDir, "files") {
return filepath.Join(cfg.HostData, "files", filepath.FromSlash(key))
}
if !cfg.Storage.S3() {
return filepath.Join(cfg.Storage.Dir, filepath.FromSlash(key))
}
return cfg.Storage.String() + "/" + key
}
// transferCommand runs `supermarket export [--with-secrets]` and
// `supermarket import <file>`.
func transferCommand(cmd string, args []string) error {
cfg, err := config.Load(os.Getenv)
if err != nil {
return fmt.Errorf("the settings need fixing (supermarket config shows them):\n%w", err)
}
files, err := storage.Open(cfg.Storage)
if err != nil {
return err
}
d, sec, err := openForCommand(cfg)
if err != nil {
return err
}
defer d.Close()
ctx := context.Background()
if cmd == "export" {
withSecrets := len(args) > 0 && args[0] == "--with-secrets"
if len(args) > 1 || (len(args) == 1 && !withSecrets) {
return errors.New("usage: supermarket export [--with-secrets]")
}
tmp, err := os.CreateTemp("", "export-*.tar.gz")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
defer tmp.Close()
var from *secrets.Store
if withSecrets {
from = sec
}
m, err := transfer.Export(ctx, d, from, version, tmp)
if err != nil {
return err
}
size, _ := tmp.Seek(0, io.SeekCurrent)
tmp.Seek(0, io.SeekStart)
key := "exports/supermarket-" + time.Now().Format("20060102-150405")
if withSecrets {
key += "-with-secrets"
}
key += ".tar.gz"
if err := files.Put(ctx, key, tmp, size); err != nil {
return err
}
rows := 0
for _, n := range m.Tables {
rows += n
}
fmt.Printf("Exported %d rows from %d tables (schema %d) to %s (%.1f MB)\n", rows, len(m.Tables), m.Schema, hostPath(cfg, key), float64(size)/(1<<20))
if withSecrets {
fmt.Printf("It holds %d keys and tokens: keep it as safe as they are, and delete it once you've moved.\n", m.Secrets)
} else {
fmt.Println("Keys and tokens aren't in it: add --with-secrets to take them too, or enter them again after the move.")
}
return nil
}
if len(args) != 1 {
return errors.New("usage: supermarket import <export file, or its name from supermarket export>")
}
open, where, err := exportOpener(ctx, cfg, files, args[0])
if err != nil {
return err
}
res, err := transfer.Import(ctx, d, sec, open)
if err != nil {
return err
}
rows := 0
for _, n := range res.Tables {
rows += n
}
fmt.Printf("Imported %d rows into %d tables, and %d keys and tokens, from %s (made %s on %s, schema %d).\n",
rows, len(res.Tables), res.Secrets, where, res.Manifest.Created.Local().Format("2 Jan 2006 15:04"), res.Manifest.From, res.Manifest.Schema)
if cfg.Edition == config.Local {
fmt.Println("Restart Supermarket to see it: supermarket restart")
}
return nil
}
// exportOpener finds an export: a file, or a name in the file storage
// (as supermarket export printed it, or under exports/ or imports/).
func exportOpener(ctx context.Context, cfg *config.Config, files storage.Store, arg string) (func() (io.ReadCloser, error), string, error) {
// A path on the host, in the data folder, is /data inside the container.
p := arg
if rel, err := filepath.Rel(cfg.HostData, arg); err == nil && filepath.IsAbs(arg) && !strings.HasPrefix(rel, "..") {
p = filepath.Join(cfg.DataDir, rel)
}
if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
return func() (io.ReadCloser, error) { return os.Open(p) }, arg, nil
}
name := filepath.ToSlash(arg)
if i := strings.Index(name, "/files/"); i >= 0 { // as export printed it
name = name[i+len("/files/"):]
}
for _, key := range []string{name, "exports/" + name, "imports/" + name} {
if storage.CheckKey(key) != nil {
continue
}
if _, err := files.Stat(ctx, key); err == nil {
return func() (io.ReadCloser, error) { return files.Get(ctx, key) }, hostPath(cfg, key), nil
}
}
return nil, "", fmt.Errorf("no export at %s", arg)
}