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>
This commit is contained in:
2026-11-25 09:37:34 -07:00
co-authored by Claude Opus 5.5
parent c8964cec12
commit da16736fb4
15 changed files with 532 additions and 17 deletions
+4
View File
@@ -14,3 +14,7 @@ dismissed.json
# Build output
/supermarket
# The server edition's settings and certificates (install-server.sh).
server.env
server/certs/*
!server/certs/.keep
+4
View File
@@ -24,6 +24,10 @@ FROM alpine:3.22
RUN apk add --no-cache ca-certificates tzdata git
COPY --from=hugo /go/bin/hugo /usr/local/bin/hugo
COPY --from=build /out/supermarket /usr/local/bin/supermarket
# The server edition runs as 10001 (compose.server.yaml): a new volume at
# /data takes this folder's owner. The local edition runs as you, with your
# own folder mounted there instead.
RUN mkdir -p /data /backups && chown 10001:10001 /data
LABEL org.opencontainers.image.title="supermarket"
ENV SUPERMARKET_DATA=/data
EXPOSE 8080
+36 -5
View File
@@ -43,12 +43,17 @@ fixed. Since then:
- Listmonk mailing lists, with their opt-outs synced to suppression.
- Phase 9: the groundwork for the server and multi-tenant editions.
The local edition runs as before, its database at schema 31. The server
and multi-tenant editions check their settings, but won't start until
Phase 10 brings sign-in.
The local edition runs as before, its database at schema 36 once Phase 10
is merged. The server edition runs; multi-tenant checks its settings but
won't start until Phase 13.
**Next: Phase 10, users, sign-in and roles (the server edition).** No
decisions are open for it; Phase 12 still needs who adds Supermarket's
**Phase 10 (users, sign-in and roles; the server edition) is built** on
branch `phase10` (2026-11-25), not yet merged: schema 36, a new
`compose.server.yaml` and `install-server.sh`. On the local edition,
the visible changes are posting accounts, Connections, Activity, and a
CSRF token in every form.
**Next: Phase 11, agents.** Phase 12 still needs who adds Supermarket's
client to Authelia.
**Coming back to it (for the agent working on it):**
@@ -2369,6 +2374,32 @@ starts** (multi-tenant still doesn't).
- *By Jane*: on drafts in Posts (who wrote it), published posts (who
posted it, and as which account) and outreach emails (who drafted it).
**Part 9 built 2026-11-25** on `phase10`. **Phase 10 is built.**
- `compose.server.yaml`: Supermarket (as uid 10001, read-only, no
capabilities, published only to Caddy), Postgres 18 on an internal
network with no way out, a `backup` service (`server/backup.sh`:
`pg_dump` custom format at 03:00, 14 days kept, the first at once) and
Caddy (`server/Caddyfile`, HSTS, ports 80 and 443, configurable).
`SUPERMARKET_TLS` picks the certificate: Let's Encrypt (empty), Caddy's
own CA (`tls internal`) or the team's (`tls /certs/…`, in `server/certs/`).
- `install-server.sh` asks for the domain, the certificate, the mail server
and the sender, makes the database password and secret key, writes
`server.env` (0600, git-ignored), builds and starts everything, and
prints the setup link. Run again after `git pull` to update.
- On the server edition, the local-only parts don't run: the MCP socket and
the CRM state file for Hermes (agents come with Phase 11).
- Settings → Backups on Postgres lists the dumps (`SUPERMARKET_PG_BACKUPS`,
the backup volume mounted read-only), warns when the last is over 36
hours old, and gives the operator's `pg_restore` commands; nothing is
restored from the browser.
- README has *The server edition*; TEST.md section 14 has its checks.
- Checked end to end in Docker (2026-11-25), on ports 18080/18443 with
`tls internal`: all four services up, the setup link printed, the owner
created over HTTPS with `__Host-` cookies, an SEO member invited (the
email fails without a mail server, and says so in the log), cross-site
and token-less posts refused, Activity showing the steps, HSTS and
`X-Frame-Options` set, the first dump on the Backups page.
1. **Users and sessions.**
- Tables:
- `users`: email, name, kind (person or agent), status (invited,
+53 -1
View File
@@ -210,10 +210,62 @@ The old terminal app used `http://localhost:8080/callback`; you can remove that
## Security
- The port is published on `127.0.0.1` only, so other machines can't reach it, whatever the firewall says.
- The app has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages: each form carries a random token that another site can't know, and the browser's `Origin` must be the app's own.
- The local edition has no login, so it protects itself from web pages open in the same browser: it only answers requests addressed to `localhost` (against DNS rebinding), and refuses form posts that don't come from its own pages: each form carries a random token that another site can't know, and the browser's `Origin` must be the app's own.
- The container runs as you, with a read-only filesystem, no Linux capabilities and `no-new-privileges`. It can write only its data folder.
- `/mcp` requires the bearer token in `mcp-token`.
## The server edition
Supermarket also runs on a server, for a team that signs in: one company,
at its own domain, with Postgres for its database and Caddy for HTTPS.
**Installing.** On a server with Docker and the compose plugin, clone this
repository and run `./install-server.sh`. It asks for:
- the domain people will open, pointed at the server
- how the certificate is made: from Let's Encrypt (the server must be
reachable from the internet on ports 80 and 443), from Caddy's own
certificate authority (a private network or VPN), or from your own CA
(`cert.pem` and `key.pem` in `server/certs/`)
- the mail server for invitations and password resets
(`smtp://user:password@host:587`, STARTTLS, or `smtps://…:465`)
It makes the database password and the secret key, writes them to
`server.env` (readable only by you), and starts Supermarket, Postgres, a
nightly backup and Caddy (`compose.server.yaml`). **Keep a copy of
`SUPERMARKET_SECRET_KEY`**: the keys and tokens in the database are encrypted
with it. Run `./install-server.sh` again after `git pull` to update.
**The first owner.** A new server prints a link to create its owner, once,
for a day (`install-server.sh` shows it; `supermarket setup-link` makes a new
one). The owner fills in the company's profile, then invites the others
under Settings → Users.
**People.** Admins can do everything; members get the modules they're given,
each to view or to edit, and see nothing else: their menu, the Overview,
Search and the SEO emails follow it, and the server refuses the rest. Each
person can turn on two-factor sign-in (an authenticator app) under Settings →
Your account, see where they're signed in, and connect their own social
accounts to post as. Sign-ins are limited per address and per IP, and an
account locks after 10 failures in a row (a password reset or an admin
unlocks it). Settings → Activity shows who did what.
**Social accounts and Search Console.** Each service's developer app needs the
server's addresses as its redirect URLs: `https://<domain>/auth/x/callback`,
`…/auth/linkedin/callback`, `…/auth/linkedin-page/callback`,
`…/auth/reddit/callback` and `…/auth/google/callback`.
**Backups.** Postgres is dumped every night at 03:00, and two weeks of dumps
are kept, in the `pgbackups` volume; Settings → Backups lists them and says
how to restore one, which is done on the server.
**A private network.** With Caddy's CA or your own, nothing on the internet
needs to reach the server; browsers need to trust the CA. Services that call
in (none yet) wouldn't reach it, so Supermarket polls instead, as on a
computer.
Hermes and the CRM bridge use the local edition's socket; on a server, agents
come with their own keys (Phase 11 in PLAN.md).
## Development
Requires Go (see `go.mod`).
+37 -2
View File
@@ -797,8 +797,8 @@ Throughout, also notice:
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
key, mail, an https:// address). With them all set, the server edition
starts (Phase 10); multi-tenant says it isn't built yet. `supermarket config` never shows a
password or the key.
- [ ] `supermarket config` also checks the file storage ("writable"), and on
the other editions that Postgres can be reached. With a wrong S3 key or
@@ -814,3 +814,38 @@ Throughout, also notice:
aren't in it. With `--with-secrets`, it says how many are, and warns.
- [ ] `supermarket import <that file>` on this install refuses: the database
isn't empty. Nothing changes.
## 14. The server edition (Phase 10)
On the local edition first:
- [ ] Nothing asks anyone to sign in; Settings has no Users or Your account.
Every form still works (each now carries a hidden `csrf` field).
- [ ] Your old X, LinkedIn and Reddit sign-ins show under Social accounts as
the company's accounts, with *Sign out*; Settings → Posting accounts
lists them. A LinkedIn draft's *Post as* lists the member and the page.
- [ ] Settings → All connections lists every service, who connected it, and
the last Test; a failing Test shows there as *Failing*.
- [ ] Settings → Activity shows what you published and deleted.
On a server (`./install-server.sh`; with Caddy's own CA on a test machine):
- [ ] The setup link from the install creates the owner and opens the
company profile; the link doesn't work twice. Before it's used, every
page says Supermarket isn't set up yet.
- [ ] Signing out and in works; a wrong password says so without saying
whether the address has an account. Five wrong tries for an address
make it wait; ten in a row lock the account and email its owner.
- [ ] *Forgotten your password?* emails a link that works once, for an hour;
afterwards the old sessions are signed out.
- [ ] Your account: turn on two-factor sign-in from the QR code; signing in
then asks for the code; a recovery code works once.
- [ ] Settings → Users: invite an admin and a member with only SEO (edit).
Both get emails; the invitation's page sets their password.
- [ ] The member sees only SEO in the menu and on the Overview; every
other module and Settings answer *No access*. With SEO as *view*,
SEO's pages show their forms greyed, without buttons.
- [ ] The member connects their own X under Your account and posts as it;
they can't choose the company's account until it's ticked for them on
Settings → Posting accounts.
- [ ] Settings → Activity shows each step above, with who and from where.
- [ ] Settings → Backups lists the nightly dump the morning after.
+18 -8
View File
@@ -252,9 +252,12 @@ func run(log *slog.Logger) error {
// 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.
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)
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
@@ -352,11 +355,15 @@ func run(log *slog.Logger) error {
srv.Restart = stop
errCh := make(chan error, 2)
go func() {
if err := mcpserver.ServeSocket(ctx, database, version, mcpSocket, log); err != nil {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
// 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)
@@ -370,6 +377,9 @@ func run(log *slog.Logger) error {
// 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 {
+116
View File
@@ -0,0 +1,116 @@
# Supermarket's server edition: one team, signing in, on its own domain.
# install-server.sh writes server.env (the domain, the mail server, the
# secret key and the database password) and starts it:
#
# docker compose -f compose.server.yaml --env-file server.env up -d --build
#
# Caddy answers on ports 80 and 443 and gets the certificate; Supermarket
# itself is published only to Caddy, on the compose network.
name: supermarket-server
services:
supermarket:
build:
context: .
args:
VERSION: ${SUPERMARKET_VERSION:-dev}
image: supermarket:server
restart: unless-stopped
init: true
user: "10001:10001"
environment:
SUPERMARKET_MODE: server
SUPERMARKET_PUBLIC_URL: https://${SUPERMARKET_DOMAIN:?}${SUPERMARKET_PUBLIC_PORT:-}
SUPERMARKET_DATABASE_URL: postgres://supermarket:${SUPERMARKET_DB_PASSWORD:?}@db:5432/supermarket?sslmode=disable
SUPERMARKET_SECRET_KEY: ${SUPERMARKET_SECRET_KEY:?}
SUPERMARKET_MAIL_URL: ${SUPERMARKET_MAIL_URL:?}
SUPERMARKET_MAIL_FROM: ${SUPERMARKET_MAIL_FROM:-}
SUPERMARKET_PG_BACKUPS: /backups
TZ: ${SUPERMARKET_TZ:-UTC}
volumes:
- appdata:/data # scratch: the sites' clones and previews
- pgbackups:/backups:ro # the nightly dumps, for Settings → Backups
depends_on:
db:
condition: service_healthy
networks: [internal, web]
read_only: true
tmpfs:
- /tmp
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
db:
image: postgres:18-alpine
restart: unless-stopped
environment:
POSTGRES_DB: supermarket
POSTGRES_USER: supermarket
POSTGRES_PASSWORD: ${SUPERMARKET_DB_PASSWORD:?}
volumes:
- pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD", "pg_isready", "-U", "supermarket", "-d", "supermarket"]
interval: 5s
timeout: 5s
retries: 20
networks: [internal]
# A dump of the database every night at 03:00 (the server's TZ), kept for
# two weeks: supermarket-YYYY-MM-DD.dump, in pg_dump's custom format.
# Restoring is the operator's: see server/README.md.
backup:
image: postgres:18-alpine
restart: unless-stopped
environment:
PGHOST: db
PGUSER: supermarket
PGDATABASE: supermarket
PGPASSWORD: ${SUPERMARKET_DB_PASSWORD:?}
TZ: ${SUPERMARKET_TZ:-UTC}
volumes:
- pgbackups:/backups
- ./server/backup.sh:/usr/local/bin/backup.sh:ro
entrypoint: ["/bin/sh", "/usr/local/bin/backup.sh"]
depends_on:
db:
condition: service_healthy
networks: [internal]
caddy:
image: caddy:2-alpine
restart: unless-stopped
ports:
- "${SUPERMARKET_HTTP_PORT:-80}:80"
- "${SUPERMARKET_HTTPS_PORT:-443}:443"
- "${SUPERMARKET_HTTPS_PORT:-443}:443/udp"
environment:
SUPERMARKET_DOMAIN: ${SUPERMARKET_DOMAIN:?}
# "email you@example.com", for Let's Encrypt's notices; or empty.
SUPERMARKET_ACME: ${SUPERMARKET_ACME:-}
# Empty: a certificate from Let's Encrypt (the server must be reachable
# from the internet on ports 80 and 443). "tls internal": Caddy's own
# CA, for a private network or VPN. "tls /certs/cert.pem
# /certs/key.pem": your own CA's certificate, put in server/certs/.
SUPERMARKET_TLS: ${SUPERMARKET_TLS:-}
volumes:
- ./server/Caddyfile:/etc/caddy/Caddyfile:ro
- ./server/certs:/certs:ro
- caddydata:/data
- caddyconfig:/config
depends_on: [supermarket]
networks: [web]
volumes:
appdata:
pgdata:
pgbackups:
caddydata:
caddyconfig:
networks:
internal:
internal: true # the database has no way out
web:
+118
View File
@@ -0,0 +1,118 @@
#!/bin/bash
#
# Purpose : Install Supermarket's server edition on this machine: one team,
# signing in, at its own domain, with Postgres and Caddy (HTTPS),
# all in Docker (compose.server.yaml). Safe to run again: it keeps
# the settings it wrote, and only rebuilds and restarts.
#
# Usage : ./install-server.sh
#
# It asks for the domain, how the certificate is made, and the mail server
# (for invitations and password resets), and makes the secret key and the
# database password. They go in server.env, readable only by you: keep a
# copy of SUPERMARKET_SECRET_KEY somewhere safe, as nothing encrypted in the
# database can be read without it.
set -euo pipefail
cd "$(dirname "${BASH_SOURCE[0]}")"
ENV_FILE=server.env
COMPOSE=(docker compose -f compose.server.yaml --env-file "$ENV_FILE")
if ! command -v docker > /dev/null || ! docker compose version > /dev/null 2>&1; then
echo "Supermarket's server edition needs Docker with the compose plugin."
exit 1
fi
if ! docker info > /dev/null 2>&1; then
echo "Docker isn't running, or you can't use it: start it, or run this as a user in the docker group."
exit 1
fi
ask() { # ask <prompt> [default]
local answer
if [ -n "${2:-}" ]; then
read -r -p "$1 [$2]: " answer
echo "${answer:-$2}"
else
while [ -z "${answer:-}" ]; do read -r -p "$1: " answer; done
echo "$answer"
fi
}
random_hex() { head -c "$1" /dev/urandom | od -An -tx1 | tr -d ' \n'; }
if [ -f "$ENV_FILE" ]; then
echo "Using the settings in $ENV_FILE (delete it to start again)."
else
echo "Supermarket's server edition: a team signs in to it at its own address."
echo
domain=$(ask "The domain people will open (e.g. supermarket.example.com)")
echo
echo "The HTTPS certificate:"
echo " 1) From Let's Encrypt: this server can be reached from the internet on ports 80 and 443 (the usual)"
echo " 2) Caddy's own certificate authority: a private network or VPN (browsers will warn until you trust its root)"
echo " 3) Your own certificate authority's: put cert.pem and key.pem in server/certs/"
tls_choice=$(ask "Which" "1")
tls="" acme=""
case "$tls_choice" in
2) tls="tls internal" ;;
3) tls="tls /certs/cert.pem /certs/key.pem" ;;
*) email=$(ask "An email for Let's Encrypt's notices (or leave empty)" "-")
[ "$email" != "-" ] && acme="email $email" ;;
esac
echo
echo "The mail server Supermarket sends invitations and password resets through,"
echo "as smtp://user:password@host:587 (STARTTLS) or smtps://user:password@host:465."
echo "Write @ in the user name as %40."
mail=$(ask "Mail server")
from=$(ask "Send as" "Supermarket <no-reply@$domain>")
tz=$(ask "Time zone" "$(cat /etc/timezone 2>/dev/null || echo UTC)")
umask 077
cat > "$ENV_FILE" <<EOF
# Supermarket's server edition (install-server.sh). Readable only by you.
SUPERMARKET_DOMAIN=$domain
SUPERMARKET_TLS=$tls
SUPERMARKET_ACME=$acme
SUPERMARKET_MAIL_URL='$mail'
SUPERMARKET_MAIL_FROM='$from'
SUPERMARKET_TZ=$tz
SUPERMARKET_DB_PASSWORD=$(random_hex 24)
# Keep a copy of this key somewhere safe: the keys and tokens in the
# database are encrypted with it, and can't be read without it.
SUPERMARKET_SECRET_KEY=$(random_hex 32)
SUPERMARKET_VERSION=$(git describe --tags --always --dirty 2>/dev/null || echo dev)
EOF
echo
echo "Wrote $ENV_FILE. Keep a copy of its SUPERMARKET_SECRET_KEY somewhere safe."
fi
# The version, from git, each time.
if version=$(git describe --tags --always --dirty 2>/dev/null); then
sed -i "s/^SUPERMARKET_VERSION=.*/SUPERMARKET_VERSION=$version/" "$ENV_FILE"
fi
echo "Building and starting Supermarket, Postgres and Caddy…"
"${COMPOSE[@]}" up -d --build
echo "Waiting for Supermarket to start…"
for _ in $(seq 1 60); do
if "${COMPOSE[@]}" exec -T supermarket wget -q -O /dev/null http://127.0.0.1:8080/healthz 2> /dev/null; then
break
fi
sleep 2
done
domain=$(grep '^SUPERMARKET_DOMAIN=' "$ENV_FILE" | cut -d= -f2-)
if link=$("${COMPOSE[@]}" exec -T supermarket supermarket setup-link 2> /dev/null | tail -1) && [[ "$link" == https://* ]]; then
echo
echo "Supermarket is running. To create its owner, open this link (it works once, for a day):"
echo " $link"
else
echo
echo "Supermarket is running at https://$domain"
fi
echo
echo "Its logs: docker compose -f compose.server.yaml --env-file $ENV_FILE logs -f supermarket"
echo "Its settings: docker compose -f compose.server.yaml --env-file $ENV_FILE exec supermarket supermarket config"
echo "To update: git pull && ./install-server.sh"
+5 -1
View File
@@ -93,7 +93,8 @@ type Config struct {
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
Mail *Mail // nil if not set
PGBackups string // where the server's nightly dumps are, to list them; "" if not known
}
// Environment variables.
@@ -115,6 +116,7 @@ const (
EnvS3SecretKey = "SUPERMARKET_S3_SECRET_KEY"
EnvMailURL = "SUPERMARKET_MAIL_URL"
EnvMailFrom = "SUPERMARKET_MAIL_FROM"
EnvPGBackups = "SUPERMARKET_PG_BACKUPS"
)
// Load reads the settings through getenv (os.Getenv) and checks them. All
@@ -208,6 +210,8 @@ func Load(getenv func(string) string) (*Config, error) {
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, "")
if len(problems) > 0 {
return c, errors.New(strings.Join(problems, "\n"))
}
+50
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -59,6 +60,10 @@ func (s *Server) backupsPage(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, flash string) {
if s.DB.Dialect != db.SQLite {
s.renderServerBackups(w, r)
return
}
bs, err := backup.List(s.backupDir())
if err != nil {
s.serverError(w, err)
@@ -82,6 +87,10 @@ func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, f
}
func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
if s.DB.Dialect != db.SQLite {
http.NotFound(w, r) // the operator backs Postgres up, and restores it
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
@@ -124,6 +133,10 @@ func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
// data (not its secrets), so it's served to this machine only, like
// everything else here.
func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) {
if s.DB.Dialect != db.SQLite {
http.NotFound(w, r)
return
}
b, err := backup.Find(s.backupDir(), r.PathValue("name"))
if err != nil {
http.NotFound(w, r)
@@ -208,3 +221,40 @@ func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) {
}
s.renderBackups(w, r, "", "Uploaded as "+b.Name+". Restore it from the list when you're ready.")
}
// dump is one of the server's nightly database dumps.
type dump struct {
Name string
Size int64
At time.Time
}
// renderServerBackups lists the nightly dumps of Postgres (compose.server.yaml's
// backup service), newest first, and how the operator restores one.
func (s *Server) renderServerBackups(w http.ResponseWriter, r *http.Request) {
data := map[string]any{"Dir": ""}
if s.Config != nil && s.Config.PGBackups != "" {
data["Dir"] = s.Config.PGBackups
entries, err := os.ReadDir(s.Config.PGBackups)
if err != nil {
data["Err"] = err.Error()
}
var dumps []dump
var total int64
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".dump") {
continue
}
if fi, err := e.Info(); err == nil {
dumps = append(dumps, dump{Name: e.Name(), Size: fi.Size(), At: fi.ModTime()})
total += fi.Size()
}
}
sort.Slice(dumps, func(i, j int) bool { return dumps[i].At.After(dumps[j].At) })
data["Dumps"], data["Total"] = dumps, total
if len(dumps) > 0 && time.Since(dumps[0].At) > 36*time.Hour {
data["Stale"] = dumps[0].At
}
}
s.render(w, r, "backups-server", page{Title: "Backups", Nav: "settings/backups", Data: data})
}
+21
View File
@@ -14,6 +14,7 @@ import (
"time"
"supermarket/internal/backup"
"supermarket/internal/users"
)
func TestBackupsPage(t *testing.T) {
@@ -125,3 +126,23 @@ func TestBackupUpload(t *testing.T) {
t.Errorf("temporary files left: %v", left)
}
}
func TestServerBackupsPage(t *testing.T) {
if !db.OnPostgres() {
t.Skip("the server's backups page is Postgres's")
}
s, h := newServerEdition(t)
dir := t.TempDir()
s.Config.PGBackups = dir
os.WriteFile(filepath.Join(dir, "supermarket-2026-11-24.dump"), []byte("x"), 0o600)
os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("x"), 0o600)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
c := sessionFor(t, s, owner)
body := as(h, c, http.MethodGet, "/settings/backups", nil).Body.String()
if !strings.Contains(body, "supermarket-2026-11-24.dump") || strings.Contains(body, "notes.txt") || !strings.Contains(body, "pg_restore") {
t.Errorf("page: %s", body)
}
if rec := as(h, c, http.MethodPost, "/settings/backups/now", url.Values{}); rec.Code != http.StatusNotFound {
t.Errorf("back up now on Postgres: %d", rec.Code)
}
}
@@ -0,0 +1,29 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>Backups</h2>
<p class="lede">Supermarket's database is Postgres, on the server. It's dumped every night at 03:00, and two weeks of dumps are kept. Keys and tokens are in it too, encrypted with the server's secret key: a dump restored elsewhere needs that key as well.</p>
{{if not .Dir}}
<section class="card warn"><p>Supermarket doesn't know where the dumps are (<code>SUPERMARKET_PG_BACKUPS</code>). With <code>compose.server.yaml</code>, they're in the <code>pgbackups</code> volume; whoever runs Postgres otherwise backs it up their own way.</p></section>
{{else}}
{{with .Err}}<p class="error">The dumps can't be read: {{.}}</p>{{end}}
{{with .Stale}}<p class="error">The last dump is from {{.Local.Format "2 Jan 2006"}}: the nightly backup isn't working. Check the backup service's log on the server.</p>{{end}}
{{if .Dumps}}
<p class="small">{{len .Dumps}} dump{{if ne (len .Dumps) 1}}s{{end}}, {{bytes .Total}} in all.</p>
<div class="table-wrap"><table>
<thead><tr><th>Made</th><th>File</th><th class="num">Size</th></tr></thead>
<tbody>{{range .Dumps}}<tr><td>{{.At.Local.Format "2 Jan 2006, 15:04"}}<br><span class="small muted">{{ago .At}}</span></td><td><code>{{.Name}}</code></td><td class="num">{{bytes .Size}}</td></tr>{{end}}</tbody>
</table></div>
{{else if not .Err}}<section class="card empty"><p>No dumps yet: the first is made when the backup service starts.</p></section>{{end}}
{{end}}
<section class="card">
<h2>Restoring</h2>
<p>Restoring is done on the server, by whoever runs it, so that no one can undo the team's work from a browser. Stop Supermarket, restore the dump over the database, and start it again:</p>
<pre id="restore">docker compose -f compose.server.yaml --env-file server.env stop supermarket
docker compose -f compose.server.yaml --env-file server.env exec backup \
pg_restore --clean --if-exists --no-owner -d supermarket /backups/supermarket-YYYY-MM-DD.dump
docker compose -f compose.server.yaml --env-file server.env start supermarket</pre>
<button type="button" class="secondary small" data-copy="restore">Copy</button>
<p class="help">To move to another server, <code>supermarket export</code> and <code>supermarket import</code> work too, from either database to either.</p>
</section>
{{end}}{{template "settings-end"}}{{end}}
+15
View File
@@ -0,0 +1,15 @@
# Caddy in front of Supermarket's server edition (compose.server.yaml).
# SUPERMARKET_ACME and SUPERMARKET_TLS are whole lines, or nothing (see
# compose.server.yaml); Caddy fills them in before reading this file.
{
{$SUPERMARKET_ACME}
}
{$SUPERMARKET_DOMAIN} {
{$SUPERMARKET_TLS}
encode zstd gzip
header Strict-Transport-Security "max-age=31536000"
# Caddy sets X-Forwarded-For to the client's address (it ignores what the
# client sent), which Supermarket's sign-in limits use.
reverse_proxy supermarket:8080
}
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Dumps Supermarket's database every night at 03:00, and keeps 14 days of
# dumps. Runs in the backup service of compose.server.yaml.
set -u
cd /backups || exit 1
umask 077
while true; do
now=$(date +%s)
next=$(date -d "$(date +%Y-%m-%d) 03:00" +%s 2>/dev/null || date -D "%Y-%m-%d %H:%M" -d "$(date +%Y-%m-%d) 03:00" +%s)
[ "$next" -le "$now" ] && next=$((next + 86400))
# The first dump right away, if there's none yet.
if ls supermarket-*.dump > /dev/null 2>&1; then
sleep $((next - now))
fi
name="supermarket-$(date +%Y-%m-%d).dump"
if pg_dump --format=custom --file="$name.part" && mv "$name.part" "$name"; then
echo "backup: wrote $name"
else
echo "backup: pg_dump failed" >&2
rm -f "$name.part"
sleep 600
continue
fi
find /backups -name 'supermarket-*.dump' -mtime +14 -delete
sleep 60
done
View File