package db import ( "context" "database/sql" "encoding/json" "errors" "strings" "time" "github.com/andrew/superbrain/internal/config" "github.com/andrew/superbrain/internal/models" ) type UserRepo struct{ db *DB } // ErrLinkRequired means an external identity matches an existing local // password account but has not been explicitly linked. Callers must return a // conflict instead of silently taking over the account. var ErrLinkRequired = errors.New("account link required") func NewUserRepo(d *DB) *UserRepo { return &UserRepo{d} } func userFromObject(o Object) (*models.User, error) { raw, err := json.Marshal(o) if err != nil { return nil, err } var row struct { ID string `json:"id"` Name *string `json:"name"` Email *string `json:"email"` EmailVerified *string `json:"emailVerified"` Image *string `json:"image"` Password *string `json:"password"` Role string `json:"role"` TokenVersion int `json:"tokenVersion"` TenantID *string `json:"tenantId"` Bio *string `json:"bio"` Location *string `json:"location"` Occupation *string `json:"occupation"` Organization *string `json:"organization"` Website *string `json:"website"` } if err = json.Unmarshal(raw, &row); err != nil { return nil, err } return &models.User{ID: row.ID, Name: row.Name, Email: row.Email, EmailVerified: row.EmailVerified, Image: row.Image, Password: row.Password, Role: row.Role, TokenVersion: row.TokenVersion, TenantID: row.TenantID, Bio: row.Bio, Location: row.Location, Occupation: row.Occupation, Organization: row.Organization, Website: row.Website}, nil } func findUser(ctx context.Context, q Queryer, field, value string) (*models.User, error) { o, err := One(ctx, q, `SELECT to_jsonb(u) FROM "User" u WHERE `+Quote(field)+`=$1`, value) if err != nil { return nil, err } return userFromObject(o) } func (r *UserRepo) find(ctx context.Context, field, value string) (*models.User, error) { return findUser(ctx, r.db, field, value) } func (r *UserRepo) FindByEmail(ctx context.Context, e string) (*models.User, error) { return r.find(ctx, "email", e) } func (r *UserRepo) FindByID(ctx context.Context, id string) (*models.User, error) { return r.find(ctx, "id", id) } func (r *UserRepo) FindByAccount(ctx context.Context, provider, providerAccountID string) (*models.User, error) { o, err := One(ctx, r.db, `SELECT to_jsonb(u) FROM "Account" a JOIN "User" u ON u.id=a."userId" WHERE a.provider=$1 AND a."providerAccountId"=$2`, provider, providerAccountID) if err != nil { return nil, err } return userFromObject(o) } func (r *UserRepo) SetRole(ctx context.Context, id, role string) error { _, err := r.db.ExecContext(ctx, `UPDATE "User" SET role=$1,"updatedAt"=now() WHERE id=$2`, role, id) return err } // BumpTokenVersion invalidates every cookie JWT issued for the user so far. func (r *UserRepo) BumpTokenVersion(ctx context.Context, id string) error { _, err := r.db.ExecContext(ctx, `UPDATE "User" SET "tokenVersion"="tokenVersion"+1,"updatedAt"=now() WHERE id=$1`, id) return err } // SetPassword replaces the bcrypt hash AND bumps tokenVersion in one // transaction: a password change (reset) must invalidate every session // minted under the old credentials, the same revocation path as an explicit // "sign out everywhere". Missing user reports ErrNotFound. func (r *UserRepo) SetPassword(ctx context.Context, id, bcryptHash string) error { return Transaction(ctx, r.db, func(tx *sql.Tx) error { res, err := tx.ExecContext(ctx, `UPDATE "User" SET password=$1,"tokenVersion"="tokenVersion"+1,"updatedAt"=now() WHERE id=$2`, bcryptHash, id) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil }) } type NewUserInput struct { ID, Name, Email, Password, Role string EmailVerified *string Image *string // External users have no local password. The bootstrap logic still applies // to the first external user on a fresh installation. External bool } // createUserTx performs the shared bootstrap decision and inserts the row. // The caller owns the transaction and the advisory lock; keeping this separate // lets signup and external provisioning use exactly the same first-admin rules. func createUserTx(ctx context.Context, tx *sql.Tx, u *NewUserInput) (string, error) { if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(927438)`); err != nil { return "", err } var bootstrapDone bool if err := tx.QueryRowContext(ctx, `SELECT COALESCE((SELECT value->>'completed' FROM "AppSetting" WHERE key='adminBootstrap'),'false')::boolean`).Scan(&bootstrapDone); err != nil { return "", err } var admins int if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM "User" WHERE role='ADMIN' AND COALESCE(email,'') NOT LIKE '%@example.com'`).Scan(&admins); err != nil { return "", err } role := u.Role if role == "" { role = "USER" } promote := config.AllowBootstrapSignup() && !bootstrapDone && admins == 0 && len(config.AdminEmails()) == 0 && !isTestEmail(u.Email) && role == "USER" if promote { role = "ADMIN" } // Record bootstrap completion as soon as the installation has (or was // just given) a real administrator. A test-address signup with no // admins present never claims the bootstrap. if !bootstrapDone && (role == "ADMIN" || admins > 0) { if _, err := tx.ExecContext(ctx, `INSERT INTO "AppSetting"(key,value) VALUES('adminBootstrap',jsonb_build_object('completed',true)) ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value,"updatedAt"=now()`); err != nil { return "", err } } var password any if u.External { password = nil } else { password = u.Password } var emailVerified any if u.EmailVerified != nil { emailVerified = *u.EmailVerified } var image any if u.Image != nil { image = *u.Image } _, err := Insert(ctx, tx, "User", Object{ "id": u.ID, "name": u.Name, "email": u.Email, "password": password, "role": role, "emailVerified": emailVerified, "image": image, }) if err != nil { return u.ID, err } // Tenancy phase 1: every created user lands in the implicit default // tenant with a membership row, atomically with the user insert. This // covers signup, OIDC provisioning and the seed CLI alike; real // multi-tenant assignment arrives with the billing workstream. return u.ID, attachDefaultTenantTx(ctx, tx, u.ID, role) } // A transaction-scoped lock serializes first-admin selection with signup. // // Review AUTH-06: initial provisioning is a one-shot lifecycle event, // distinct from administrator recovery. Once bootstrap completion is // recorded in AppSetting, the mere absence of a qualifying administrator — // e.g. after demoting or removing the last one — never re-opens // administrator assignment through signup. Recovery is operator-driven // (ADMIN_EMAILS + make seed, or promotion by an existing admin). func (r *UserRepo) Create(ctx context.Context, u *NewUserInput) (string, error) { err := Transaction(ctx, r.db, func(tx *sql.Tx) error { _, e := createUserTx(ctx, tx, u) return e }) return u.ID, err } // ExternalUserInput is the verified profile returned by the OIDC bridge. // ProviderAccountID is the OIDC subject; it is only ever used to find the // local account link, never as the local User.id. type ExternalUserInput struct { Provider string ProviderAccountID string Email string EmailVerified bool Name string Image string } func insertAccountTx(ctx context.Context, tx *sql.Tx, userID string, in ExternalUserInput) error { _, err := Insert(ctx, tx, "Account", Object{ "id": NewID(), "userId": userID, "type": "oidc", "provider": in.Provider, "providerAccountId": in.ProviderAccountID, }) return err } // ErrAccountLinked means the external subject is already linked to a // different local user; an operator must unlink it deliberately first. var ErrAccountLinked = errors.New("account already linked") func (r *UserRepo) LinkExternal(ctx context.Context, userID, provider, subject string) error { return Transaction(ctx, r.db, func(tx *sql.Tx) error { if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, provider+":"+subject); err != nil { return err } if _, err := findUser(ctx, tx, "id", userID); err != nil { return err } var existing string err := tx.QueryRowContext(ctx, `SELECT "userId" FROM "Account" WHERE provider=$1 AND "providerAccountId"=$2`, provider, subject).Scan(&existing) if err == nil { if existing == userID { return nil } return ErrAccountLinked } if !errors.Is(err, sql.ErrNoRows) { return err } _, err = Insert(ctx, tx, "Account", Object{ "id": NewID(), "userId": userID, "type": "oidc", "provider": provider, "providerAccountId": subject, }) return err }) } // ProvisionExternal resolves an OIDC identity to a local user. The advisory // lock is keyed by provider+subject so concurrent first logins cannot create // duplicate accounts. Linking policy is deliberately conservative: // // - an existing Account link is authoritative; // - a matching local account with no password may be linked only when the // IdP asserts a verified email; // - a matching local password account returns ErrLinkRequired (409) and must // be linked explicitly by an operator; email alone is not proof of identity. func (r *UserRepo) ProvisionExternal(ctx context.Context, in ExternalUserInput) (*models.User, error) { var out *models.User err := Transaction(ctx, r.db, func(tx *sql.Tx) error { if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, in.Provider+":"+in.ProviderAccountID); err != nil { return err } // 1. Existing provider link is authoritative. o, err := One(ctx, tx, `SELECT to_jsonb(u) FROM "Account" a JOIN "User" u ON u.id=a."userId" WHERE a.provider=$1 AND a."providerAccountId"=$2`, in.Provider, in.ProviderAccountID) if err == nil { u, err := userFromObject(o) if err != nil { return err } if in.EmailVerified && u.EmailVerified == nil { if _, err := tx.ExecContext(ctx, `UPDATE "User" SET "emailVerified"=now(),"updatedAt"=now() WHERE id=$1`, u.ID); err != nil { return err } now := time.Now().UTC().Format(time.RFC3339) u.EmailVerified = &now } out = u return nil } if !errors.Is(err, ErrNotFound) { return err } // 2. Existing local account with the same email. if in.Email != "" { o, err := One(ctx, tx, `SELECT to_jsonb(u) FROM "User" u WHERE email=$1`, in.Email) if err == nil { u, err := userFromObject(o) if err != nil { return err } if u.Password != nil && *u.Password != "" { return ErrLinkRequired } if !in.EmailVerified { return ErrLinkRequired } if err := insertAccountTx(ctx, tx, u.ID, in); err != nil { return err } if u.EmailVerified == nil { if _, err := tx.ExecContext(ctx, `UPDATE "User" SET "emailVerified"=now(),"updatedAt"=now() WHERE id=$1`, u.ID); err != nil { return err } now := time.Now().UTC().Format(time.RFC3339) u.EmailVerified = &now } out = u return nil } if !errors.Is(err, ErrNotFound) { return err } } // 3. New external user. Name falls back to the email local part. // Operator-listed addresses (ADMIN_EMAILS) become ADMIN at first SSO // login: on AUTH_MODE=oidc deployments this is the only bootstrap // path — password login, signup and the seeded-password flow are all // unavailable there. Same trust semantics as --seed. role := "USER" if config.IsAdminEmail(in.Email) { role = "ADMIN" } id := NewID() name := strings.TrimSpace(in.Name) if name == "" { name = strings.SplitN(in.Email, "@", 2)[0] } var verified *string if in.EmailVerified { now := time.Now().UTC().Format(time.RFC3339) verified = &now } var image *string if in.Image != "" { img := in.Image image = &img } if _, err := createUserTx(ctx, tx, &NewUserInput{ ID: id, Name: name, Email: in.Email, Role: role, EmailVerified: verified, Image: image, External: true, }); err != nil { return err } if err := insertAccountTx(ctx, tx, id, in); err != nil { return err } u, err := findUser(ctx, tx, "id", id) if err != nil { return err } out = u return nil }) return out, err } func isTestEmail(e string) bool { return len(e) >= 12 && e[len(e)-12:] == "@example.com" } func IsAdminEmail(email string) bool { return config.IsAdminEmail(email) }