Phase 9, part 1: editions and their settings

SUPERMARKET_MODE picks local (the default), server or multi. internal/config
reads and checks every setting the editions need (database, secret key,
storage, the app's own mail, an https address), reporting all problems at
once. supermarket config prints them without passwords; supermarket
secret-key makes a key. Settings -> About shows the edition. Server and
multi-tenant are checked but refuse to start until they're built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 06:55:30 -07:00
co-authored by Claude Opus 5.5
parent 338eaa2c79
commit 7a857c7346
12 changed files with 671 additions and 9 deletions
+11
View File
@@ -1867,6 +1867,17 @@ done as the owner.
#### Phase 9: Groundwork: editions, Postgres, secrets and files #### 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 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 commit after each part; the whole test suite runs against both SQLite and
Postgres from part 2 on. Postgres from part 2 on.
+14
View File
@@ -786,3 +786,17 @@ Throughout, also notice:
without losing data. without losing data.
- [x] Backups hold no keys: open one with `sqlite3` and look for a token - [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. 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.
+2 -1
View File
@@ -19,6 +19,7 @@ Usage: supermarket [command]
hermes Set up, or repair, Hermes' connection to your Core's MCP hub 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 token Print the token agents use to reach Supermarket's MCP endpoint
data Print where its data is kept 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 [note] Back up the database now (it also backs up daily)
backup --with-secrets The same, with your keys and tokens, for moving backup --with-secrets The same, with your keys and tokens, for moving
to another computer (keep the file safe) to another computer (keep the file safe)
@@ -63,7 +64,7 @@ case "${1:-open}" in
logs) compose logs -f --tail 200 ;; logs) compose logs -f --tail 200 ;;
hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;; hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;;
token) cat "$DATA/mcp-token" ;; token) cat "$DATA/mcp-token" ;;
backup|backups) backup|backups|config)
if ! docker exec supermarket true 2> /dev/null; then if ! docker exec supermarket true 2> /dev/null; then
echo "Supermarket isn't running: start it first (supermarket start)." echo "Supermarket isn't running: start it first (supermarket start)."
exit 1 exit 1
+56 -8
View File
@@ -1,8 +1,9 @@
// Supermarket serves the marketing suite's web app. It's meant to run in // 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. // 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_DATA data folder (default /data)
// SUPERMARKET_ADDR listen address (default :8080) // SUPERMARKET_ADDR listen address (default :8080)
// SUPERMARKET_PUBLIC_URL the address the browser uses (default http://localhost:8470) // 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 <data>/mcp.sock) // 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 // SUPERMARKET_HOST_DATA the data folder's path on the host, to show in
// setup instructions (default: same as the data folder) // 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 package main
import ( import (
@@ -30,6 +36,7 @@ import (
"supermarket/internal/ai" "supermarket/internal/ai"
"supermarket/internal/backup" "supermarket/internal/backup"
"supermarket/internal/config"
"supermarket/internal/content" "supermarket/internal/content"
"supermarket/internal/core" "supermarket/internal/core"
"supermarket/internal/crm" "supermarket/internal/crm"
@@ -49,6 +56,18 @@ func main() {
fmt.Println(version) fmt.Println(version)
return 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 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 { if err := backupCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
@@ -70,13 +89,41 @@ func env(key, def string) string {
return def 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 { func run(log *slog.Logger) error {
dataDir := env("SUPERMARKET_DATA", "/data") cfg, err := config.Load(os.Getenv)
addr := env("SUPERMARKET_ADDR", ":8080") if err != nil {
publicURL := strings.TrimRight(env("SUPERMARKET_PUBLIC_URL", "http://localhost:8470"), "/") for _, problem := range strings.Split(err.Error(), "\n") {
coreConf := env("SUPERMARKET_CORE_CONF", filepath.Join(dataDir, "core.conf")) log.Error("settings: " + problem)
mcpSocket := env("SUPERMARKET_MCP_SOCKET", filepath.Join(dataDir, "mcp.sock")) }
hostData := env("SUPERMARKET_HOST_DATA", dataDir) 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 // Everything the app writes (database, secrets, clones) is for this user
// only: it will hold contacts and credentials. // only: it will hold contacts and credentials.
@@ -155,6 +202,7 @@ func run(log *slog.Logger) error {
} }
srv := &web.Server{ srv := &web.Server{
Config: cfg,
DB: database, DB: database,
Secrets: sec, Secrets: sec,
Core: c, Core: c,
@@ -215,7 +263,7 @@ func run(log *slog.Logger) error {
} }
}() }()
go func() { 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() errCh <- httpServer.ListenAndServe()
}() }()
+355
View File
@@ -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 <no-reply@example.com>"
}
// 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 <no-reply@" + host + ">"
}
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()
}
+147
View File
@@ -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 <no-reply@sm.example.com>" {
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")
}
}
+44
View File
@@ -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(),
}})
}
+3
View File
@@ -14,6 +14,7 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"supermarket/internal/config"
"sync" "sync"
"time" "time"
"unicode" "unicode"
@@ -42,6 +43,7 @@ var staticFS embed.FS
// Server holds what the handlers need. // Server holds what the handlers need.
type Server struct { type Server struct {
Config *config.Config // how it's run; nil in tests: the local edition
DB *db.DB DB *db.DB
Secrets *secrets.Store Secrets *secrets.Store
Core *core.Core // nil without a Core 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("POST /settings/backups/{action}", s.backupsAction)
mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload) mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload)
mux.HandleFunc("POST /settings/backups/upload", s.backupUpload) 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", s.corePage)
mux.HandleFunc("GET /settings/core/checks", s.coreChecks) mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
+16
View File
@@ -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)
}
}
}
+5
View File
@@ -481,3 +481,8 @@ svg.line-chart line.axis { stroke: hsl(var(--border)); }
.next-item .next-head h3 { margin: 0; } .next-item .next-head h3 { margin: 0; }
.next-item .next-head p { margin: 0 0 0.15rem; } .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)); } .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; }
+16
View File
@@ -0,0 +1,16 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>About</h2>
<p class="lede">This Supermarket: its edition, its version, and where it keeps things.</p>
<section class="card">
<h2>{{.Edition.Name}} edition</h2>
<dl class="facts">
<dt>Version</dt><dd>{{.Version}} <span class="muted">· database schema {{.Schema}}</span></dd>
{{range .Items}}<dt>{{.Name}}</dt><dd>{{.Value}}{{if .Help}} <span class="help">{{.Help}}</span>{{end}}</dd>
{{end}}
</dl>
{{if eq (print .Edition) "local"}}
<p class="help">Supermarket also comes as a <strong>server</strong> edition, for a team signing in on a server, and a <strong>multi-tenant</strong> one, for many teams at one address. The edition is chosen with <code>SUPERMARKET_MODE</code> when it starts; <code>supermarket config</code> checks the settings.</p>
{{end}}
</section>
{{end}}{{template "settings-end"}}{{end}}
+2
View File
@@ -136,6 +136,7 @@
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a> <a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
<div class="nav-label">Data</div> <div class="nav-label">Data</div>
<a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a> <a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a>
<a href="/settings/about" {{if eq .Nav "settings/about"}}aria-current="page"{{end}}>{{template "icon" "info"}}About</a>
</nav> </nav>
<div class="settings-body"> <div class="settings-body">
{{end}} {{end}}
@@ -183,6 +184,7 @@
{{- else if eq . "accounts"}}<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/> {{- else if eq . "accounts"}}<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/>
{{- else if eq . "ai"}}<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/> {{- else if eq . "ai"}}<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>
{{- else if eq . "core"}}<path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z"/><path d="m2 22 3-3"/><path d="M7.5 13.5 10 11"/><path d="M10.5 16.5 13 14"/><path d="m18 3-4 4h6l-4 4"/> {{- else if eq . "core"}}<path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z"/><path d="m2 22 3-3"/><path d="M7.5 13.5 10 11"/><path d="M10.5 16.5 13 14"/><path d="m18 3-4 4h6l-4 4"/>
{{- else if eq . "info"}}<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>
{{- else if eq . "backups"}}<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/> {{- else if eq . "backups"}}<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>
{{- else if eq . "chevron"}}<path d="m6 9 6 6 6-6"/> {{- else if eq . "chevron"}}<path d="m6 9 6 6 6-6"/>
{{- else if eq . "menu"}}<path d="M4 12h16"/><path d="M4 6h16"/><path d="M4 18h16"/> {{- else if eq . "menu"}}<path d="M4 12h16"/><path d="M4 6h16"/><path d="M4 18h16"/>