Replaces the ~1044-line bespoke session/login/TOTP/admin-user proxy
(backend/auth.go, built directly on authclient) with
sharedauth.NewWithStore, the same shared engine GameStream and
OmniLogger already migrated onto. A tiny collabTableAuthStore adapter
delegates the local one-time setup-claim flag to the existing
collabtable_setup_state table/queries; CollabTable never had a
"require login" toggle, so LoginRequired always reports true and
SetLoginRequired is a no-op.
The local authguard_totp_cache (GetCachedTOTPEnabled/
SetCachedTOTPEnabled) is retired: the shared engine reads TOTP status
live from AuthGuard's GET /api/me. Its table is left in place, same as
the already-dormant auth_users/auth_sessions tables.
URL paths and HTTP methods are unchanged; only response shapes
changed to the shared engine's standardized ones (nested `user: {...}`,
`data: {...}` for TOTP setup/enable/disable). Updated
frontend/src/lib/api.js to translate these back into the shapes the
rest of the frontend already expects, and AppShell.svelte's
saveProfile to always send the current username/email (UpdateMe
requires a non-empty email on every call).
Known behavior differences: POST /api/auth/setup now returns 201
instead of 200; PUT/PATCH /api/auth/users/{id} now returns the updated
user instead of {"ok":true}; POST /api/auth/credentials no longer
forces re-login after a successful change (no bulk session-invalidation
call exists in the shared engine, only single-session Logout).
The separate device/sync API bearer-token scheme (requireAPIToken,
handleTokenStatus/handleTokenRegenerate) is untouched other than
resolving the caller's identity via sharedauth.UserFromContext instead
of local session lookups.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
328 lines
12 KiB
Go
328 lines
12 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
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) {
|
|
pool, err := sharedpostgres.Open(ctx, sharedpostgres.DefaultConfig(connectionString))
|
|
if err != nil {
|
|
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 {
|
|
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 RETIRED as of the migration onto
|
|
-- shared/backend/auth (sharedauth.Service): it used to be a
|
|
-- best-effort, locally-cached mirror of "does this AuthGuard account
|
|
-- have TOTP enabled", keyed by AuthGuard's own numeric user id, needed
|
|
-- because AuthGuard's HTTP API had no endpoint to query current TOTP
|
|
-- status, only to enable/verify/disable it. sharedauth.Service's
|
|
-- Me/Status/TOTPStatus now read TOTP-enabled status live from
|
|
-- AuthGuard's GET /api/me on every request instead, so no Go code
|
|
-- reads or writes this table anymore. Left in place rather than
|
|
-- dropped, same as auth_users/auth_sessions above.
|
|
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
|
|
}
|
|
|
|
// Note: this instance used to also keep a local best-effort cache of each
|
|
// AuthGuard account's TOTP-enabled state (GetCachedTOTPEnabled/
|
|
// SetCachedTOTPEnabled, backed by the authguard_totp_cache table above) --
|
|
// that existed only because the pre-migration code believed AuthGuard could
|
|
// not report TOTP status live. It can (GET /api/me), so sharedauth.Service's
|
|
// Me/Status/TOTPStatus now read it live from AuthGuard directly and this
|
|
// cache's Go code was deleted along with the migration onto that shared
|
|
// package. The authguard_totp_cache table itself (and any rows already in
|
|
// it) is left in place rather than dropped, same as auth_users/auth_sessions
|
|
// above.
|
|
|
|
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
|
|
}
|