Files
supermarket/internal/db/migrations.go
T
davidandClaude Opus 5.5 96404a3580 Phase 10, part 1: users, sessions and form tokens
Schema 32 adds users, memberships and sessions, on both databases.
internal/users keeps accounts (Argon2id passwords), roles and modules,
and sessions whose rows hold only a hash of the cookie's value; they end
after a week unused or 30 days. On the server edition, every page but the
public ones needs a session and sends others to /signin. Every edition's
forms now carry a CSRF token (a cookie repeated in each form, added as
pages render; htmx sends it as a header), besides the same-origin check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 08:49:45 -07:00

154 lines
5.8 KiB
Go

package db
import (
"fmt"
"regexp"
"strings"
)
// Migration is a change to the schema from schema 30 on, for both
// databases. It's written once, in SQLite's SQL; Postgres gets the same
// statements with SQLite's types and defaults translated (see PostgresSQL).
// A migration that changes data with SQL only SQLite has gives Postgres
// its own.
//
// Never edit or reorder one that has shipped: add a new one instead.
type Migration struct {
Note string // what it does, for the record (Postgres' schema_migrations)
SQLite string
Postgres string // empty: PostgresSQL(SQLite)
}
// both are the migrations after schema 29, on both databases: schema 30
// is both[0]. (migrations, before them, are SQLite's own; Postgres starts
// from postgres.sql, which is schema 29 as a whole.)
var both = []Migration{
// 30
{
Note: "secrets kept in the database, encrypted (server and multi-tenant editions)",
SQLite: `
CREATE TABLE secrets (
name TEXT PRIMARY KEY,
value TEXT NOT NULL, -- v1:<base64 of the nonce and the sealed value>, AES-256-GCM
key_id TEXT NOT NULL, -- which key sealed it: a fingerprint, never the key
updated_at TEXT NOT NULL
);
`,
},
// 31
{
Note: "copies of the app, and the locks that let only one of them do a job",
SQLite: `
CREATE TABLE instances (
id TEXT PRIMARY KEY, -- a copy of the app, while it runs
host TEXT NOT NULL DEFAULT '',
version TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL,
seen_at TEXT NOT NULL -- its last check-in (every 30 seconds)
);
CREATE TABLE locks (
name TEXT PRIMARY KEY, -- the work, e.g. job:seo, outreach:send, audit:<site>
holder TEXT NOT NULL DEFAULT '', -- <instance>:<random>, or '' when free
taken_at TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL DEFAULT '' -- renewed while the work runs; free after it
);
`,
},
// 32
{
Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)",
SQLite: `
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
name TEXT NOT NULL DEFAULT '',
kind TEXT NOT NULL DEFAULT 'person', -- person or agent
status TEXT NOT NULL DEFAULT 'invited', -- invited, active or disabled
password_hash TEXT NOT NULL DEFAULT '', -- Argon2id, in the PHC string format; '' for none
title TEXT NOT NULL DEFAULT '',
time_zone TEXT NOT NULL DEFAULT '', -- an IANA name, such as Europe/Paris
photo TEXT NOT NULL DEFAULT '', -- a name in the file storage
emails TEXT NOT NULL DEFAULT '[]', -- the emails they want, as a JSON list
created_at TEXT NOT NULL,
signed_in_at TEXT NOT NULL DEFAULT '' -- their last sign-in
);
CREATE TABLE memberships (
team_id INTEGER NOT NULL DEFAULT 1, -- one team until the multi-tenant edition
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role TEXT NOT NULL, -- owner, admin or member
modules TEXT NOT NULL DEFAULT '{}', -- a member's modules: {"seo":"edit","metrics":"view"}
created_at TEXT NOT NULL,
PRIMARY KEY (team_id, user_id)
);
CREATE TABLE sessions (
id TEXT PRIMARY KEY, -- the SHA-256 of the cookie's random ID, never the ID itself
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TEXT NOT NULL,
seen_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
ip TEXT NOT NULL DEFAULT '',
user_agent TEXT NOT NULL DEFAULT ''
);
CREATE INDEX sessions_user ON sessions(user_id);
`,
},
}
// Schema is the schema version this build migrates databases to.
func Schema() int { return len(migrations) + len(both) }
// sqliteStep is the SQL that takes SQLite from schema i to i+1.
func sqliteStep(i int) string {
if i < len(migrations) {
return migrations[i]
}
return both[i-len(migrations)].SQLite
}
// postgresStep is the migration that takes Postgres from schema i to i+1
// (i is pgBaseline or later).
func postgresStep(i int) (Migration, string) {
m := both[i-pgBaseline]
if m.Postgres != "" {
return m, m.Postgres
}
return m, PostgresSQL(m.SQLite)
}
var (
ddlIntegerKey = regexp.MustCompile(`(?i)\bINTEGER\s+PRIMARY\s+KEY\b`)
ddlInteger = regexp.MustCompile(`(?i)\bINTEGER\b`)
ddlReal = regexp.MustCompile(`(?i)\bREAL\b`)
ddlBlob = regexp.MustCompile(`(?i)\bBLOB\b`)
ddlNow = regexp.MustCompile(`(?i)strftime\('%Y-%m-%dT%H:%M:%SZ',\s*'now'\)`)
// A column whose COLLATE comes after its constraints: Postgres wants it
// right after the type.
ddlCollateLate = regexp.MustCompile(`(?i)\bTEXT((?:\s+(?:NOT\s+NULL|UNIQUE|PRIMARY\s+KEY|DEFAULT\s+(?:'(?:[^']|'')*'|\([^)]*\)|[^\s,]+)))+)\s+COLLATE\s+NOCASE\b`)
ddlCollate = regexp.MustCompile(`(?i)\bCOLLATE\s+NOCASE\b`)
)
// PostgresSQL translates SQLite's DDL (CREATE TABLE, CREATE INDEX, ALTER
// TABLE … ADD COLUMN) to Postgres': 64-bit integers, identity keys,
// doubles, the nocase collation in its place, and timestamps from now().
func PostgresSQL(sqlite string) string {
s := ddlIntegerKey.ReplaceAllString(sqlite, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY")
s = ddlInteger.ReplaceAllString(s, "BIGINT")
s = ddlReal.ReplaceAllString(s, "DOUBLE PRECISION")
s = ddlBlob.ReplaceAllString(s, "BYTEA")
s = ddlNow.ReplaceAllString(s, `to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`)
s = ddlCollateLate.ReplaceAllString(s, "TEXT COLLATE nocase$1")
s = ddlCollate.ReplaceAllString(s, "COLLATE nocase")
return s
}
// checkMigrations catches a mistake in the list before it reaches a
// database: an empty step.
func checkMigrations() error {
for i, m := range both {
if strings.TrimSpace(m.SQLite) == "" || strings.TrimSpace(m.Note) == "" {
return fmt.Errorf("migration %d needs its SQLite SQL and a note", len(migrations)+i+1)
}
}
return nil
}