diff --git a/PLAN.md b/PLAN.md index 3c42c30..d4a5b3d 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1867,6 +1867,17 @@ done as the owner. #### Phase 9: Groundwork: editions, Postgres, secrets and files +**Part 1 built 2026-11-25** on branch `phase9`. A new `internal/config` +package reads and checks every setting, listing all the problems at once. +`supermarket config` prints the settings (never a password or the key) +and any problems; `supermarket secret-key` makes a key. Settings → About +shows the edition. Server and multi-tenant settings are checked, but +starting either one says it isn't built yet, until the parts that make +them work are done. S3 storage takes `SUPERMARKET_S3_ENDPOINT`, +`_REGION` (default `garage`), `_ACCESS_KEY` and `_SECRET_KEY`; the app's +mail takes `SUPERMARKET_MAIL_URL` (`smtp://` with STARTTLS, or +`smtps://`) and `SUPERMARKET_MAIL_FROM`. + Nothing changes for the local user; this makes the rest possible. A commit after each part; the whole test suite runs against both SQLite and Postgres from part 2 on. diff --git a/TEST.md b/TEST.md index c821af2..4a3b38c 100644 --- a/TEST.md +++ b/TEST.md @@ -786,3 +786,17 @@ Throughout, also notice: without losing data. - [x] Backups hold no keys: open one with `sqlite3` and look for a token you've saved (e.g. `.dump` and search); it isn't there. + +## 13. Editions (Phase 9) + +- [ ] Settings → About says **Local edition**, with the version, the + database schema, and the database, files and secrets in + `~/.local/share/supermarket`. +- [ ] `supermarket config` prints the same, and "The settings are fine." +- [ ] `docker exec supermarket supermarket secret-key` prints a new + 64-digit key each time. +- [ ] Started with `SUPERMARKET_MODE=server` and nothing else, Supermarket + doesn't start: its log names each missing setting (database, secret + key, mail, an https:// address). With them all set, it says the + server edition isn't built yet. `supermarket config` never shows a + password or the key. diff --git a/bin/supermarket b/bin/supermarket index 9744481..51d0f17 100755 --- a/bin/supermarket +++ b/bin/supermarket @@ -19,6 +19,7 @@ Usage: supermarket [command] hermes Set up, or repair, Hermes' connection to your Core's MCP hub token Print the token agents use to reach Supermarket's MCP endpoint data Print where its data is kept + config Show its edition and settings, and any problems with them backup [note] Back up the database now (it also backs up daily) backup --with-secrets The same, with your keys and tokens, for moving to another computer (keep the file safe) @@ -63,7 +64,7 @@ case "${1:-open}" in logs) compose logs -f --tail 200 ;; hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;; token) cat "$DATA/mcp-token" ;; - backup|backups) + backup|backups|config) if ! docker exec supermarket true 2> /dev/null; then echo "Supermarket isn't running: start it first (supermarket start)." exit 1 diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index 7a89c99..6661528 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -1,8 +1,9 @@ // 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: +// 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) @@ -10,6 +11,11 @@ // SUPERMARKET_MCP_SOCKET Unix socket for agents' MCP (default /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 ( @@ -30,6 +36,7 @@ import ( "supermarket/internal/ai" "supermarket/internal/backup" + "supermarket/internal/config" "supermarket/internal/content" "supermarket/internal/core" "supermarket/internal/crm" @@ -49,6 +56,18 @@ func main() { 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] == "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) @@ -70,13 +89,41 @@ func env(key, def string) string { 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 { + 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 +} + func run(log *slog.Logger) error { - dataDir := env("SUPERMARKET_DATA", "/data") - addr := env("SUPERMARKET_ADDR", ":8080") - publicURL := strings.TrimRight(env("SUPERMARKET_PUBLIC_URL", "http://localhost:8470"), "/") - coreConf := env("SUPERMARKET_CORE_CONF", filepath.Join(dataDir, "core.conf")) - mcpSocket := env("SUPERMARKET_MCP_SOCKET", filepath.Join(dataDir, "mcp.sock")) - hostData := env("SUPERMARKET_HOST_DATA", dataDir) + 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. @@ -155,6 +202,7 @@ func run(log *slog.Logger) error { } srv := &web.Server{ + Config: cfg, DB: database, Secrets: sec, Core: c, @@ -215,7 +263,7 @@ func run(log *slog.Logger) error { } }() go func() { - log.Info("Supermarket is running", "version", version, "listen", addr, "open", publicURL) + log.Info("Supermarket is running", "version", version, "edition", cfg.Edition, "listen", addr, "open", publicURL) errCh <- httpServer.ListenAndServe() }() diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..8a37c42 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,355 @@ +// Package config reads how Supermarket is run from its environment: which +// edition (local, server or multi-tenant), and what that edition needs +// (a database, a key for secrets, file storage, a mail server). It checks +// that the settings fit together, and says what's wrong when they don't. +package config + +import ( + "crypto/rand" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "net" + "net/mail" + "net/url" + "path/filepath" + "strings" +) + +// Edition is how Supermarket is run. +type Edition string + +const ( + // Local is one person on their own computer: no sign-in, SQLite, the + // data folder. The default. + Local Edition = "local" + // Server is one team on a server: sign-in, Postgres. + Server Edition = "server" + // Multi is many teams at one address: sign-in, Postgres, object + // storage, billing. + Multi Edition = "multi" +) + +// Name is the edition as the app shows it. +func (e Edition) Name() string { + switch e { + case Server: + return "Server" + case Multi: + return "Multi-tenant" + } + return "Local" +} + +// Storage is where files go: a folder, or an S3-compatible bucket. +type Storage struct { + Dir string // a folder, when not S3 + + Bucket, Prefix string // s3://bucket/prefix + Endpoint string // the S3 server (Garage, …), https://… + Region string + AccessKey string + SecretKey string +} + +// S3 says whether files go to object storage. +func (s Storage) S3() bool { return s.Bucket != "" } + +// String describes it, without credentials. +func (s Storage) String() string { + if s.S3() { + u := "s3://" + s.Bucket + if s.Prefix != "" { + u += "/" + s.Prefix + } + return u + " at " + s.Endpoint + } + return s.Dir +} + +// Mail is the SMTP server the app sends its own mail through +// (invitations, password resets): not a team's outreach mail. +type Mail struct { + Host string // host:port + TLS bool // smtps: TLS from the start; smtp: STARTTLS when offered + User string + Password string + From string // the sender, e.g. "Supermarket " +} + +// Config is how this Supermarket is run. +type Config struct { + Edition Edition + + DataDir string // where the local edition keeps everything, and scratch files on the others + Addr string // the address to listen on + PublicURL string // the address people use, without a trailing slash + CoreConf string + MCPSocket string + HostData string // the data folder's path on the host, for instructions + + DatabaseURL string // postgres://…; empty on the local edition + SecretKey []byte // 32 bytes that encrypt secrets in the database; nil if not set + Storage Storage + Mail *Mail // nil if not set +} + +// Environment variables. +const ( + EnvMode = "SUPERMARKET_MODE" + EnvData = "SUPERMARKET_DATA" + EnvAddr = "SUPERMARKET_ADDR" + EnvPublicURL = "SUPERMARKET_PUBLIC_URL" + EnvCoreConf = "SUPERMARKET_CORE_CONF" + EnvMCPSocket = "SUPERMARKET_MCP_SOCKET" + EnvHostData = "SUPERMARKET_HOST_DATA" + EnvDatabaseURL = "SUPERMARKET_DATABASE_URL" + EnvSecretKey = "SUPERMARKET_SECRET_KEY" + EnvStorage = "SUPERMARKET_STORAGE" + EnvS3Endpoint = "SUPERMARKET_S3_ENDPOINT" + EnvS3Region = "SUPERMARKET_S3_REGION" + EnvS3AccessKey = "SUPERMARKET_S3_ACCESS_KEY" + EnvS3SecretKey = "SUPERMARKET_S3_SECRET_KEY" + EnvMailURL = "SUPERMARKET_MAIL_URL" + EnvMailFrom = "SUPERMARKET_MAIL_FROM" +) + +// Load reads the settings through getenv (os.Getenv) and checks them. All +// the problems found are returned together, one per line. +func Load(getenv func(string) string) (*Config, error) { + get := func(k, def string) string { + if v := strings.TrimSpace(getenv(k)); v != "" { + return v + } + return def + } + var problems []string + bad := func(format string, a ...any) { problems = append(problems, fmt.Sprintf(format, a...)) } + + c := &Config{Edition: Edition(strings.ToLower(get(EnvMode, string(Local))))} + switch c.Edition { + case Local, Server, Multi: + default: + bad("%s is %q: it must be local, server or multi", EnvMode, getenv(EnvMode)) + } + c.DataDir = get(EnvData, "/data") + c.Addr = get(EnvAddr, ":8080") + c.CoreConf = get(EnvCoreConf, filepath.Join(c.DataDir, "core.conf")) + c.MCPSocket = get(EnvMCPSocket, filepath.Join(c.DataDir, "mcp.sock")) + c.HostData = get(EnvHostData, c.DataDir) + shared := c.Edition == Server || c.Edition == Multi + + // The address people use. + c.PublicURL = strings.TrimRight(get(EnvPublicURL, "http://localhost:8470"), "/") + if u, err := url.Parse(c.PublicURL); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" { + bad("%s is %q: give the address people open, such as https://supermarket.example.com", EnvPublicURL, c.PublicURL) + } else if shared && u.Scheme != "https" { + bad("%s must start with https:// on the %s edition: people sign in through it", EnvPublicURL, c.Edition.Name()) + } else if shared && getenv(EnvPublicURL) == "" { + bad("%s is needed on the %s edition: the https:// address people open", EnvPublicURL, c.Edition.Name()) + } + + // The database. + c.DatabaseURL = get(EnvDatabaseURL, "") + switch { + case c.Edition == Local && c.DatabaseURL != "": + bad("%s is set, but the local edition keeps its database in the data folder (SQLite): unset it, or set %s=server", EnvDatabaseURL, EnvMode) + case shared && c.DatabaseURL == "": + bad("%s is needed on the %s edition: postgres://user:password@host:5432/supermarket", EnvDatabaseURL, c.Edition.Name()) + case shared: + if u, err := url.Parse(c.DatabaseURL); err != nil || (u.Scheme != "postgres" && u.Scheme != "postgresql") || u.Host == "" { + bad("%s must be a Postgres address: postgres://user:password@host:5432/supermarket", EnvDatabaseURL) + } + } + + // The key for secrets. + if k := get(EnvSecretKey, ""); k != "" { + key, err := ParseKey(k) + if err != nil { + bad("%s: %v (supermarket secret-key makes one)", EnvSecretKey, err) + } + c.SecretKey = key + } else if shared { + bad("%s is needed on the %s edition: it encrypts the keys and tokens kept in the database. Run supermarket secret-key to make one, and keep a copy somewhere safe", EnvSecretKey, c.Edition.Name()) + } + + // Files. + c.Storage = loadStorage(get, bad, c.DataDir) + switch { + case c.Edition == Local && c.Storage.S3(): + bad("%s is an S3 bucket, but the local edition keeps its files in the data folder: unset it", EnvStorage) + case c.Edition == Multi && !c.Storage.S3(): + bad("%s must be an S3 bucket on the multi-tenant edition (s3://bucket/prefix), so every copy of the app sees the same files", EnvStorage) + } + + // The app's own mail. + if m := get(EnvMailURL, ""); m != "" { + mm, err := parseMail(m, get(EnvMailFrom, ""), c.PublicURL) + if err != nil { + bad("%s: %v", EnvMailURL, err) + } + c.Mail = mm + } else if shared { + bad("%s is needed on the %s edition, to send invitations and password resets: smtp://user:password@mail.example.com:587", EnvMailURL, c.Edition.Name()) + } + + if len(problems) > 0 { + return c, errors.New(strings.Join(problems, "\n")) + } + return c, nil +} + +func loadStorage(get func(string, string) string, bad func(string, ...any), dataDir string) Storage { + v := get(EnvStorage, "") + if v == "" { + return Storage{Dir: dataDir} + } + if !strings.HasPrefix(v, "s3://") { + if !filepath.IsAbs(v) { + bad("%s is %q: give a folder's full path, or s3://bucket/prefix", EnvStorage, v) + } + return Storage{Dir: filepath.Clean(v)} + } + u, err := url.Parse(v) + if err != nil || u.Host == "" { + bad("%s is %q: an S3 bucket is s3://bucket or s3://bucket/prefix", EnvStorage, v) + return Storage{} + } + s := Storage{ + Bucket: u.Host, Prefix: strings.Trim(u.Path, "/"), + Endpoint: strings.TrimRight(get(EnvS3Endpoint, ""), "/"), + Region: get(EnvS3Region, "garage"), + AccessKey: get(EnvS3AccessKey, ""), + SecretKey: get(EnvS3SecretKey, ""), + } + if e, err := url.Parse(s.Endpoint); s.Endpoint == "" || err != nil || (e.Scheme != "https" && e.Scheme != "http") || e.Host == "" { + bad("%s is needed with an S3 bucket: the storage server's address, such as https://s3.example.com", EnvS3Endpoint) + } + if s.AccessKey == "" || s.SecretKey == "" { + bad("%s and %s are needed with an S3 bucket", EnvS3AccessKey, EnvS3SecretKey) + } + return s +} + +func parseMail(raw, from, publicURL string) (*Mail, error) { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "smtp" && u.Scheme != "smtps") || u.Hostname() == "" { + return nil, errors.New("give the mail server as smtp://user:password@host:587 (STARTTLS) or smtps://…:465 (TLS)") + } + m := &Mail{TLS: u.Scheme == "smtps", Host: u.Host} + if u.Port() == "" { + port := "587" + if m.TLS { + port = "465" + } + m.Host = net.JoinHostPort(u.Hostname(), port) + } + if u.User != nil { + m.User = u.User.Username() + m.Password, _ = u.User.Password() + } + if from == "" { + from = u.Query().Get("from") + } + if from == "" { + host := "localhost" + if pu, err := url.Parse(publicURL); err == nil && pu.Hostname() != "" { + host = pu.Hostname() + } + from = "Supermarket " + } + if _, err := mail.ParseAddress(from); err != nil { + return nil, fmt.Errorf("the sender %q isn't an email address (%s)", from, EnvMailFrom) + } + m.From = from + return m, nil +} + +// ParseKey reads a secret key: 32 bytes as 64 hex digits, or as base64. +func ParseKey(s string) ([]byte, error) { + s = strings.TrimSpace(s) + if b, err := hex.DecodeString(s); err == nil && len(b) == 32 { + return b, nil + } + for _, enc := range []*base64.Encoding{base64.StdEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.RawURLEncoding} { + if b, err := enc.DecodeString(s); err == nil && len(b) == 32 { + return b, nil + } + } + return nil, errors.New("it must be 32 random bytes, as 64 hex digits or base64") +} + +// NewKey makes a secret key, as 64 hex digits. +func NewKey() (string, error) { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "", err + } + return hex.EncodeToString(b), nil +} + +// Ready says whether this version of Supermarket can run the edition. The +// server and multi-tenant editions are planned (PLAN.md, Phases 9–14) and +// come in steps; until they're built, only the settings are checked. +func (c *Config) Ready() error { + if c.Edition == Local { + return nil + } + return fmt.Errorf("This version of Supermarket runs only the local edition: the %s edition isn't built yet. Its settings are fine", c.Edition.Name()) +} + +// Item is one line of the settings, to show. +type Item struct { + Name, Value, Help string +} + +// Summary describes the settings for Settings → About and `supermarket +// config`, without passwords or keys. +func (c *Config) Summary() []Item { + items := []Item{ + {"Edition", c.Edition.Name(), editionHelp[c.Edition]}, + {"Address", c.PublicURL, "Where people open Supermarket (" + EnvPublicURL + ")."}, + } + switch { + case c.DatabaseURL == "" && c.Edition == Local: + items = append(items, Item{"Database", "SQLite: " + filepath.Join(c.HostData, "app.db"), "One file in the data folder."}) + case c.DatabaseURL == "": + items = append(items, Item{"Database", "Not set", EnvDatabaseURL + "."}) + default: + items = append(items, Item{"Database", "Postgres: " + RedactURL(c.DatabaseURL), EnvDatabaseURL + "."}) + } + files := Item{"Files", c.Storage.String(), "Backups, exports and uploads (" + EnvStorage + ")."} + if !c.Storage.S3() && c.Storage.Dir == c.DataDir { + files.Value = c.HostData + files.Help = "The data folder." + } + items = append(items, files) + switch { + case c.SecretKey != nil: + items = append(items, Item{"Secrets", "Encrypted in the database", "With the key in " + EnvSecretKey + "."}) + case c.Edition == Local: + items = append(items, Item{"Secrets", filepath.Join(c.HostData, "secrets.json"), "Readable only by you; never in backups unless you ask."}) + } + if c.Mail != nil { + items = append(items, Item{"Mail", c.Mail.From + " through " + c.Mail.Host, "The app's own mail: invitations and password resets (" + EnvMailURL + ")."}) + } else if c.Edition == Local { + items = append(items, Item{"Mail", "Not needed", "The local edition sends no mail of its own; outreach uses Settings → Email."}) + } + return items +} + +var editionHelp = map[Edition]string{ + Local: "One person, on this computer, with no sign-in: only this computer can reach it.", + Server: "One team, on a server, signing in.", + Multi: "Many teams at one address, each working on its own domain.", +} + +// RedactURL hides a URL's password. +func RedactURL(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "(unreadable)" + } + return u.Redacted() +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go new file mode 100644 index 0000000..acc69c8 --- /dev/null +++ b/internal/config/config_test.go @@ -0,0 +1,147 @@ +package config + +import ( + "strings" + "testing" +) + +func envOf(m map[string]string) func(string) string { + return func(k string) string { return m[k] } +} + +const key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + +func TestLocalDefaults(t *testing.T) { + c, err := Load(envOf(nil)) + if err != nil { + t.Fatal(err) + } + if c.Edition != Local || c.DataDir != "/data" || c.Addr != ":8080" || c.PublicURL != "http://localhost:8470" || + c.Storage.Dir != "/data" || c.Storage.S3() || c.Mail != nil || c.SecretKey != nil || c.DatabaseURL != "" { + t.Fatalf("%+v", c) + } + if c.CoreConf != "/data/core.conf" || c.MCPSocket != "/data/mcp.sock" || c.HostData != "/data" { + t.Fatalf("%+v", c) + } + if err := c.Ready(); err != nil { + t.Fatal(err) + } + // As today's compose.yaml runs it. + c, err = Load(envOf(map[string]string{EnvPublicURL: "http://localhost:8470/", EnvHostData: "/home/u/.local/share/supermarket", "TZ": "Europe/Rome"})) + if err != nil || c.PublicURL != "http://localhost:8470" { + t.Fatal(c, err) + } + for _, it := range c.Summary() { + if it.Name == "Database" && it.Value != "SQLite: /home/u/.local/share/supermarket/app.db" { + t.Errorf("summary: %+v", it) + } + } +} + +func TestLocalRefusesServerSettings(t *testing.T) { + _, err := Load(envOf(map[string]string{EnvDatabaseURL: "postgres://u:p@db/sm", EnvStorage: "s3://b"})) + if err == nil || !strings.Contains(err.Error(), EnvDatabaseURL) || !strings.Contains(err.Error(), EnvStorage) { + t.Fatal(err) + } + if _, err := Load(envOf(map[string]string{EnvMode: "cloud"})); err == nil || !strings.Contains(err.Error(), "local, server or multi") { + t.Fatal(err) + } +} + +func TestServerNeedsEverything(t *testing.T) { + _, err := Load(envOf(map[string]string{EnvMode: "server"})) + if err == nil { + t.Fatal("no error") + } + for _, want := range []string{EnvPublicURL, EnvDatabaseURL, EnvSecretKey, EnvMailURL} { + if !strings.Contains(err.Error(), want) { + t.Errorf("no word of %s in:\n%v", want, err) + } + } + _, err = Load(envOf(map[string]string{EnvMode: "server", EnvPublicURL: "http://sm.example.com"})) + if err == nil || !strings.Contains(err.Error(), "https://") { + t.Fatal(err) + } +} + +func server() map[string]string { + return map[string]string{ + EnvMode: "Server", EnvPublicURL: "https://sm.example.com", EnvDatabaseURL: "postgres://sm:hunter2@db:5432/supermarket", + EnvSecretKey: key, EnvMailURL: "smtp://sm%40example.com:pw@mail.example.com", + } +} + +func TestServer(t *testing.T) { + c, err := Load(envOf(server())) + if err != nil { + t.Fatal(err) + } + if c.Edition != Server || len(c.SecretKey) != 32 || c.Storage.Dir != "/data" { + t.Fatalf("%+v", c) + } + m := c.Mail + if m.Host != "mail.example.com:587" || m.TLS || m.User != "sm@example.com" || m.Password != "pw" || m.From != "Supermarket " { + t.Fatalf("%+v", m) + } + if err := c.Ready(); err == nil || !strings.Contains(err.Error(), "isn't built yet") { + t.Fatal(err) + } + // The summary never shows a password. + for _, it := range c.Summary() { + if strings.Contains(it.Value, "hunter2") || strings.Contains(it.Value, "pw@") || strings.Contains(it.Value, key) { + t.Errorf("leaks: %+v", it) + } + } + env := server() + env[EnvDatabaseURL] = "mysql://x@db/sm" + env[EnvSecretKey] = "short" + env[EnvMailURL] = "smtps://mail.example.com" + env[EnvMailFrom] = "not an address" + _, err = Load(envOf(env)) + for _, want := range []string{"Postgres address", "32 random bytes", "isn't an email address"} { + if err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("want %q in %v", want, err) + } + } +} + +func TestMulti(t *testing.T) { + env := server() + env[EnvMode] = "multi" + if _, err := Load(envOf(env)); err == nil || !strings.Contains(err.Error(), "S3 bucket") { + t.Fatal(err) + } + env[EnvStorage] = "s3://supermarket/prod/" + if _, err := Load(envOf(env)); err == nil || !strings.Contains(err.Error(), EnvS3Endpoint) || !strings.Contains(err.Error(), EnvS3AccessKey) { + t.Fatal(err) + } + env[EnvS3Endpoint] = "https://s3.example.com/" + env[EnvS3AccessKey], env[EnvS3SecretKey] = "GK1", "s3cret" + c, err := Load(envOf(env)) + if err != nil { + t.Fatal(err) + } + s := c.Storage + if s.Bucket != "supermarket" || s.Prefix != "prod" || s.Endpoint != "https://s3.example.com" || s.Region != "garage" || s.String() != "s3://supermarket/prod at https://s3.example.com" { + t.Fatalf("%+v", s) + } +} + +func TestKeys(t *testing.T) { + k, err := NewKey() + if err != nil { + t.Fatal(err) + } + if b, err := ParseKey(k); err != nil || len(b) != 32 { + t.Fatal(b, err) + } + if b, err := ParseKey("MDEyMzQ1Njc4OWFiY2RlZjAxMjM0NTY3ODlhYmNkZWY="); err != nil || string(b) != "0123456789abcdef0123456789abcdef" { + t.Fatal(b, err) + } + if _, err := ParseKey("abcd"); err == nil { + t.Fatal("short key accepted") + } + if _, err := Load(envOf(map[string]string{EnvStorage: "relative/dir"})); err == nil { + t.Fatal("relative folder accepted") + } +} diff --git a/internal/web/about.go b/internal/web/about.go new file mode 100644 index 0000000..cb7bced --- /dev/null +++ b/internal/web/about.go @@ -0,0 +1,44 @@ +package web + +import ( + "net/http" + "os" + + "supermarket/internal/config" + "supermarket/internal/db" +) + +// config is how this Supermarket is run: the local edition's defaults when +// none was given (tests). +func (s *Server) config() *config.Config { + if s.Config != nil { + return s.Config + } + c, _ := config.Load(func(k string) string { + switch k { + case config.EnvData, config.EnvHostData: + return s.DataDir + case config.EnvPublicURL: + return s.PublicURL + case config.EnvMode: + return "" + } + return os.Getenv(k) + }) + return c +} + +type aboutData struct { + Edition config.Edition + Version string + Schema int + Items []config.Item +} + +// aboutPage shows the edition and how it's run (Settings → About). +func (s *Server) aboutPage(w http.ResponseWriter, r *http.Request) { + c := s.config() + s.render(w, r, "about", page{Title: "About", Nav: "settings/about", Data: aboutData{ + Edition: c.Edition, Version: s.Version, Schema: db.Schema(), Items: c.Summary(), + }}) +} diff --git a/internal/web/server.go b/internal/web/server.go index d96ac23..c8779ec 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -14,6 +14,7 @@ import ( "regexp" "strconv" "strings" + "supermarket/internal/config" "sync" "time" "unicode" @@ -42,6 +43,7 @@ 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 @@ -259,6 +261,7 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /settings/backups/{action}", s.backupsAction) mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload) mux.HandleFunc("POST /settings/backups/upload", s.backupUpload) + mux.HandleFunc("GET /settings/about", s.aboutPage) mux.HandleFunc("GET /settings/core", s.corePage) mux.HandleFunc("GET /settings/core/checks", s.coreChecks) diff --git a/internal/web/server_test.go b/internal/web/server_test.go index cf03f0f..7cbcc86 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -739,3 +739,19 @@ func TestRedirectKeepsFragmentLast(t *testing.T) { } } } + +// Settings → About shows the edition, and where the local edition keeps +// its database. +func TestAboutPage(t *testing.T) { + s, h := newTestServer(t, nil) + rec := do(h, "GET", "/settings/about", nil, nil) + if rec.Code != 200 { + t.Fatal(rec.Code) + } + body := rec.Body.String() + for _, want := range []string{"Local edition", "SQLite: " + s.DataDir + "/app.db", "SUPERMARKET_MODE", `href="/settings/about" aria-current="page"`} { + if !strings.Contains(body, want) { + t.Errorf("no %q", want) + } + } +} diff --git a/internal/web/static/app.css b/internal/web/static/app.css index e61d387..db44504 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -481,3 +481,8 @@ svg.line-chart line.axis { stroke: hsl(var(--border)); } .next-item .next-head h3 { margin: 0; } .next-item .next-head p { margin: 0 0 0.15rem; } .next-rank { flex: none; width: 1.9rem; height: 1.9rem; border-radius: 999px; display: grid; place-items: center; font-weight: 600; background: hsl(var(--accent)); color: hsl(var(--accent-foreground)); } + +/* Settings → About: name and value pairs */ +dl.facts { display: grid; grid-template-columns: max-content 1fr; gap: 0.6rem 1.2rem; margin: 0.5rem 0 0.8rem; } +dl.facts dt { font-weight: 600; color: hsl(var(--muted-foreground)); } +dl.facts dd { margin: 0; overflow-wrap: anywhere; } diff --git a/internal/web/templates/about.html b/internal/web/templates/about.html new file mode 100644 index 0000000..b367e4a --- /dev/null +++ b/internal/web/templates/about.html @@ -0,0 +1,16 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}} +

About

+

This Supermarket: its edition, its version, and where it keeps things.

+ +
+

{{.Edition.Name}} edition

+
+
Version
{{.Version}} · database schema {{.Schema}}
+ {{range .Items}}
{{.Name}}
{{.Value}}{{if .Help}} {{.Help}}{{end}}
+ {{end}} +
+ {{if eq (print .Edition) "local"}} +

Supermarket also comes as a server edition, for a team signing in on a server, and a multi-tenant one, for many teams at one address. The edition is chosen with SUPERMARKET_MODE when it starts; supermarket config checks the settings.

+ {{end}} +
+{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 2a81776..a5104d4 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -136,6 +136,7 @@ {{template "icon" "ai"}}AI {{template "icon" "backups"}}Backups + {{template "icon" "info"}}About
{{end}} @@ -183,6 +184,7 @@ {{- else if eq . "accounts"}} {{- else if eq . "ai"}} {{- else if eq . "core"}} +{{- else if eq . "info"}} {{- else if eq . "backups"}} {{- else if eq . "chevron"}} {{- else if eq . "menu"}}