The multi-tenant edition's plans (Free and Paid as decided, or a plans file) and each team's billing account, with a 14-day trial of Paid. A team's plan caps what its people and agents may change: modules outside it stay readable, a lapsed team changes nothing, and agents, Market entries, crawls and background jobs keep to it. Without a Stripe key, no billing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
419 lines
15 KiB
Go
419 lines
15 KiB
Go
// 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
|
|
OldKey []byte // the key being replaced: secrets under it are encrypted again with SecretKey
|
|
Storage Storage
|
|
Mail *Mail // nil if not set
|
|
PGBackups string // where the server's nightly dumps are, to list them; "" if not known
|
|
// PlatformAdmins are the email addresses of the people running the
|
|
// multi-tenant service (its /platform area).
|
|
PlatformAdmins []string
|
|
|
|
// Billing (multi-tenant): the platform's own Stripe account; empty, no
|
|
// billing (every team has everything).
|
|
StripeKey, StripeWebhookSecret string
|
|
StripePrice, StripePriceYear string // per person, a month and a year
|
|
StripePriceStorage string // an extra storage block, a month
|
|
PlansFile string // the plans, if not the defaults
|
|
}
|
|
|
|
// 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"
|
|
EnvOldKey = "SUPERMARKET_SECRET_KEY_OLD"
|
|
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"
|
|
EnvPGBackups = "SUPERMARKET_PG_BACKUPS"
|
|
EnvPlatform = "SUPERMARKET_PLATFORM_ADMINS"
|
|
EnvStripeKey = "SUPERMARKET_STRIPE_KEY"
|
|
EnvStripeHook = "SUPERMARKET_STRIPE_WEBHOOK_SECRET"
|
|
EnvStripePrice = "SUPERMARKET_STRIPE_PRICE"
|
|
EnvStripeYear = "SUPERMARKET_STRIPE_PRICE_YEAR"
|
|
EnvStripeStore = "SUPERMARKET_STRIPE_PRICE_STORAGE"
|
|
EnvPlans = "SUPERMARKET_PLANS"
|
|
)
|
|
|
|
// 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())
|
|
}
|
|
if k := get(EnvOldKey, ""); k != "" {
|
|
key, err := ParseKey(k)
|
|
switch {
|
|
case err != nil:
|
|
bad("%s: %v", EnvOldKey, err)
|
|
case c.SecretKey == nil:
|
|
bad("%s is set without %s: give the new key too", EnvOldKey, EnvSecretKey)
|
|
case string(key) == string(c.SecretKey):
|
|
bad("%s is the same key as %s", EnvOldKey, EnvSecretKey)
|
|
}
|
|
c.OldKey = key
|
|
}
|
|
|
|
// 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())
|
|
}
|
|
|
|
c.PGBackups = get(EnvPGBackups, "")
|
|
for _, a := range strings.Split(get(EnvPlatform, ""), ",") {
|
|
if a = strings.ToLower(strings.TrimSpace(a)); a == "" {
|
|
continue
|
|
}
|
|
if _, err := mail.ParseAddress(a); err != nil {
|
|
bad("%s: %q isn't an email address", EnvPlatform, a)
|
|
continue
|
|
}
|
|
c.PlatformAdmins = append(c.PlatformAdmins, a)
|
|
}
|
|
if len(c.PlatformAdmins) > 0 && c.Edition != Multi {
|
|
bad("%s is for the multi-tenant edition", EnvPlatform)
|
|
}
|
|
|
|
// Billing.
|
|
c.StripeKey, c.StripeWebhookSecret = get(EnvStripeKey, ""), get(EnvStripeHook, "")
|
|
c.StripePrice, c.StripePriceYear, c.StripePriceStorage = get(EnvStripePrice, ""), get(EnvStripeYear, ""), get(EnvStripeStore, "")
|
|
c.PlansFile = get(EnvPlans, "")
|
|
if c.StripeKey != "" {
|
|
switch {
|
|
case c.Edition != Multi:
|
|
bad("%s is for the multi-tenant edition: it bills its teams", EnvStripeKey)
|
|
case !strings.HasPrefix(c.StripeKey, "sk_") && !strings.HasPrefix(c.StripeKey, "rk_"):
|
|
bad("%s isn't a Stripe secret key (sk_…)", EnvStripeKey)
|
|
case c.StripeWebhookSecret == "":
|
|
bad("%s is needed with %s: the webhook's signing secret (whsec_…), from Stripe's dashboard", EnvStripeHook, EnvStripeKey)
|
|
case c.StripePrice == "" && c.PlansFile == "":
|
|
bad("%s is needed with %s: the paid plan's price per person a month (price_…)", EnvStripePrice, EnvStripeKey)
|
|
}
|
|
}
|
|
|
|
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: filepath.Join(dataDir, "files")}
|
|
}
|
|
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:
|
|
// every edition, since Phase 13.
|
|
func (c *Config) Ready() error { return nil }
|
|
|
|
// 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(), "Exports and uploaded files (" + EnvStorage + ")."}
|
|
if !c.Storage.S3() && c.Storage.Dir == filepath.Join(c.DataDir, "files") {
|
|
files.Value = filepath.Join(c.HostData, "files")
|
|
files.Help = "Exports and uploaded files, in the data folder."
|
|
}
|
|
items = append(items, files)
|
|
switch {
|
|
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."})
|
|
case c.SecretKey != nil:
|
|
help := "With the key in " + EnvSecretKey + "."
|
|
if c.OldKey != nil {
|
|
help = "Moving from the key in " + EnvOldKey + " to the one in " + EnvSecretKey + ": unset " + EnvOldKey + " once Supermarket has started."
|
|
}
|
|
items = append(items, Item{"Secrets", "Encrypted in the database", help})
|
|
}
|
|
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()
|
|
}
|