Files
CollabTable/backend/db.go
T

353 lines
13 KiB
Go
Raw Normal View History

package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
2026-08-04 17:05:37 +02:00
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
// DB owns the PostgreSQL pool. The schema deliberately uses the same physical
// column names as the existing Node service: PostgreSQL lowercases unquoted
// camelCase identifiers, so createdAt is stored as createdat, etc.
type DB struct {
pool *pgxpool.Pool
}
func connectDB(ctx context.Context, connectionString string) (*DB, error) {
2026-08-04 17:05:37 +02:00
pool, err := sharedpostgres.Open(ctx, sharedpostgres.DefaultConfig(connectionString))
if err != nil {
2026-08-04 17:05:37 +02:00
return nil, err
}
return &DB{pool: pool}, nil
}
func (d *DB) close() {
d.pool.Close()
}
func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
2026-08-04 17:05:37 +02:00
return sharedpostgres.WithTx(ctx, d.pool, fn)
}
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
// be used by the Go server without a separate migration step.
func (d *DB) initSchema(ctx context.Context) error {
_, err := d.pool.Exec(ctx, `
CREATE TABLE IF NOT EXISTS lists (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
createdat BIGINT NOT NULL,
updatedat BIGINT NOT NULL,
isdeleted INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS fields (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
fieldtype TEXT NOT NULL,
fieldoptions TEXT,
alignment TEXT NOT NULL DEFAULT 'start',
listid TEXT NOT NULL,
"order" INTEGER NOT NULL,
createdat BIGINT NOT NULL,
updatedat BIGINT NOT NULL,
isdeleted INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (listid) REFERENCES lists(id)
);
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY,
listid TEXT NOT NULL,
createdat BIGINT NOT NULL,
updatedat BIGINT NOT NULL,
isdeleted INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (listid) REFERENCES lists(id)
);
CREATE TABLE IF NOT EXISTS item_values (
id TEXT PRIMARY KEY,
itemid TEXT NOT NULL,
fieldid TEXT NOT NULL,
value TEXT,
updatedat BIGINT NOT NULL,
FOREIGN KEY (itemid) REFERENCES items(id),
FOREIGN KEY (fieldid) REFERENCES fields(id)
);
CREATE INDEX IF NOT EXISTS idx_fields_listid ON fields(listid);
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
CREATE TABLE IF NOT EXISTS notifications (
id TEXT PRIMARY KEY,
deviceidorigin TEXT,
eventtype TEXT NOT NULL,
entitytype TEXT NOT NULL,
entityid TEXT,
listid TEXT,
createdat BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_notifications_createdat ON notifications(createdat);
CREATE INDEX IF NOT EXISTS idx_notifications_listid ON notifications(listid);
ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';
-- auth_users/auth_sessions are RETIRED as of the AuthGuard migration:
-- account and session state now lives in AuthGuard's own database,
-- reached over HTTP via authclient (see auth.go). These two tables and
-- their schema are deliberately left in place rather than dropped --
-- dropping tables/data is a separate, more destructive decision outside
-- the scope of that migration -- but no Go code reads or writes them for
-- authentication purposes anymore. pruneExpiredSessions keeps running
-- only as harmless best-effort cleanup of whatever rows a pre-migration
-- deployment already had.
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
email TEXT NOT NULL DEFAULT '',
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
DROP INDEX IF EXISTS auth_users_singleton_idx;
CREATE TABLE IF NOT EXISTS auth_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions(expires_at);
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions(user_id);
-- collabtable_setup_state tracks only whether THIS CollabTable instance
-- has completed its one-time "create the first account" setup flow
-- against AuthGuard (see handleSetup in auth.go). It intentionally holds
-- no credentials or account identity of its own -- AuthGuard is the sole
-- source of truth for accounts -- just the boolean that used to be
-- derived from "COUNT(*) FROM auth_users" before the migration.
CREATE TABLE IF NOT EXISTS collabtable_setup_state (
id SMALLINT PRIMARY KEY DEFAULT 1,
claimed BOOLEAN NOT NULL DEFAULT FALSE,
claimed_at TIMESTAMPTZ,
CHECK (id = 1)
);
-- authguard_totp_cache is a best-effort, locally-cached mirror of "does
-- this AuthGuard account have TOTP enabled", keyed by AuthGuard's own
-- numeric user id. AuthGuard's HTTP API (deliberately not modified by
-- this migration) has no endpoint to query current TOTP status, only to
-- enable/verify/disable it, so CollabTable keeps this cache updated
-- itself at every point it can observe the true state (successful TOTP
-- verify/disable calls, and a successful login attempted without a TOTP
-- token, which AuthGuard would have rejected had TOTP been enabled). See
-- handleTOTPStatus's doc comment in auth.go for the full reasoning and
-- its known staleness caveat.
CREATE TABLE IF NOT EXISTS authguard_totp_cache (
authguard_user_id BIGINT PRIMARY KEY,
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- api_tokens backs the long-lived per-account bearer token CollabTable's
-- own devices use for the sync API (requireAPIToken in auth.go) -- a
-- concern entirely separate from browser-session auth, so it is NOT
-- proxied to AuthGuard. Its user_id used to be a foreign key into this
-- database's own auth_users; now that account identity lives in
-- AuthGuard (or, when AUTHGUARD_URL is unset, every caller shares the
-- fixed placeholder id 0 -- see localProfile/currentUserID in auth.go),
-- user_id is just an opaque identity id with no matching row in the
-- (now dormant) local auth_users table, so the FK constraint a
-- pre-migration deployment already has is dropped below.
CREATE TABLE IF NOT EXISTS api_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
`)
if err != nil {
return fmt.Errorf("initialize schema: %w", err)
}
return nil
}
func (d *DB) pruneExpiredSessions(ctx context.Context) {
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
fmt.Printf("[db] session prune failed: %v\n", err)
}
}
}
}
func (d *DB) cleanupNotifications(ctx context.Context) {
retention := envInt64("NOTIF_RETENTION_MS", 7*24*60*60*1000)
if retention < 0 {
retention = 0
}
ticker := time.NewTicker(time.Hour)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
cutoff := time.Now().UnixMilli() - retention
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
fmt.Printf("[db] notification cleanup failed: %v\n", err)
}
}
}
}
// --- AuthGuard migration: local-only auxiliary state ------------------------
//
// Everything below is new state introduced by the AuthGuard migration. None
// of it is account/credential data -- that all lives in AuthGuard now -- it
// is bookkeeping CollabTable keeps about itself. See auth.go for how each is
// used.
// IsSetupClaimed reports whether this CollabTable instance has already
// completed its one-time setup flow (see TryClaimSetup).
func (d *DB) IsSetupClaimed(ctx context.Context) (bool, error) {
var claimed bool
err := d.pool.QueryRow(ctx, `SELECT claimed FROM collabtable_setup_state WHERE id = 1`).Scan(&claimed)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("check setup claim: %w", err)
}
return claimed, nil
}
// TryClaimSetup atomically flips the local "setup completed" flag from
// unclaimed to claimed and reports whether this call was the one that did so.
// A caller that wins the claim but then fails to actually create the
// AuthGuard account (e.g. a validation error, or AuthGuard being unreachable)
// must call UnclaimSetup to reopen the slot for a later retry.
func (d *DB) TryClaimSetup(ctx context.Context) (bool, error) {
tag, err := d.pool.Exec(ctx, `
INSERT INTO collabtable_setup_state (id, claimed, claimed_at) VALUES (1, TRUE, now())
ON CONFLICT (id) DO UPDATE SET claimed = TRUE, claimed_at = now()
WHERE collabtable_setup_state.claimed = FALSE
`)
if err != nil {
return false, fmt.Errorf("claim setup: %w", err)
}
return tag.RowsAffected() > 0, nil
}
// UnclaimSetup reopens the setup flow after a claimed-but-failed setup
// attempt (see TryClaimSetup).
func (d *DB) UnclaimSetup(ctx context.Context) error {
if _, err := d.pool.Exec(ctx, `UPDATE collabtable_setup_state SET claimed = FALSE, claimed_at = NULL WHERE id = 1`); err != nil {
return fmt.Errorf("unclaim setup: %w", err)
}
return nil
}
// ClearSetupClaim resets the local "setup completed" flag so the setup screen
// reappears. Used by the local break-glass password-reset flow (see
// handleResetConfirm in auth.go) -- it deliberately does not touch the
// underlying AuthGuard account at all.
func (d *DB) ClearSetupClaim(ctx context.Context) error {
return d.UnclaimSetup(ctx)
}
// GetCachedTOTPEnabled returns the best-effort locally-cached TOTP-enabled
// state for an AuthGuard account, or false if this instance has never
// observed that account's TOTP state. See handleTOTPStatus's doc comment in
// auth.go.
func (d *DB) GetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64) (bool, error) {
var enabled bool
err := d.pool.QueryRow(ctx, `SELECT totp_enabled FROM authguard_totp_cache WHERE authguard_user_id = $1`, authGuardUserID).Scan(&enabled)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("get cached totp state: %w", err)
}
return enabled, nil
}
// SetCachedTOTPEnabled upserts the best-effort locally-cached TOTP-enabled
// state for an AuthGuard account.
func (d *DB) SetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64, enabled bool) error {
_, err := d.pool.Exec(ctx, `
INSERT INTO authguard_totp_cache (authguard_user_id, totp_enabled, updated_at) VALUES ($1, $2, now())
ON CONFLICT (authguard_user_id) DO UPDATE SET totp_enabled = $2, updated_at = now()
`, authGuardUserID, enabled)
if err != nil {
return fmt.Errorf("set cached totp state: %w", err)
}
return nil
}
func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) {
var exists bool
if err := d.pool.QueryRow(ctx, `
SELECT EXISTS(SELECT 1 FROM api_tokens WHERE user_id = $1)
`, userID).Scan(&exists); err != nil {
return false, fmt.Errorf("check API token: %w", err)
}
return exists, nil
}
func (d *DB) regenerateAPIToken(ctx context.Context, userID int64, tokenHash string) error {
return d.withTx(ctx, func(tx pgx.Tx) error {
if _, err := tx.Exec(ctx, `DELETE FROM api_tokens WHERE user_id = $1`, userID); err != nil {
return fmt.Errorf("delete old API token: %w", err)
}
if _, err := tx.Exec(ctx, `
INSERT INTO api_tokens (user_id, token_hash)
VALUES ($1, $2)
`, userID, tokenHash); err != nil {
return fmt.Errorf("insert API token: %w", err)
}
return nil
})
}
func (d *DB) getAPITokenUserID(ctx context.Context, tokenHash string) (int64, error) {
var userID int64
err := d.pool.QueryRow(ctx, `
SELECT user_id FROM api_tokens WHERE token_hash = $1
`, tokenHash).Scan(&userID)
if errors.Is(err, pgx.ErrNoRows) {
return 0, nil
}
if err != nil {
return 0, fmt.Errorf("get API token owner: %w", err)
}
return userID, nil
}