Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: implement email_verification_code store (#20034)

ecmadaod3c7e3b19b7b
diff --git a/backend/migrator/migration/3.18/0000##add_email_verification_code.sql b/backend/migrator/migration/3.18/0000##add_email_verification_code.sql
new file mode 100644
index 0000000000..3ab3fa4d21
--- /dev/null
+++ b/backend/migrator/migration/3.18/0000##add_email_verification_code.sql
@@ -0,0 +1,16 @@
+CREATE TABLE email_verification_code (
+ email text NOT NULL,
+ -- Stored as EmailVerificationCodePurpose enum name (proto/store/store/email_verification_code.proto)
+ purpose text NOT NULL,
+ code_hash text NOT NULL,
+ attempts int NOT NULL DEFAULT 0,
+ expires_at timestamptz NOT NULL,
+ last_sent_at timestamptz NOT NULL,
+ -- Workspace context captured at send time. Used at verify time for gate checks
+ -- (disallow_signup, allow_email_code_signin) and for provisionWorkspaceForNewUser.
+ -- NULL for SaaS brand-new signup (no workspace exists yet — provision creates one).
+ workspace text,
+ PRIMARY KEY (email, purpose)
+);
+
+CREATE INDEX idx_email_verification_code_expires_at ON email_verification_code (expires_at);
diff --git a/backend/migrator/migration/LATEST.sql b/backend/migrator/migration/LATEST.sql
index 970d475d81..6760b8238f 100644
--- a/backend/migrator/migration/LATEST.sql
+++ b/backend/migrator/migration/LATEST.sql
@@ -637,6 +637,23 @@ CREATE TABLE web_refresh_token (
CREATE INDEX idx_web_refresh_token_user_email ON web_refresh_token(user_email);
CREATE INDEX idx_web_refresh_token_expires_at ON web_refresh_token(expires_at);
+CREATE TABLE email_verification_code (
+ email text NOT NULL,
+ -- Stored as EmailVerificationCodePurpose enum name (proto/store/store/email_verification_code.proto)
+ purpose text NOT NULL,
+ code_hash text NOT NULL,
+ attempts int NOT NULL DEFAULT 0,
+ expires_at timestamptz NOT NULL,
+ last_sent_at timestamptz NOT NULL,
+ -- Workspace context captured at send time. Used at verify time for gate checks
+ -- (disallow_signup, allow_email_code_signin) and for provisionWorkspaceForNewUser.
+ -- NULL for SaaS brand-new signup (no workspace exists yet — provision creates one).
+ workspace text,
+ PRIMARY KEY (email, purpose)
+);
+
+CREATE INDEX idx_email_verification_code_expires_at ON email_verification_code (expires_at);
+
-----------------------
-- Seed data
-----------------------
diff --git a/backend/migrator/migrator_test.go b/backend/migrator/migrator_test.go
index 7cd67b1447..b5c6d8b3ec 100644
--- a/backend/migrator/migrator_test.go
+++ b/backend/migrator/migrator_test.go
@@ -15,8 +15,8 @@ import (
func TestLatestVersion(t *testing.T) {
files, err := getSortedVersionedFiles()
require.NoError(t, err)
- require.Equal(t, semver.MustParse("3.17.16"), *files[len(files)-1].version)
- require.Equal(t, "migration/3.17/0016##revision_file_path_normalize.sql", files[len(files)-1].path)
+ require.Equal(t, semver.MustParse("3.18.0"), *files[len(files)-1].version)
+ require.Equal(t, "migration/3.18/0000##add_email_verification_code.sql", files[len(files)-1].path)
}
func TestVersionUnique(t *testing.T) {
diff --git a/backend/runner/cleaner/data_cleaner.go b/backend/runner/cleaner/data_cleaner.go
index 21c06fdda7..054bc0b31d 100644
--- a/backend/runner/cleaner/data_cleaner.go
+++ b/backend/runner/cleaner/data_cleaner.go
@@ -79,6 +79,7 @@ func (c *DataCleaner) cleanup(ctx context.Context) {
c.cleanupExportArchives(ctx)
c.cleanupOAuth2Data(ctx)
c.cleanupWebRefreshTokens(ctx)
+ c.cleanupEmailVerificationCodes(ctx)
c.cleanupStaleHeartbeats(ctx)
}
@@ -157,3 +158,11 @@ func (c *DataCleaner) cleanupWebRefreshTokens(ctx context.Context) {
slog.Info("Cleaned up expired web refresh tokens", slog.Int64("count", rowsAffected))
}
}
+
+func (c *DataCleaner) cleanupEmailVerificationCodes(ctx context.Context) {
+ if rowsAffected, err := c.store.DeleteExpiredEmailVerificationCodes(ctx); err != nil {
+ slog.Error("Failed to clean up expired email verification codes", log.BBError(err))
+ } else if rowsAffected > 0 {
+ slog.Info("Cleaned up expired email verification codes", slog.Int64("count", rowsAffected))
+ }
+}
diff --git a/backend/store/email_verification_code.go b/backend/store/email_verification_code.go
new file mode 100644
index 0000000000..dfd5f88919
--- /dev/null
+++ b/backend/store/email_verification_code.go
@@ -0,0 +1,152 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/pkg/errors"
+
+ "github.com/bytebase/bytebase/backend/common/qb"
+ storepb "github.com/bytebase/bytebase/backend/generated-go/store"
+)
+
+// EmailVerificationCodeMessage represents a row in the email_verification_code table.
+type EmailVerificationCodeMessage struct {
+ Email string
+ Purpose storepb.EmailVerificationCodePurpose
+ CodeHash string
+ Attempts int
+ ExpiresAt time.Time
+ LastSentAt time.Time
+ // Workspace is the workspace context captured when the code was sent.
+ // Empty string means no workspace (SaaS brand-new signup).
+ Workspace string
+}
+
+// UpsertEmailVerificationCodeIfCooldownExpired inserts or updates the row for (email, purpose),
+// but ONLY if no row exists OR the existing row's last_sent_at is older than the cooldown.
+// Returns (true, nil) if the upsert happened (caller may proceed to send), or
+// (false, nil) if the cooldown is still active (caller must skip the send).
+//
+// Atomic check-and-set: uses INSERT ... ON CONFLICT DO UPDATE ... WHERE ... RETURNING 1
+// to ensure only one concurrent request proceeds when both see an expired cooldown.
+// RETURNING is used (not RowsAffected) because Postgres returns unreliable counts
+// when the DO UPDATE's WHERE filters out the update.
+func (s *Store) UpsertEmailVerificationCodeIfCooldownExpired(ctx context.Context, msg *EmailVerificationCodeMessage, cooldown time.Duration) (bool, error) {
+ var workspace sql.NullString
+ if msg.Workspace != "" {
+ workspace = sql.NullString{String: msg.Workspace, Valid: true}
+ }
+ q := qb.Q().Space(`
+ INSERT INTO email_verification_code (email, purpose, code_hash, attempts, expires_at, last_sent_at, workspace)
+ VALUES (?, ?, ?, 0, ?, ?, ?)
+ ON CONFLICT (email, purpose) DO UPDATE SET
+ code_hash = EXCLUDED.code_hash,
+ attempts = 0,
+ expires_at = EXCLUDED.expires_at,
+ last_sent_at = EXCLUDED.last_sent_at,
+ workspace = EXCLUDED.workspace
+ WHERE email_verification_code.last_sent_at < EXCLUDED.last_sent_at - make_interval(secs => ?)
+ RETURNING 1
+ `, msg.Email, msg.Purpose.String(), msg.CodeHash, msg.ExpiresAt, msg.LastSentAt, workspace, cooldown.Seconds())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return false, err
+ }
+ var dummy int
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(&dummy); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil // cooldown blocked the upsert
+ }
+ return false, errors.Wrap(err, "failed to upsert email verification code")
+ }
+ return true, nil
+}
+
+// GetEmailVerificationCode returns the verification code record for the given email and purpose,
+// or (nil, nil) if no row exists.
+func (s *Store) GetEmailVerificationCode(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose) (*EmailVerificationCodeMessage, error) {
+ q := qb.Q().Space(`
+ SELECT email, purpose, code_hash, attempts, expires_at, last_sent_at, workspace
+ FROM email_verification_code
+ WHERE email = ? AND purpose = ?
+ `, email, purpose.String())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return nil, err
+ }
+
+ msg := &EmailVerificationCodeMessage{}
+ var purposeStr string
+ var workspace sql.NullString
+ if err := s.GetDB().QueryRowContext(ctx, query, args...).Scan(
+ &msg.Email, &purposeStr, &msg.CodeHash, &msg.Attempts, &msg.ExpiresAt, &msg.LastSentAt, &workspace,
+ ); err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, errors.Wrap(err, "failed to get email verification code")
+ }
+ msg.Purpose = storepb.EmailVerificationCodePurpose(storepb.EmailVerificationCodePurpose_value[purposeStr])
+ if workspace.Valid {
+ msg.Workspace = workspace.String
+ }
+ return msg, nil
+}
+
+// IncrementEmailVerificationCodeAttempts increments the attempt counter for the given email and purpose.
+func (s *Store) IncrementEmailVerificationCodeAttempts(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose) error {
+ q := qb.Q().Space(`
+ UPDATE email_verification_code
+ SET attempts = attempts + 1
+ WHERE email = ? AND purpose = ?
+ `, email, purpose.String())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to increment email verification code attempts")
+ }
+ return nil
+}
+
+// DeleteEmailVerificationCode deletes the verification code record for the given email and purpose.
+func (s *Store) DeleteEmailVerificationCode(ctx context.Context, email string, purpose storepb.EmailVerificationCodePurpose) error {
+ q := qb.Q().Space(`
+ DELETE FROM email_verification_code
+ WHERE email = ? AND purpose = ?
+ `, email, purpose.String())
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return err
+ }
+ if _, err := s.GetDB().ExecContext(ctx, query, args...); err != nil {
+ return errors.Wrap(err, "failed to delete email verification code")
+ }
+ return nil
+}
+
+// DeleteExpiredEmailVerificationCodes deletes all verification code records that have expired.
+// Returns the number of deleted rows.
+func (s *Store) DeleteExpiredEmailVerificationCodes(ctx context.Context) (int64, error) {
+ q := qb.Q().Space(`
+ DELETE FROM email_verification_code
+ WHERE expires_at < NOW()
+ `)
+
+ query, args, err := q.ToSQL()
+ if err != nil {
+ return 0, err
+ }
+ result, err := s.GetDB().ExecContext(ctx, query, args...)
+ if err != nil {
+ return 0, errors.Wrap(err, "failed to delete expired email verification codes")
+ }
+ return result.RowsAffected()
+}