diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index bda8bc2..323b841 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -64,7 +64,11 @@ jobs: cache: true - name: Check gofmt shell: bash - run: test -z "$(gofmt -l $(find . -type f -name '*.go'))" + run: | + mapfile -d '' go_files < <(find . -type f -name '*.go' -print0) + if ((${#go_files[@]})); then + test -z "$(gofmt -l "${go_files[@]}")" + fi - name: Run go vet run: go vet ./... diff --git a/README.md b/README.md index b538d73..6c774ee 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ The Node and Python packages intentionally expose the same infrastructure concep ## Existing MediaCollection shared package -`Original/MediaCollection/MediaShared` is an existing, larger Express/media-specific package. It remains in place while consumers are migrated so the MediaCollection repo does not break. Its generic PostgreSQL, auth/session, and startup responsibilities are represented in the new runtime-specific packages above; migrate one service at a time, then remove the old workspace dependency in a separate MediaCollection change. +`Original/MediaCollection/MediaShared` is an existing, larger media-specific package. It remains in place for media workflows and startup integration, while the MediaCollection WebUI authentication surface and admin-reset code use this shared package. Its remaining generic responsibilities can be migrated independently without introducing another authentication screen. ## Typical application wiring @@ -219,12 +219,18 @@ For authentication, use the same shell with `AuthPage` and connect the callbacks brand="My application" onLogin={(credentials) => auth.login(credentials.identifier, credentials.password)} onSetup={(credentials) => auth.setup(credentials)} + onRequestReset={() => auth.requestAdminReset()} + onConfirmReset={(code) => auth.confirmAdminReset(code)} setupRequired={setupRequired} tagline="Your project tagline" /> ``` -The package handles form state, validation attributes, loading state, and error presentation. The application remains responsible for deciding where to navigate after a successful action and how errors are returned. +Applications that support MFA can enable the shared optional authenticator-code field with +`showTotp` and forward `credentials.totpToken` to their login endpoint. The base layout and reset +controls remain the same as every other shared auth screen. + +The shared reset controls request a short-lived code printed by the server-side auth package and consume it once after confirmation. The package handles form state, validation attributes, loading state, and error presentation. The application remains responsible for deciding where to navigate after a successful action and how errors are returned. ## Local package development diff --git a/backend/auth/reset.go b/backend/auth/reset.go new file mode 100644 index 0000000..c3f3717 --- /dev/null +++ b/backend/auth/reset.go @@ -0,0 +1,80 @@ +package auth + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "fmt" + "strings" + "sync" + "time" +) + +// ResetCodeTTL is the amount of time a printed admin reset code remains valid. +const ResetCodeTTL = 5 * time.Minute + +// ResetManager creates and validates the short-lived, one-time code used by +// the public "reset admin account" flow. Account deletion remains owned by +// each application because its account table and session policy may differ. +type ResetManager struct { + mu sync.Mutex + code string + expiresAt time.Time +} + +// NewResetManager creates an independent reset-code manager for one server. +func NewResetManager() *ResetManager { + return &ResetManager{} +} + +// Request creates a reset code and prints it to the server console. A new +// request invalidates any code previously issued by this manager. +func (m *ResetManager) Request() (string, error) { + if m == nil { + return "", fmt.Errorf("auth reset manager is nil") + } + + raw := make([]byte, 4) + if _, err := rand.Read(raw); err != nil { + return "", fmt.Errorf("generate auth reset code: %w", err) + } + code := strings.ToUpper(hex.EncodeToString(raw)) + + m.mu.Lock() + m.code = code + m.expiresAt = time.Now().Add(ResetCodeTTL) + m.mu.Unlock() + + fmt.Printf("\n%s\nADMIN RESET CODE: %s\nExpires in 5 minutes. Enter it on the login page.\n%s\n\n", strings.Repeat("=", 50), code, strings.Repeat("=", 50)) + return code, nil +} + +// Confirm validates a code and consumes it on success. Invalid codes do not +// consume the pending code, while expired codes are cleared immediately. +func (m *ResetManager) Confirm(candidate string) bool { + if m == nil { + return false + } + + m.mu.Lock() + defer m.mu.Unlock() + + if m.code == "" { + return false + } + if time.Now().After(m.expiresAt) { + m.code = "" + m.expiresAt = time.Time{} + return false + } + + want := []byte(m.code) + got := []byte(strings.ToUpper(strings.TrimSpace(candidate))) + if len(want) != len(got) || subtle.ConstantTimeCompare(want, got) != 1 { + return false + } + + m.code = "" + m.expiresAt = time.Time{} + return true +} diff --git a/backend/auth/roles.go b/backend/auth/roles.go new file mode 100644 index 0000000..35b8f62 --- /dev/null +++ b/backend/auth/roles.go @@ -0,0 +1,34 @@ +package auth + +// Role is the shared account-management role used by the web applications. +type Role string + +const ( + RoleSuperAdmin Role = "superadmin" + RoleAdmin Role = "admin" + RoleUser Role = "user" +) + +// NormalizeRole keeps persisted role values inside the shared contract. +func NormalizeRole(value string) Role { + switch Role(value) { + case RoleSuperAdmin: + return RoleSuperAdmin + case RoleAdmin: + return RoleAdmin + default: + return RoleUser + } +} + +// CanManageUsers is the common authorization gate for account CRUD. +func CanManageUsers(role string) bool { + role = string(NormalizeRole(role)) + return role == string(RoleSuperAdmin) || role == string(RoleAdmin) +} + +// CanAssignRole prevents an administrator from creating or promoting another +// administrator. Only the first-created superadmin can delegate admin access. +func CanAssignRole(actorRole, targetRole string) bool { + return NormalizeRole(actorRole) == RoleSuperAdmin && NormalizeRole(targetRole) != RoleSuperAdmin +} diff --git a/backend/auth/store.go b/backend/auth/store.go index 76891d4..fbeb70b 100644 --- a/backend/auth/store.go +++ b/backend/auth/store.go @@ -21,6 +21,7 @@ type User struct { Username string Email string PasswordHash string + Role Role CreatedAt time.Time UpdatedAt time.Time } @@ -62,12 +63,21 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions 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; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); + 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'); CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> ''; @@ -91,6 +101,8 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions `); err != nil { return fmt.Errorf("ensure single-user auth constraint: %w", err) } + } else if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_singleton_idx`); err != nil { + return fmt.Errorf("remove single-user auth constraint: %w", err) } if options.APITokens { @@ -109,6 +121,65 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions return nil } +// TOTPState is the private provisioning state for one account. Secret must +// never be included in an API response. +type TOTPState struct { + Secret string + Enabled bool +} + +// GetTOTPState reads the stored TOTP provisioning state for an account. +func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, error) { + if err := s.validate(); err != nil { + return TOTPState{}, err + } + var state TOTPState + err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled) + if errors.Is(err, pgx.ErrNoRows) { + return TOTPState{}, nil + } + if err != nil { + return TOTPState{}, fmt.Errorf("get TOTP state: %w", err) + } + return state, nil +} + +// SetTOTPSecret stores a pending secret without enabling two-factor auth. +func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error { + if err := s.validate(); err != nil { + return err + } + _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID) + if err != nil { + return fmt.Errorf("set TOTP secret: %w", err) + } + return nil +} + +// EnableTOTP marks a previously provisioned secret as active. +func (s *Store) EnableTOTP(ctx context.Context, userID int64) error { + if err := s.validate(); err != nil { + return err + } + _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID) + if err != nil { + return fmt.Errorf("enable TOTP: %w", err) + } + return nil +} + +// DisableTOTP clears both the active and pending TOTP secret. +func (s *Store) DisableTOTP(ctx context.Context, userID int64) error { + if err := s.validate(); err != nil { + return err + } + _, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID) + if err != nil { + return fmt.Errorf("disable TOTP: %w", err) + } + return nil +} + // CountUsers returns the number of configured accounts. func (s *Store) CountUsers(ctx context.Context) (int, error) { if err := s.validate(); err != nil { @@ -129,11 +200,13 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st } var user User err := s.pool.QueryRow(ctx, ` - INSERT INTO auth_users (username, email, password_hash, updated_at) - VALUES ($1, $2, $3, now()) - RETURNING id, username, email, password_hash, created_at, updated_at + INSERT INTO auth_users (username, email, password_hash, role, updated_at) + VALUES ($1, $2, $3, + CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END, + now()) + RETURNING id, username, email, password_hash, role, created_at, updated_at `, username, email, passwordHash).Scan( - &user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt, + &user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, ) if err != nil { var pgErr *pgconn.PgError @@ -151,7 +224,7 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User, return nil, err } return s.find(ctx, ` - SELECT id, username, email, password_hash, created_at, updated_at + SELECT id, username, email, password_hash, role, created_at, updated_at FROM auth_users WHERE username = $1 OR lower(email) = lower($1) `, identifier) @@ -163,7 +236,7 @@ func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) { return nil, err } return s.find(ctx, ` - SELECT id, username, email, password_hash, created_at, updated_at + SELECT id, username, email, password_hash, role, created_at, updated_at FROM auth_users WHERE id = $1 `, id) } @@ -184,6 +257,86 @@ func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email return nil } +// ListUsers returns the non-secret account fields used by the shared user +// management screen. +func (s *Store) ListUsers(ctx context.Context) ([]User, error) { + if err := s.validate(); err != nil { + return nil, err + } + rows, err := s.pool.Query(ctx, ` + SELECT id, username, email, role, created_at, updated_at + FROM auth_users ORDER BY created_at, id + `) + if err != nil { + return nil, fmt.Errorf("list auth users: %w", err) + } + defer rows.Close() + users := make([]User, 0) + for rows.Next() { + var user User + if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt); err != nil { + return nil, fmt.Errorf("scan auth user: %w", err) + } + users = append(users, user) + } + return users, rows.Err() +} + +// CreateManagedUser creates a user with an explicit, already-authorized role. +func (s *Store) CreateManagedUser(ctx context.Context, username, email, passwordHash string, role Role) (*User, error) { + if err := s.validate(); err != nil { + return nil, err + } + role = NormalizeRole(string(role)) + var user User + err := s.pool.QueryRow(ctx, ` + INSERT INTO auth_users (username, email, password_hash, role, updated_at) + VALUES ($1, $2, $3, $4, now()) + RETURNING id, username, email, password_hash, role, created_at, updated_at + `, username, email, passwordHash, role).Scan( + &user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, + ) + if err != nil { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "23505" { + return nil, ErrUserExists + } + return nil, fmt.Errorf("create managed auth user: %w", err) + } + return &user, nil +} + +// UpdateUser updates account fields and, when supplied, its role. +func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passwordHash string, role *Role) error { + if err := s.validate(); err != nil { + return err + } + if role == nil { + return s.UpdateCredentials(ctx, id, username, email, passwordHash) + } + *role = NormalizeRole(string(*role)) + _, err := s.pool.Exec(ctx, ` + UPDATE auth_users + SET username = $1, email = $2, password_hash = $3, role = $4, updated_at = now() + WHERE id = $5 + `, username, email, passwordHash, *role, id) + if err != nil { + return fmt.Errorf("update managed auth user: %w", err) + } + return nil +} + +// DeleteUser removes one account. Callers enforce the superadmin/self policy. +func (s *Store) DeleteUser(ctx context.Context, id int64) error { + if err := s.validate(); err != nil { + return err + } + if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil { + return fmt.Errorf("delete auth user: %w", err) + } + return nil +} + // CreateSession stores a hash of a session token until expiresAt. func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error { if err := s.validate(); err != nil { @@ -205,7 +358,7 @@ func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, e return nil, err } return s.find(ctx, ` - SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at + SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now() @@ -234,6 +387,18 @@ func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error { return nil } +// DeleteAllUsers removes every shared account. The auth schema's foreign keys +// cascade this to browser sessions and API tokens, allowing a fresh bootstrap. +func (s *Store) DeleteAllUsers(ctx context.Context) error { + if err := s.validate(); err != nil { + return err + } + if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil { + return fmt.Errorf("delete all auth users: %w", err) + } + return nil +} + // DeleteExpiredSessions performs the periodic session cleanup shared by the // services. A caller can run it from its own scheduler. func (s *Store) DeleteExpiredSessions(ctx context.Context) error { diff --git a/backend/auth/store_test.go b/backend/auth/store_test.go index 0a31243..a497a0d 100644 --- a/backend/auth/store_test.go +++ b/backend/auth/store_test.go @@ -1,7 +1,9 @@ package auth import ( + "strings" "testing" + "time" "golang.org/x/crypto/bcrypt" ) @@ -35,3 +37,33 @@ func TestNewSessionToken(t *testing.T) { t.Fatalf("HashToken(raw) = %q, want %q", diff, hash) } } + +func TestResetManagerRoundTrip(t *testing.T) { + manager := NewResetManager() + code, err := manager.Request() + if err != nil { + t.Fatalf("Request() error = %v", err) + } + if len(code) != 8 || strings.ToUpper(code) != code { + t.Fatalf("reset code = %q, want eight uppercase characters", code) + } + if !manager.Confirm(" " + strings.ToLower(code) + " ") { + t.Fatal("Confirm() rejected a valid reset code") + } + if manager.Confirm(code) { + t.Fatal("Confirm() accepted a reset code twice") + } +} + +func TestResetManagerExpiresCode(t *testing.T) { + manager := NewResetManager() + if _, err := manager.Request(); err != nil { + t.Fatalf("Request() error = %v", err) + } + manager.mu.Lock() + manager.expiresAt = time.Now().Add(-time.Second) + manager.mu.Unlock() + if manager.Confirm("anything") { + t.Fatal("Confirm() accepted an expired reset code") + } +} diff --git a/backend/auth/totp.go b/backend/auth/totp.go new file mode 100644 index 0000000..6ded413 --- /dev/null +++ b/backend/auth/totp.go @@ -0,0 +1,104 @@ +package auth + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha1" + "crypto/subtle" + "encoding/base32" + "encoding/binary" + "fmt" + "net/url" + "strconv" + "strings" + "time" +) + +// TOTP follows RFC 6238's default interoperable profile. +const ( + TOTPPeriod = 30 * time.Second + TOTPDigits = 6 + TOTPSecretBytes = 20 + TOTPWindow = 1 + TOTPSecretLength = 32 +) + +// GenerateTOTPSecret returns a base32 secret suitable for authenticator apps. +func GenerateTOTPSecret() (string, error) { + raw := make([]byte, TOTPSecretBytes) + if _, err := rand.Read(raw); err != nil { + return "", fmt.Errorf("generate TOTP secret: %w", err) + } + return base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw), nil +} + +// TOTPProvisioningURI builds the otpauth URI accepted by common authenticator apps. +func TOTPProvisioningURI(issuer, account, secret string) string { + issuer = strings.TrimSpace(issuer) + account = strings.TrimSpace(account) + secret = normalizeTOTPSecret(secret) + label := account + if issuer != "" { + label = issuer + ":" + account + } + query := url.Values{} + query.Set("secret", secret) + if issuer != "" { + query.Set("issuer", issuer) + } + query.Set("algorithm", "SHA1") + query.Set("digits", strconv.Itoa(TOTPDigits)) + query.Set("period", strconv.Itoa(int(TOTPPeriod/time.Second))) + return "otpauth://totp/" + url.PathEscape(label) + "?" + query.Encode() +} + +// VerifyTOTP checks a six-digit token with a one-period clock-skew window. +func VerifyTOTP(secret, token string, now time.Time) bool { + secret = normalizeTOTPSecret(secret) + token = normalizeTOTPToken(token) + if secret == "" || len(token) != TOTPDigits { + return false + } + key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(secret) + if err != nil || len(key) == 0 { + return false + } + period := now.Unix() / int64(TOTPPeriod/time.Second) + for offset := int64(-TOTPWindow); offset <= TOTPWindow; offset++ { + if period+offset < 0 { + continue + } + var counter [8]byte + binary.BigEndian.PutUint64(counter[:], uint64(period+offset)) + hash := hmac.New(sha1.New, key) + _, _ = hash.Write(counter[:]) + digest := hash.Sum(nil) + index := digest[len(digest)-1] & 0x0f + value := (uint32(digest[index])&0x7f)<<24 | + uint32(digest[index+1])<<16 | + uint32(digest[index+2])<<8 | + uint32(digest[index+3]) + candidate := fmt.Sprintf("%06d", value%1000000) + if subtle.ConstantTimeCompare([]byte(candidate), []byte(token)) == 1 { + return true + } + } + return false +} + +func normalizeTOTPSecret(value string) string { + return strings.TrimRight(strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(value)), " ", ""), "=") +} + +func normalizeTOTPToken(value string) string { + value = strings.TrimSpace(value) + if len(value) > TOTPDigits { + return "" + } + for _, character := range value { + if character < '0' || character > '9' { + return "" + } + } + return value +} diff --git a/backend/auth/totp_test.go b/backend/auth/totp_test.go new file mode 100644 index 0000000..9e2623d --- /dev/null +++ b/backend/auth/totp_test.go @@ -0,0 +1,32 @@ +package auth + +import ( + "testing" + "time" +) + +func TestVerifyTOTPRFC6238SHA1Vectors(t *testing.T) { + secret := "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" + cases := []struct { + unix int64 + code string + }{ + {unix: 59, code: "287082"}, + {unix: 1111111109, code: "081804"}, + {unix: 1111111111, code: "050471"}, + {unix: 1234567890, code: "005924"}, + {unix: 2000000000, code: "279037"}, + } + for _, testCase := range cases { + if !VerifyTOTP(secret, testCase.code, time.Unix(testCase.unix, 0)) { + t.Errorf("VerifyTOTP(%d, %q) = false", testCase.unix, testCase.code) + } + } +} + +func TestTOTPProvisioningURI(t *testing.T) { + uri := TOTPProvisioningURI("Example App", "admin@example.com", "abc123") + if uri == "" || len(uri) < len("otpauth://totp/") || uri[:15] != "otpauth://totp/" { + t.Fatalf("unexpected provisioning URI: %q", uri) + } +} diff --git a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/ResetManager.java b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/ResetManager.java new file mode 100644 index 0000000..1cefa94 --- /dev/null +++ b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/ResetManager.java @@ -0,0 +1,58 @@ +package com.gabriel20xx.shared.auth; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.Locale; + +/** Shared short-lived, one-time admin reset-code primitive for Java services. */ +public final class ResetManager { + private static final long RESET_CODE_TTL_MILLIS = 5L * 60L * 1000L; + private static final SecureRandom RANDOM = new SecureRandom(); + + private String code; + private long expiresAtMillis; + + /** Creates and prints a new reset code, invalidating any previous code. */ + public synchronized String request() { + byte[] raw = new byte[4]; + RANDOM.nextBytes(raw); + StringBuilder generated = new StringBuilder(raw.length * 2); + for (byte value : raw) { + generated.append(String.format(Locale.ROOT, "%02X", value & 0xff)); + } + + code = generated.toString(); + expiresAtMillis = System.currentTimeMillis() + RESET_CODE_TTL_MILLIS; + System.out.println("\n==================================================\n" + + "ADMIN RESET CODE: " + code + "\n" + + "Expires in 5 minutes. Enter it on the login page.\n" + + "==================================================\n"); + return code; + } + + /** Validates and consumes the current code. Invalid codes remain retryable. */ + public synchronized boolean confirm(String candidate) { + if (code == null) { + return false; + } + if (System.currentTimeMillis() > expiresAtMillis) { + clear(); + return false; + } + + String normalized = candidate == null ? "" : candidate.trim().toUpperCase(Locale.ROOT); + boolean matches = MessageDigest.isEqual( + code.getBytes(StandardCharsets.US_ASCII), + normalized.getBytes(StandardCharsets.US_ASCII)); + if (matches) { + clear(); + } + return matches; + } + + private void clear() { + code = null; + expiresAtMillis = 0L; + } +} diff --git a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Roles.java b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Roles.java new file mode 100644 index 0000000..f0e91e4 --- /dev/null +++ b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Roles.java @@ -0,0 +1,29 @@ +package com.gabriel20xx.shared.auth; + +import java.util.Locale; + +/** Shared account-management roles used by Java web services. */ +public final class Roles { + public static final String SUPERADMIN = "superadmin"; + public static final String ADMIN = "admin"; + public static final String USER = "user"; + + private Roles() { + } + + public static String normalize(String value) { + String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT); + if (SUPERADMIN.equals(normalized)) return SUPERADMIN; + if (ADMIN.equals(normalized)) return ADMIN; + return USER; + } + + public static boolean canManageUsers(String role) { + String normalized = normalize(role); + return SUPERADMIN.equals(normalized) || ADMIN.equals(normalized); + } + + public static boolean canAssignRole(String actorRole, String targetRole) { + return SUPERADMIN.equals(normalize(actorRole)) && !SUPERADMIN.equals(normalize(targetRole)); + } +} diff --git a/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java new file mode 100644 index 0000000..6579c9c --- /dev/null +++ b/packages/java-backend/src/main/java/com/gabriel20xx/shared/auth/Totp.java @@ -0,0 +1,143 @@ +package com.gabriel20xx.shared.auth; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Locale; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** RFC 6238 TOTP primitives shared by Java services. */ +public final class Totp { + private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; + private static final int SECRET_BYTES = 20; + private static final int PERIOD_SECONDS = 30; + private static final int WINDOW = 1; + private static final int DIGITS = 6; + private static final SecureRandom RANDOM = new SecureRandom(); + + private Totp() { + } + + public static String generateSecret() { + byte[] raw = new byte[SECRET_BYTES]; + RANDOM.nextBytes(raw); + return encodeBase32(raw); + } + + public static String provisioningUri(String issuer, String account, String secret) { + String normalizedIssuer = issuer == null ? "" : issuer.trim(); + String normalizedAccount = account == null ? "" : account.trim(); + String label = normalizedIssuer.isEmpty() + ? normalizedAccount + : normalizedIssuer + ":" + normalizedAccount; + StringBuilder uri = new StringBuilder("otpauth://totp/") + .append(urlEncode(label)) + .append("?secret=").append(normalizeSecret(secret)); + if (!normalizedIssuer.isEmpty()) { + uri.append("&issuer=").append(urlEncode(normalizedIssuer)); + } + return uri.append("&algorithm=SHA1&digits=").append(DIGITS) + .append("&period=").append(PERIOD_SECONDS).toString(); + } + + public static boolean verify(String secret, String token, long nowMillis) { + String normalizedSecret = normalizeSecret(secret); + String normalizedToken = token == null ? "" : token.trim(); + if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) { + return false; + } + byte[] key; + try { + key = decodeBase32(normalizedSecret); + } catch (IllegalArgumentException ex) { + return false; + } + if (key.length == 0) { + return false; + } + long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L); + for (long offset = -WINDOW; offset <= WINDOW; offset++) { + if (counter + offset < 0) { + continue; + } + try { + byte[] message = new byte[8]; + long value = counter + offset; + for (int index = 7; index >= 0; index--) { + message[index] = (byte) (value & 0xff); + value >>>= 8; + } + Mac mac = Mac.getInstance("HmacSHA1"); + mac.init(new SecretKeySpec(key, "HmacSHA1")); + byte[] hash = mac.doFinal(message); + int index = hash[hash.length - 1] & 0x0f; + int code = ((hash[index] & 0x7f) << 24) + | ((hash[index + 1] & 0xff) << 16) + | ((hash[index + 2] & 0xff) << 8) + | (hash[index + 3] & 0xff); + String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000); + if (candidate.equals(normalizedToken)) { + return true; + } + } catch (Exception ex) { + return false; + } + } + return false; + } + + private static String normalizeSecret(String value) { + return value == null ? "" : value.trim().replace(" ", "").replace("=", "").toUpperCase(Locale.ROOT); + } + + private static String encodeBase32(byte[] bytes) { + StringBuilder result = new StringBuilder((bytes.length * 8 + 4) / 5); + int buffer = 0; + int bits = 0; + for (byte value : bytes) { + buffer = (buffer << 8) | (value & 0xff); + bits += 8; + while (bits >= 5) { + bits -= 5; + result.append(BASE32.charAt((buffer >>> bits) & 31)); + } + } + if (bits > 0) { + result.append(BASE32.charAt((buffer << (5 - bits)) & 31)); + } + return result.toString(); + } + + private static byte[] decodeBase32(String value) { + int outputLength = value.length() * 5 / 8; + byte[] result = new byte[outputLength]; + int buffer = 0; + int bits = 0; + int output = 0; + for (int index = 0; index < value.length(); index++) { + int digit = BASE32.indexOf(value.charAt(index)); + if (digit < 0) { + throw new IllegalArgumentException("Invalid base32 secret"); + } + buffer = (buffer << 5) | digit; + bits += 5; + while (bits >= 8) { + bits -= 8; + if (output < result.length) { + result[output++] = (byte) ((buffer >>> bits) & 0xff); + } + } + buffer &= bits == 0 ? 0 : (1 << bits) - 1; + } + return result; + } + + private static String urlEncode(String value) { + try { + return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replace("+", "%20"); + } catch (Exception ex) { + throw new IllegalArgumentException("Unable to encode provisioning URI", ex); + } + } +} diff --git a/packages/node-backend/README.md b/packages/node-backend/README.md index 4af088f..af7d84f 100644 --- a/packages/node-backend/README.md +++ b/packages/node-backend/README.md @@ -5,6 +5,7 @@ Shared Node.js backend infrastructure for services that use PostgreSQL: - validated `DATABASE_URL` and pool settings; - one pool owner with startup retry, transient query retry, transactions, and shutdown; - PBKDF2 password hashing and secure session-token helpers; +- short-lived, one-time admin reset codes printed to the server console; - common account/session persistence; - transaction-locked ordered migrations. diff --git a/packages/node-backend/src/auth.js b/packages/node-backend/src/auth.js index 9b5ac70..c438b99 100644 --- a/packages/node-backend/src/auth.js +++ b/packages/node-backend/src/auth.js @@ -3,6 +3,22 @@ import crypto from 'node:crypto'; const PASSWORD_ITERATIONS = 100000; const PASSWORD_KEY_LENGTH = 32; const PASSWORD_DIGEST = 'sha256'; +export const RESET_CODE_TTL_MS = 5 * 60 * 1000; +export const USER_ROLES = Object.freeze({ SUPERADMIN: 'superadmin', ADMIN: 'admin', USER: 'user' }); + +export function normalizeRole(value) { + const normalized = String(value ?? '').trim().toLowerCase(); + return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN ? normalized : USER_ROLES.USER; +} + +export function canManageUsers(role) { + const normalized = normalizeRole(role); + return normalized === USER_ROLES.SUPERADMIN || normalized === USER_ROLES.ADMIN; +} + +export function canAssignRole(actorRole, targetRole) { + return normalizeRole(actorRole) === USER_ROLES.SUPERADMIN && normalizeRole(targetRole) !== USER_ROLES.SUPERADMIN; +} export const AUTH_SCHEMA = ` CREATE TABLE IF NOT EXISTS auth_users ( @@ -10,12 +26,21 @@ CREATE TABLE IF NOT EXISTS auth_users ( 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; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); +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'); CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> ''; CREATE TABLE IF NOT EXISTS auth_sessions ( id BIGSERIAL PRIMARY KEY, @@ -64,6 +89,48 @@ export function hashToken(token) { return crypto.createHash('sha256').update(String(token)).digest('hex'); } +/** + * Creates and validates the short-lived, one-time code used by the public + * "reset admin account" flow. Account deletion stays with the application + * because its account table and session policy may differ. + */ +export class ResetManager { + constructor({ ttlMs = RESET_CODE_TTL_MS, log = console.log } = {}) { + this.ttlMs = ttlMs; + this.log = log; + this.code = null; + this.expiresAt = 0; + } + + request() { + this.code = crypto.randomBytes(4).toString('hex').toUpperCase(); + this.expiresAt = Date.now() + this.ttlMs; + this.log( + `\n${'='.repeat(50)}\nADMIN RESET CODE: ${this.code}\nExpires in 5 minutes. Enter it on the login page.\n${'='.repeat(50)}\n`, + ); + return this.code; + } + + confirm(candidate) { + if (!this.code) return false; + if (Date.now() > this.expiresAt) { + this.code = null; + this.expiresAt = 0; + return false; + } + + const normalized = String(candidate ?? '').trim().toUpperCase(); + const expected = Buffer.from(this.code); + const actual = Buffer.from(normalized); + const valid = expected.length === actual.length && crypto.timingSafeEqual(expected, actual); + if (!valid) return false; + + this.code = null; + this.expiresAt = 0; + return true; + } +} + /** Persistence-only auth store; cookies, roles, and HTTP policy stay in the app. */ export class AuthStore { constructor(database, { singleUser = true } = {}) { @@ -78,6 +145,8 @@ export class AuthStore { await this.database.query(AUTH_SCHEMA); if (this.singleUser) { await this.database.query('CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))'); + } else { + await this.database.query('DROP INDEX IF EXISTS auth_users_singleton_idx'); } } @@ -89,9 +158,11 @@ export class AuthStore { async createUser(username, email, passwordHash) { try { const result = await this.database.query( - `INSERT INTO auth_users (username, email, password_hash, updated_at) - VALUES ($1, $2, $3, now()) - RETURNING id, username, email, password_hash, created_at, updated_at`, + `INSERT INTO auth_users (username, email, password_hash, role, updated_at) + VALUES ($1, $2, $3, + CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END, + now()) + RETURNING id, username, email, password_hash, role, created_at, updated_at`, [username, email, passwordHash] ); return result.rows[0]; @@ -107,7 +178,7 @@ export class AuthStore { async findByIdentifier(identifier) { const result = await this.database.query( - `SELECT id, username, email, password_hash, created_at, updated_at + `SELECT id, username, email, password_hash, role, created_at, updated_at FROM auth_users WHERE username = $1 OR lower(email) = lower($1)`, [identifier] ); @@ -131,7 +202,7 @@ export class AuthStore { async findSessionUser(tokenHash) { const result = await this.database.query( - `SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at + `SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()`, [tokenHash] @@ -147,6 +218,85 @@ export class AuthStore { await this.database.query('DELETE FROM auth_sessions WHERE user_id = $1', [userId]); } + async listUsers() { + const result = await this.database.query( + 'SELECT id, username, email, role, created_at, updated_at FROM auth_users ORDER BY created_at, id', + ); + return result.rows; + } + + async createManagedUser(username, email, passwordHash, role = USER_ROLES.USER) { + try { + const result = await this.database.query( + `INSERT INTO auth_users (username, email, password_hash, role, updated_at) + VALUES ($1, $2, $3, $4, now()) + RETURNING id, username, email, role, created_at, updated_at`, + [username, email, passwordHash, normalizeRole(role)], + ); + return result.rows[0]; + } catch (error) { + if (error?.code === '23505') { + const duplicate = new Error('auth user already exists'); + duplicate.code = 'AUTH_USER_EXISTS'; + throw duplicate; + } + throw error; + } + } + + async updateUser(id, { username, email, passwordHash, role } = {}) { + const fields = []; + const values = []; + const add = (sql, value) => { fields.push(sql); values.push(value); }; + if (username !== undefined) add(`username = $${values.length + 1}`, username); + if (email !== undefined) add(`email = $${values.length + 1}`, email); + if (passwordHash !== undefined) add(`password_hash = $${values.length + 1}`, passwordHash); + if (role !== undefined) add(`role = $${values.length + 1}`, normalizeRole(role)); + if (fields.length === 0) return; + values.push(id); + await this.database.query( + `UPDATE auth_users SET ${fields.join(', ')}, updated_at = now() WHERE id = $${values.length}`, + values, + ); + } + + async deleteUser(id) { + await this.database.query('DELETE FROM auth_users WHERE id = $1', [id]); + } + + async deleteAllUsers() { + await this.database.query('DELETE FROM auth_users'); + } + + async getTotpState(userId) { + const result = await this.database.query( + 'SELECT COALESCE(totp_secret, \'\') AS secret, COALESCE(totp_enabled, false) AS enabled FROM auth_users WHERE id = $1', + [userId], + ); + return result.rows[0] || { secret: '', enabled: false }; + } + + async setTotpSecret(userId, secret) { + await this.database.query( + 'UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2', + [secret, userId], + ); + } + + async enableTotp(userId) { + await this.database.query( + "UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''", + [userId], + ); + } + + async disableTotp(userId) { + await this.database.query( + "UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1", + [userId], + ); + } + async pruneExpiredSessions() { await this.database.query('DELETE FROM auth_sessions WHERE expires_at < now()'); } diff --git a/packages/node-backend/src/index.js b/packages/node-backend/src/index.js index 8516455..fda2b68 100644 --- a/packages/node-backend/src/index.js +++ b/packages/node-backend/src/index.js @@ -11,9 +11,23 @@ export { export { AUTH_SCHEMA, AuthStore, + RESET_CODE_TTL_MS, + ResetManager, createSessionToken, hashPassword, hashToken, + USER_ROLES, + canAssignRole, + canManageUsers, + normalizeRole, verifyPassword, } from './auth.js'; +export { + TOTP_DIGITS, + TOTP_PERIOD_SECONDS, + TOTP_WINDOW, + generateTotpSecret, + totpProvisioningUri, + verifyTotp, +} from './totp.js'; export { runMigrations } from './migrate.js'; diff --git a/packages/node-backend/src/totp.js b/packages/node-backend/src/totp.js new file mode 100644 index 0000000..f9ec2ba --- /dev/null +++ b/packages/node-backend/src/totp.js @@ -0,0 +1,96 @@ +import crypto from 'node:crypto'; + +export const TOTP_PERIOD_SECONDS = 30; +export const TOTP_DIGITS = 6; +export const TOTP_WINDOW = 1; +const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + +export function generateTotpSecret() { + return encodeBase32(crypto.randomBytes(20)); +} + +export function totpProvisioningUri(issuer, account, secret) { + const normalizedIssuer = String(issuer ?? '').trim(); + const normalizedAccount = String(account ?? '').trim(); + const label = normalizedIssuer ? `${normalizedIssuer}:${normalizedAccount}` : normalizedAccount; + const params = new URLSearchParams({ + secret: normalizeSecret(secret), + algorithm: 'SHA1', + digits: String(TOTP_DIGITS), + period: String(TOTP_PERIOD_SECONDS), + }); + if (normalizedIssuer) params.set('issuer', normalizedIssuer); + return `otpauth://totp/${encodeURIComponent(label)}?${params.toString()}`; +} + +export function verifyTotp(secret, token, now = Date.now()) { + const normalizedSecret = normalizeSecret(secret); + const normalizedToken = normalizeToken(token); + if (!normalizedSecret || normalizedToken.length !== TOTP_DIGITS) return false; + + let key; + try { + key = decodeBase32(normalizedSecret); + } catch { + return false; + } + if (key.length === 0) return false; + const period = Math.floor(now / 1000 / TOTP_PERIOD_SECONDS); + for (let offset = -TOTP_WINDOW; offset <= TOTP_WINDOW; offset += 1) { + if (period + offset < 0) continue; + const counter = Buffer.alloc(8); + counter.writeBigUInt64BE(BigInt(period + offset)); + const digest = crypto.createHmac('sha1', key).update(counter).digest(); + const index = digest[digest.length - 1] & 0x0f; + const value = ((digest[index] & 0x7f) << 24) + | (digest[index + 1] << 16) + | (digest[index + 2] << 8) + | digest[index + 3]; + const candidate = String(value % 1000000).padStart(TOTP_DIGITS, '0'); + if (crypto.timingSafeEqual(Buffer.from(candidate), Buffer.from(normalizedToken))) return true; + } + return false; +} + +function normalizeSecret(value) { + return String(value ?? '').trim().toUpperCase().replaceAll(' ', '').replaceAll('=', ''); +} + +function normalizeToken(value) { + const token = String(value ?? '').trim(); + return /^\d{6}$/.test(token) ? token : ''; +} + +function encodeBase32(buffer) { + let output = ''; + let bits = 0; + let value = 0; + for (const byte of buffer) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) { + output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + } + if (bits > 0) output += BASE32_ALPHABET[(value << (5 - bits)) & 31]; + return output; +} + +function decodeBase32(value) { + let bits = 0; + let buffer = 0; + const output = []; + for (const character of value) { + const index = BASE32_ALPHABET.indexOf(character); + if (index < 0) throw new Error('invalid base32 secret'); + buffer = (buffer << 5) | index; + bits += 5; + while (bits >= 8) { + bits -= 8; + output.push((buffer >>> bits) & 255); + } + buffer &= bits === 0 ? 0 : (1 << bits) - 1; + } + return Buffer.from(output); +} diff --git a/packages/node-backend/test/auth.test.js b/packages/node-backend/test/auth.test.js index f0d3ce6..4969b79 100644 --- a/packages/node-backend/test/auth.test.js +++ b/packages/node-backend/test/auth.test.js @@ -1,11 +1,31 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { + ResetManager, createSessionToken, hashPassword, hashToken, verifyPassword, } from '../src/auth.js'; +import { totpProvisioningUri, verifyTotp } from '../src/totp.js'; + +test('reset codes are printed, case-insensitive, expiring, and one-time', () => { + const messages = []; + const manager = new ResetManager({ log: (message) => messages.push(message) }); + const code = manager.request(); + + assert.equal(code.length, 8); + assert.equal(messages.length, 1); + assert.match(messages[0], new RegExp(`ADMIN RESET CODE: ${code}`)); + assert.equal(manager.confirm(` ${code.toLowerCase()} `), true); + assert.equal(manager.confirm(code), false); +}); + +test('expired reset codes are rejected', () => { + const manager = new ResetManager({ ttlMs: -1, log: () => {} }); + const code = manager.request(); + assert.equal(manager.confirm(code), false); +}); test('password hashes verify and reject a different password', () => { const hash = hashPassword('correct horse battery staple'); @@ -13,6 +33,21 @@ test('password hashes verify and reject a different password', () => { assert.equal(verifyPassword('wrong password', hash), false); }); +test('TOTP verifies RFC 6238 SHA-1 vectors', () => { + const secret = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; + const vectors = [ + [59, '287082'], + [1111111109, '081804'], + [1111111111, '050471'], + [1234567890, '005924'], + [2000000000, '279037'], + ]; + for (const [seconds, code] of vectors) { + assert.equal(verifyTotp(secret, code, seconds * 1000), true); + } + assert.match(totpProvisioningUri('Example App', 'admin@example.com', secret), /^otpauth:\/\/totp\//); +}); + test('session token hashes are not the raw token', () => { const { token, tokenHash } = createSessionToken(); assert.notEqual(token, tokenHash); diff --git a/packages/python-backend/README.md b/packages/python-backend/README.md index 41cb900..6c5a2ee 100644 --- a/packages/python-backend/README.md +++ b/packages/python-backend/README.md @@ -5,6 +5,7 @@ Shared Python backend infrastructure for services using `asyncpg`: - validated `DATABASE_URL` and pool settings; - one async pool owner with ping and graceful shutdown; - bcrypt password and secure session-token helpers; +- short-lived, one-time admin reset codes printed to the server console; - common account/session persistence for the single-admin or optional multi-user model. HTTP framework adapters stay in each service. Install this package from the diff --git a/packages/python-backend/src/shared_backend/__init__.py b/packages/python-backend/src/shared_backend/__init__.py index ae56a19..b506ebb 100644 --- a/packages/python-backend/src/shared_backend/__init__.py +++ b/packages/python-backend/src/shared_backend/__init__.py @@ -1,18 +1,43 @@ """Shared PostgreSQL and authentication primitives for Python services.""" -from .auth import AuthStore, AuthUser, hash_password, verify_password +from .auth import ( + ROLE_ADMIN, + ROLE_SUPERADMIN, + ROLE_USER, + RESET_CODE_TTL, + AuthStore, + AuthUser, + ResetManager, + can_assign_role, + can_manage_users, + hash_password, + normalize_role, + verify_password, +) from .config import DatabaseConfig, database_url_from_env from .postgres import Database +from .totp import generate_totp_secret, totp_provisioning_uri, verify_totp from .tokens import hash_token, new_session_token __all__ = [ "AuthStore", "AuthUser", + "ROLE_ADMIN", + "ROLE_SUPERADMIN", + "ROLE_USER", + "RESET_CODE_TTL", + "ResetManager", + "can_assign_role", + "can_manage_users", "Database", "DatabaseConfig", "database_url_from_env", + "generate_totp_secret", "hash_password", "hash_token", "new_session_token", + "normalize_role", + "totp_provisioning_uri", "verify_password", + "verify_totp", ] diff --git a/packages/python-backend/src/shared_backend/auth.py b/packages/python-backend/src/shared_backend/auth.py index e6312c6..faacb7f 100644 --- a/packages/python-backend/src/shared_backend/auth.py +++ b/packages/python-backend/src/shared_backend/auth.py @@ -2,8 +2,10 @@ from __future__ import annotations +import secrets +import threading from dataclasses import dataclass -from datetime import datetime +from datetime import datetime, timedelta import asyncpg import bcrypt @@ -16,12 +18,21 @@ CREATE TABLE IF NOT EXISTS auth_users ( 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; ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now(); +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'); CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> ''; CREATE TABLE IF NOT EXISTS auth_sessions ( @@ -35,6 +46,61 @@ 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); """ +RESET_CODE_TTL = timedelta(minutes=5) + +ROLE_SUPERADMIN = "superadmin" +ROLE_ADMIN = "admin" +ROLE_USER = "user" + + +def normalize_role(value: str | None) -> str: + normalized = str(value or "").strip().lower() + return normalized if normalized in {ROLE_SUPERADMIN, ROLE_ADMIN} else ROLE_USER + + +def can_manage_users(role: str | None) -> bool: + return normalize_role(role) in {ROLE_SUPERADMIN, ROLE_ADMIN} + + +def can_assign_role(actor_role: str | None, target_role: str | None) -> bool: + return normalize_role(actor_role) == ROLE_SUPERADMIN and normalize_role(target_role) != ROLE_SUPERADMIN + + +class ResetManager: + """Creates and validates the short-lived, one-time admin reset code.""" + + def __init__(self, *, ttl: timedelta = RESET_CODE_TTL, log=print) -> None: + self._ttl = ttl + self._log = log + self._code: str | None = None + self._expires_at: datetime | None = None + self._lock = threading.Lock() + + def request(self) -> str: + code = secrets.token_hex(4).upper() + with self._lock: + self._code = code + self._expires_at = datetime.now().astimezone() + self._ttl + self._log( + f"\n{'=' * 50}\nADMIN RESET CODE: {code}\n" + f"Expires in 5 minutes. Enter it on the login page.\n{'=' * 50}\n" + ) + return code + + def confirm(self, candidate: str) -> bool: + with self._lock: + if self._code is None or self._expires_at is None: + return False + if datetime.now().astimezone() > self._expires_at: + self._code = None + self._expires_at = None + return False + valid = secrets.compare_digest(self._code, str(candidate or "").strip().upper()) + if valid: + self._code = None + self._expires_at = None + return valid + @dataclass(frozen=True, slots=True) class AuthUser: @@ -42,6 +108,7 @@ class AuthUser: username: str email: str password_hash: str + role: str = ROLE_USER created_at: datetime | None = None updated_at: datetime | None = None @@ -74,6 +141,8 @@ class AuthStore: await self.database.execute( "CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true))" ) + else: + await self.database.execute("DROP INDEX IF EXISTS auth_users_singleton_idx") async def count_users(self) -> int: return int(await self.database.fetchval("SELECT count(*) FROM auth_users")) @@ -82,9 +151,11 @@ class AuthStore: try: row = await self.database.fetchrow( """ - INSERT INTO auth_users (username, email, password_hash, updated_at) - VALUES ($1, $2, $3, now()) - RETURNING id, username, email, password_hash, created_at, updated_at + INSERT INTO auth_users (username, email, password_hash, role, updated_at) + VALUES ($1, $2, $3, + CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END, + now()) + RETURNING id, username, email, password_hash, role, created_at, updated_at """, username, email, @@ -98,7 +169,7 @@ class AuthStore: async def find_by_identifier(self, identifier: str) -> AuthUser | None: row = await self.database.fetchrow( """ - SELECT id, username, email, password_hash, created_at, updated_at + SELECT id, username, email, password_hash, role, created_at, updated_at FROM auth_users WHERE username = $1 OR lower(email) = lower($1) """, @@ -132,7 +203,7 @@ class AuthStore: async def find_session_user(self, token_hash: str) -> AuthUser | None: row = await self.database.fetchrow( """ - SELECT u.id, u.username, u.email, u.password_hash, u.created_at, u.updated_at + SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at FROM auth_sessions s JOIN auth_users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now() @@ -147,5 +218,89 @@ class AuthStore: async def delete_sessions_for_user(self, user_id: int) -> None: await self.database.execute("DELETE FROM auth_sessions WHERE user_id = $1", user_id) + async def list_users(self) -> list[AuthUser]: + rows = await self.database.fetch( + "SELECT id, username, email, role, password_hash, created_at, updated_at " + "FROM auth_users ORDER BY created_at, id" + ) + return [AuthUser(**dict(row)) for row in rows] + + async def create_managed_user( + self, username: str, email: str, password_hash: str, role: str = ROLE_USER + ) -> AuthUser: + try: + row = await self.database.fetchrow( + """ + INSERT INTO auth_users (username, email, password_hash, role, updated_at) + VALUES ($1, $2, $3, $4, now()) + RETURNING id, username, email, password_hash, role, created_at, updated_at + """, + username, + email, + password_hash, + normalize_role(role), + ) + except asyncpg.UniqueViolationError as exc: + raise UserExistsError from exc + assert row is not None + return AuthUser(**dict(row)) + + async def update_user( + self, + user_id: int, + *, + username: str | None = None, + email: str | None = None, + password_hash: str | None = None, + role: str | None = None, + ) -> None: + fields: list[str] = [] + values: list[object] = [] + for column, value in (("username", username), ("email", email), ("password_hash", password_hash), ("role", normalize_role(role) if role is not None else None)): + if value is not None: + fields.append(f"{column} = ${len(values) + 1}") + values.append(value) + if not fields: + return + values.append(user_id) + await self.database.execute( + f"UPDATE auth_users SET {', '.join(fields)}, updated_at = now() WHERE id = ${len(values)}", + *values, + ) + + async def delete_user(self, user_id: int) -> None: + await self.database.execute("DELETE FROM auth_users WHERE id = $1", user_id) + + async def delete_all_users(self) -> None: + await self.database.execute("DELETE FROM auth_users") + + async def get_totp_state(self, user_id: int) -> dict[str, object]: + row = await self.database.fetchrow( + "SELECT COALESCE(totp_secret, '') AS secret, COALESCE(totp_enabled, false) AS enabled " + "FROM auth_users WHERE id = $1", + user_id, + ) + return dict(row) if row else {"secret": "", "enabled": False} + + async def set_totp_secret(self, user_id: int, secret: str) -> None: + await self.database.execute( + "UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2", + secret, + user_id, + ) + + async def enable_totp(self, user_id: int) -> None: + await self.database.execute( + "UPDATE auth_users SET totp_enabled = true, updated_at = now() " + "WHERE id = $1 AND totp_secret <> ''", + user_id, + ) + + async def disable_totp(self, user_id: int) -> None: + await self.database.execute( + "UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1", + user_id, + ) + async def prune_expired_sessions(self) -> None: await self.database.execute("DELETE FROM auth_sessions WHERE expires_at < now()") diff --git a/packages/python-backend/src/shared_backend/totp.py b/packages/python-backend/src/shared_backend/totp.py new file mode 100644 index 0000000..00ad29f --- /dev/null +++ b/packages/python-backend/src/shared_backend/totp.py @@ -0,0 +1,75 @@ +"""RFC 6238 TOTP helpers shared by Python auth services.""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import hmac +import secrets +import struct +import time +from urllib.parse import quote, urlencode + +TOTP_PERIOD_SECONDS = 30 +TOTP_DIGITS = 6 +TOTP_WINDOW = 1 + + +def generate_totp_secret() -> str: + return base64.b32encode(secrets.token_bytes(20)).decode("ascii").rstrip("=") + + +def totp_provisioning_uri(issuer: str, account: str, secret: str) -> str: + normalized_issuer = str(issuer or "").strip() + normalized_account = str(account or "").strip() + label = f"{normalized_issuer}:{normalized_account}" if normalized_issuer else normalized_account + params = { + "secret": _normalize_secret(secret), + "algorithm": "SHA1", + "digits": str(TOTP_DIGITS), + "period": str(TOTP_PERIOD_SECONDS), + } + if normalized_issuer: + params["issuer"] = normalized_issuer + return f"otpauth://totp/{quote(label, safe='')}?{urlencode(params)}" + + +def verify_totp(secret: str, token: str, now: float | None = None) -> bool: + normalized_secret = _normalize_secret(secret) + normalized_token = _normalize_token(token) + if not normalized_secret or len(normalized_token) != TOTP_DIGITS: + return False + try: + key = base64.b32decode(normalized_secret + "=" * ((8 - len(normalized_secret) % 8) % 8)) + except (ValueError, binascii.Error): + return False + if not key: + return False + + period = int((time.time() if now is None else now) // TOTP_PERIOD_SECONDS) + for offset in range(-TOTP_WINDOW, TOTP_WINDOW + 1): + counter = period + offset + if counter < 0: + continue + digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest() + index = digest[-1] & 0x0F + value = ( + ((digest[index] & 0x7F) << 24) + | (digest[index + 1] << 16) + | (digest[index + 2] << 8) + | digest[index + 3] + ) + candidate = f"{value % 1_000_000:06d}" + if hmac.compare_digest(candidate, normalized_token): + return True + return False + + +def _normalize_secret(value: str) -> str: + return str(value or "").strip().upper().replace(" ", "").rstrip("=") + + +def _normalize_token(value: str) -> str: + token = str(value or "").strip() + return token if len(token) == TOTP_DIGITS and token.isdigit() else "" diff --git a/packages/python-backend/tests/test_core.py b/packages/python-backend/tests/test_core.py index 63d386e..95e4193 100644 --- a/packages/python-backend/tests/test_core.py +++ b/packages/python-backend/tests/test_core.py @@ -1,8 +1,11 @@ import os import unittest -from shared_backend.auth import hash_password, verify_password +from datetime import timedelta + +from shared_backend.auth import ResetManager, hash_password, verify_password from shared_backend.config import DatabaseConfig +from shared_backend.totp import totp_provisioning_uri, verify_totp from shared_backend.tokens import hash_token, new_session_token @@ -17,6 +20,38 @@ class SharedBackendTests(unittest.TestCase): self.assertNotEqual(token, token_hash) self.assertEqual(hash_token(token), token_hash) + def test_reset_manager_round_trip_and_one_time_use(self): + messages = [] + manager = ResetManager(log=messages.append) + code = manager.request() + + self.assertEqual(len(code), 8) + self.assertIn(f"ADMIN RESET CODE: {code}", messages[0]) + self.assertTrue(manager.confirm(f" {code.lower()} ")) + self.assertFalse(manager.confirm(code)) + + def test_reset_manager_expires(self): + manager = ResetManager(ttl=timedelta(seconds=-1), log=lambda _message: None) + code = manager.request() + self.assertFalse(manager.confirm(code)) + + def test_totp_rfc6238_sha1_vectors(self): + secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ" + vectors = [ + (59, "287082"), + (1111111109, "081804"), + (1111111111, "050471"), + (1234567890, "005924"), + (2000000000, "279037"), + ] + for timestamp, code in vectors: + self.assertTrue(verify_totp(secret, code, timestamp)) + self.assertTrue( + totp_provisioning_uri("Example App", "admin@example.com", secret).startswith( + "otpauth://totp/" + ) + ) + def test_database_config_from_environment(self): config = DatabaseConfig.from_env( { diff --git a/packages/web-ui/src/lib/components/AuthPage.svelte b/packages/web-ui/src/lib/components/AuthPage.svelte index c93d4df..083837b 100644 --- a/packages/web-ui/src/lib/components/AuthPage.svelte +++ b/packages/web-ui/src/lib/components/AuthPage.svelte @@ -1,6 +1,11 @@
@@ -122,6 +170,20 @@ /> + {#if showTotp && !setupRequired} + + {/if} + {#if setupRequired}
diff --git a/packages/web-ui/src/lib/components/ProfileDialog.svelte b/packages/web-ui/src/lib/components/ProfileDialog.svelte index 1607d6b..df08c31 100644 --- a/packages/web-ui/src/lib/components/ProfileDialog.svelte +++ b/packages/web-ui/src/lib/components/ProfileDialog.svelte @@ -1,17 +1,52 @@ + +
+
+
+

Two-factor authentication

+

Protect sign-in with a time-based authenticator code.

+
+ + {currentEnabled ? 'Enabled' : 'Optional'} + +
+ + {#if currentEnabled} + + + {:else if setup} +
+

Scan this address in your authenticator app, or enter the secret manually.

+ {setup.otpauthUrl} +

Manual secret: {setup.secret}

+
+ +
+ + +
+ {:else} + + {/if} + + {#if error} +

{error}

+ {/if} +
diff --git a/packages/web-ui/src/lib/components/UserManagement.svelte b/packages/web-ui/src/lib/components/UserManagement.svelte new file mode 100644 index 0000000..d17d638 --- /dev/null +++ b/packages/web-ui/src/lib/components/UserManagement.svelte @@ -0,0 +1,196 @@ + + +{#if canManage && onList && onCreate && onUpdate && onDelete} +
+
+
+

User management

+

Add, edit, or remove accounts for this project.

+
+ +
+ +
+ Add user +
+ + + + +
+
+
+ + {#if error}

{error}

{/if} + {#if notice}

{notice}

{/if} + + {#if loading && users.length === 0} +

Loading users...

+ {:else if users.length === 0} +

No users found.

+ {:else} +
+ {#each users as user (user.id)} + {#if String(editingId) === String(user.id)} +
+ + + + + +
+ {:else} +
+
{user.username}{user.email}
+ {user.role} + +
+ {/if} + {/each} +
+ {/if} +
+{/if} diff --git a/packages/web-ui/src/lib/index.ts b/packages/web-ui/src/lib/index.ts index 6072bc0..2af9c49 100644 --- a/packages/web-ui/src/lib/index.ts +++ b/packages/web-ui/src/lib/index.ts @@ -9,12 +9,29 @@ export { default as Header } from './components/Header.svelte'; export { default as PageHeader } from './components/PageHeader.svelte'; export { default as ProfileDialog } from './components/ProfileDialog.svelte'; export { default as SettingsDialog } from './components/SettingsDialog.svelte'; +export { default as TotpSettings } from './components/TotpSettings.svelte'; +export { default as UserManagement } from './components/UserManagement.svelte'; export type { AboutLink, AsyncAction, AuthLoginInput, + AuthResetConfirm, + AuthResetRequest, AuthSetupInput, ContentSnippet, NavItem, - ProfileUpdateInput + ProfileUpdateInput, + ManagedUser, + UserCreateInput, + UserCreateRequest, + UserDeleteRequest, + UserId, + UserListRequest, + UserRole, + UserUpdateInput, + UserUpdateRequest, + TotpSetupRequest, + TotpSetupResponse, + TotpStatusRequest, + TotpTokenAction } from './types'; diff --git a/packages/web-ui/src/lib/styles.css b/packages/web-ui/src/lib/styles.css index e4a657e..155e406 100644 --- a/packages/web-ui/src/lib/styles.css +++ b/packages/web-ui/src/lib/styles.css @@ -330,6 +330,71 @@ font-weight: 650; } +.sc-label-optional { + color: var(--sc-muted-fg); + font-weight: 400; +} + +.sc-totp-settings { + display: grid; + gap: 0.75rem; + margin-top: 1.5rem; + padding-top: 1.25rem; + border-top: 1px solid var(--sc-border); +} + +.sc-totp-heading { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; +} + +.sc-totp-heading h3 { + margin: 0; + font-size: 0.95rem; +} + +.sc-totp-heading p { + margin: 0.25rem 0 0; +} + +.sc-totp-status { + flex: 0 0 auto; + border: 1px solid var(--sc-border); + border-radius: 999px; + padding: 0.2rem 0.55rem; + color: var(--sc-muted-fg); + font-size: 0.75rem; + font-weight: 600; +} + +.sc-totp-status.sc-totp-enabled { + border-color: var(--sc-success); + color: var(--sc-success); +} + +.sc-totp-secret { + display: grid; + gap: 0.5rem; + color: var(--sc-muted-fg); + font-size: 0.8rem; + overflow-wrap: anywhere; +} + +.sc-totp-secret p { + margin: 0; +} + +.sc-totp-secret code { + display: block; + border-radius: 0.4rem; + background: var(--sc-input-bg); + padding: 0.6rem; + color: var(--sc-fg); + font-size: 0.7rem; +} + .sc-input, .sc-select, .sc-textarea { @@ -383,6 +448,109 @@ color: var(--sc-success); } +.sc-user-management { + display: grid; + gap: 1rem; + margin-top: 1.5rem; + padding-top: 1.5rem; + border-top: 1px solid var(--sc-border); +} + +.sc-user-management-header, +.sc-user-row, +.sc-user-edit-row { + display: flex; + align-items: center; + gap: 0.75rem; +} + +.sc-user-management-header { + justify-content: space-between; +} + +.sc-user-management-header h3 { + margin: 0; +} + +.sc-user-management-header p { + margin: 0.25rem 0 0; +} + +.sc-user-form, +.sc-user-list { + display: grid; + gap: 0.75rem; +} + +.sc-user-form { + padding: 0.9rem; + border: 1px solid var(--sc-border); + border-radius: 0.6rem; + background: var(--sc-surface-raised); +} + +.sc-user-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.6rem; +} + +.sc-user-row { + min-width: 0; + justify-content: space-between; + padding: 0.7rem 0; + border-bottom: 1px solid var(--sc-border); +} + +.sc-user-row > div:first-child { + display: grid; + min-width: 0; +} + +.sc-user-row > div:first-child span { + overflow: hidden; + color: var(--sc-muted-fg); + text-overflow: ellipsis; + white-space: nowrap; +} + +.sc-user-role { + color: var(--sc-muted-fg); + font-size: 0.8rem; + text-transform: capitalize; +} + +.sc-user-actions { + display: flex; + flex-shrink: 0; + gap: 0.4rem; +} + +.sc-user-edit-row { + align-items: stretch; + flex-wrap: wrap; +} + +.sc-user-edit-row .sc-input { + flex: 1 1 10rem; + min-width: 8rem; +} + +@media (max-width: 620px) { + .sc-user-grid { + grid-template-columns: 1fr; + } + + .sc-user-row { + align-items: flex-start; + flex-wrap: wrap; + } + + .sc-user-actions { + width: 100%; + } +} + .sc-auth-page { display: grid; min-height: 100vh; @@ -423,6 +591,37 @@ margin-top: 1rem; } +.sc-auth-reset { + display: grid; + gap: 0.625rem; + margin-top: 1.25rem; + padding-top: 1rem; + border-top: 1px solid var(--sc-border); +} + +.sc-auth-reset-hint { + color: var(--sc-subtle-fg); + font-size: 0.75rem; + line-height: 1.45; +} + +.sc-auth-reset-link { + display: block; + margin: 1.25rem auto 0; + padding: 0; + color: var(--sc-subtle-fg); + font: inherit; + font-size: 0.75rem; + text-decoration: underline; + background: none; + border: 0; + cursor: pointer; +} + +.sc-auth-reset-link:hover { + color: var(--sc-fg); +} + .sc-dialog-backdrop { position: fixed; z-index: 100; diff --git a/packages/web-ui/src/lib/types.ts b/packages/web-ui/src/lib/types.ts index 72957e9..6cd6341 100644 --- a/packages/web-ui/src/lib/types.ts +++ b/packages/web-ui/src/lib/types.ts @@ -16,14 +16,67 @@ export interface AuthSetupInput { export interface AuthLoginInput { identifier: string; password: string; + totpToken?: string; } +export interface TotpSetupResponse { + secret: string; + otpauthUrl: string; + enabled?: boolean; +} + +export type TotpStatusRequest = () => boolean | Promise; + +export type TotpSetupRequest = () => TotpSetupResponse | Promise; + +export type TotpTokenAction = (token: string) => void | Promise; + +export type AuthResetRequest = () => void | Promise; + +export type AuthResetConfirm = (code: string) => void | Promise; + export interface ProfileUpdateInput { username: string; email: string; password?: string; } +export type UserRole = 'superadmin' | 'admin' | 'user'; + +export type UserId = string | number; + +export interface ManagedUser { + id: UserId; + username: string; + email: string; + role: UserRole; + totpEnabled?: boolean; + createdAt?: string; + updatedAt?: string; +} + +export interface UserCreateInput { + username: string; + email: string; + password: string; + role?: UserRole; +} + +export interface UserUpdateInput { + username?: string; + email?: string; + password?: string; + role?: UserRole; +} + +export type UserListRequest = () => ManagedUser[] | Promise; + +export type UserCreateRequest = (input: UserCreateInput) => void | Promise; + +export type UserUpdateRequest = (id: UserId, input: UserUpdateInput) => void | Promise; + +export type UserDeleteRequest = (id: UserId) => void | Promise; + export interface AboutLink { label: string; href: string; diff --git a/shared-styles.css b/shared-styles.css index 0d4e597..5326c17 100644 --- a/shared-styles.css +++ b/shared-styles.css @@ -330,6 +330,11 @@ font-weight: 650; } +.sc-label-optional { + color: var(--sc-muted-fg); + font-weight: 400; +} + .sc-input, .sc-select, .sc-textarea { @@ -423,6 +428,37 @@ margin-top: 1rem; } +.sc-auth-reset { + display: grid; + gap: 0.625rem; + margin-top: 1.25rem; + padding-top: 1rem; + border-top: 1px solid var(--sc-border); +} + +.sc-auth-reset-hint { + color: var(--sc-subtle-fg); + font-size: 0.75rem; + line-height: 1.45; +} + +.sc-auth-reset-link { + display: block; + margin: 1.25rem auto 0; + padding: 0; + color: var(--sc-subtle-fg); + font: inherit; + font-size: 0.75rem; + text-decoration: underline; + background: none; + border: 0; + cursor: pointer; +} + +.sc-auth-reset-link:hover { + color: var(--sc-fg); +} + .sc-dialog-backdrop { position: fixed; z-index: 100;