datastore

package
v0.0.0-...-1cd555d Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2026 License: MPL-2.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	NormalStateExpiration = 30 * time.Second
	TwoFAStateExpiration  = 5 * time.Minute
)
View Source
const (
	EmailAuthSessionVersion    = 1
	PasswordAuthSessionVersion = 2
)
View Source
const (
	AuthTokenIntent      = "auth_token"
	VerificationIntent   = "verification"
	RegistrationIntent   = "registration"
	ResetPasswordIntent  = "reset_password"
	ChangePasswordIntent = "change_password"

	VerificationExpiration = 30 * time.Minute

	MaxCodeAttempts = 10
)
View Source
const MaxUserKeysPerService = 2
View Source
const (
	WebhookKeysEnv = "WEBHOOK_KEYS"
)

Variables

View Source
var ErrAccountNotFound = errors.New("account not found")
View Source
var ErrSessionNotFound = errors.New("session not found")

Functions

This section is empty.

Types

type Account

type Account struct {
	// Unique identifier for the account
	ID uuid.UUID
	// Email address associated with the account
	Email string
	// Simplified email address used in the account recovery flow only
	SimplifiedEmail *string `json:"-"`
	// Optional reference to the OPRF seed used for password hashing
	OprfSeedID *int `json:"-"`
	// Serialized OPAQUE protocol registration data
	OpaqueRegistration []byte `json:"-"`
	// Timestamp when the account was last used (with a MOE of 30 minutes)
	LastUsedAt time.Time `gorm:"<-:update"`
	// Timestamp when the account was last verified via email
	LastEmailVerifiedAt *time.Time `gorm:"<-:update"`
	// Locale preference for the account (e.g., "en-US", "es-ES")
	Locale *string `json:"-"`
	// TOTPEnabled indicates whether the account has TOTP enabled
	TOTPEnabled bool `json:"-"`
	// Timestamp when TOTP was enabled
	TOTPEnabledAt *time.Time `json:"-"`
	// Recovery key hash
	RecoveryKeyHash []byte `json:"-"`
	// Timestamp when the recovery key was created
	RecoveryKeyCreatedAt *time.Time `json:"-"`
	// Timestamp when the account was created
	CreatedAt time.Time `gorm:"<-:false"`
}

Account defines a Brave Account

func (*Account) IsTwoFAEnabled

func (a *Account) IsTwoFAEnabled() bool

type AccountDeletionEventDetails

type AccountDeletionEventDetails struct {
	// Unique identifier of the deleted account
	AccountID uuid.UUID `json:"accountId"`
}

AccountDeletionEventDetails represents the payload for an account deletion webhook event

type DBUserKey

type DBUserKey struct {
	// AccountID is the UUID of the account that owns this key
	AccountID uuid.UUID `json:"-" gorm:"primaryKey"`
	// Service identifies the service this key is for
	Service string `json:"service" gorm:"primaryKey"`
	// KeyName identifies the name of the key within the service
	KeyName string `json:"keyName" gorm:"primaryKey"`
	// KeyMaterial contains the encrypted key data as bytes
	KeyMaterial []byte `json:"keyMaterial"`
	// SerialNumber is incremented each time the key is overwritten
	SerialNumber int `json:"serialNumber" gorm:"default:1"`
	// UpdatedAt is the timestamp when the key was last updated
	UpdatedAt time.Time `json:"updatedAt" gorm:"autoUpdateTime:false"`
}

DBUserKey represents a key in the database

func (DBUserKey) TableName

func (DBUserKey) TableName() string

TableName overrides the default table name for DBUserKey

type Datastore

type Datastore struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

func NewDatastore

func NewDatastore(minSessionVersion int, isKeyService bool, isTesting bool) (*Datastore, error)

func (*Datastore) CheckAndStoreTOTPCodeUsed

func (d *Datastore) CheckAndStoreTOTPCodeUsed(accountID uuid.UUID, code string) error

CheckAndStoreTOTPCodeUsed atomically checks if a TOTP code has been used and stores it if not

func (*Datastore) CheckRecoveryKey

func (d *Datastore) CheckRecoveryKey(accountID uuid.UUID, recoveryKey string) error

func (*Datastore) Close

func (ds *Datastore) Close()

func (*Datastore) CreateLoginState

func (d *Datastore) CreateLoginState(accountID *uuid.UUID, email string, state []byte, oprfSeedID int, requiresTwoFA bool) (*InterimPasswordState, error)

func (*Datastore) CreateRegistrationState

func (d *Datastore) CreateRegistrationState(accountID uuid.UUID, email string, oprfSeedID int, requiresTwoFA bool) error

func (*Datastore) CreateSession

func (d *Datastore) CreateSession(accountID uuid.UUID, sessionVersion int, userAgent string) (*Session, error)

func (*Datastore) CreateVerification

func (d *Datastore) CreateVerification(email string, service string, intent string) (*Verification, error)

CreateVerification creates a new verification record

func (*Datastore) DecrementVerificationEmailAttempts

func (d *Datastore) DecrementVerificationEmailAttempts(id uuid.UUID) error

func (*Datastore) DeleteAccount

func (d *Datastore) DeleteAccount(accountID uuid.UUID) error

func (*Datastore) DeleteAccountIfUnverified

func (d *Datastore) DeleteAccountIfUnverified(email string) error

func (*Datastore) DeleteAllSessions

func (d *Datastore) DeleteAllSessions(accountID uuid.UUID) error

func (*Datastore) DeleteAllUserKeys

func (d *Datastore) DeleteAllUserKeys(accountID uuid.UUID) error

DeleteAllUserKeys deletes all keys for an account

func (*Datastore) DeleteInterimPasswordState

func (d *Datastore) DeleteInterimPasswordState(stateID uuid.UUID) error

func (*Datastore) DeletePendingEvent

func (d *Datastore) DeletePendingEvent(eventID int64) error

func (*Datastore) DeleteSession

func (d *Datastore) DeleteSession(sessionID uuid.UUID, accountID uuid.UUID) error

func (*Datastore) DeleteTOTPKey

func (d *Datastore) DeleteTOTPKey(accountID uuid.UUID) error

DeleteTOTPKey deletes a TOTP key from the database

func (*Datastore) DeleteVerification

func (d *Datastore) DeleteVerification(id uuid.UUID) error

func (*Datastore) DeleteVerificationsByNewSessionID

func (d *Datastore) DeleteVerificationsByNewSessionID(sessionID uuid.UUID) error

func (*Datastore) GetAccount

func (d *Datastore) GetAccount(tx *gorm.DB, email string) (*Account, error)

func (*Datastore) GetAccountLocale

func (d *Datastore) GetAccountLocale(accountID uuid.UUID) (*string, error)

func (*Datastore) GetAccountsBySimplifiedEmail

func (d *Datastore) GetAccountsBySimplifiedEmail(email string) ([]Account, error)

func (*Datastore) GetLoginState

func (d *Datastore) GetLoginState(loginStateID uuid.UUID, forTwoFA bool) (*InterimPasswordState, error)

func (*Datastore) GetOrCreateAccount

func (d *Datastore) GetOrCreateAccount(email string) (*Account, error)

func (*Datastore) GetOrCreateJWTKeys

func (d *Datastore) GetOrCreateJWTKeys(usePublicKeyCrypto bool, create bool) (map[int]*JWTKey, error)

func (*Datastore) GetOrCreateOPRFSeeds

func (d *Datastore) GetOrCreateOPRFSeeds(seedGenerator func() []byte) (map[int][]byte, error)

func (*Datastore) GetPendingEvent

func (d *Datastore) GetPendingEvent(eventID int64) (*PendingWebhookEvent, error)

func (*Datastore) GetPendingEvents

func (d *Datastore) GetPendingEvents(failedOnly bool) ([]PendingWebhookEvent, error)

func (*Datastore) GetRegistrationState

func (d *Datastore) GetRegistrationState(email string, forTwoFA bool) (*InterimPasswordState, error)

func (*Datastore) GetSession

func (d *Datastore) GetSession(sessionID uuid.UUID) (*SessionWithAccountInfo, error)

func (*Datastore) GetTOTPKey

func (d *Datastore) GetTOTPKey(accountID uuid.UUID) (string, error)

GetTOTPKey retrieves the TOTP key string for an account

func (*Datastore) GetTwoFADetails

func (d *Datastore) GetTwoFADetails(accountID uuid.UUID) (*TwoFADetails, error)

func (*Datastore) GetUserKey

func (d *Datastore) GetUserKey(accountID uuid.UUID, service string, keyName string) (*DBUserKey, error)

GetUserKey retrieves a user key from the database

func (*Datastore) GetUserKeys

func (d *Datastore) GetUserKeys(accountID uuid.UUID) ([]DBUserKey, error)

GetUserKeys retrieves all keys for an account

func (*Datastore) GetVerificationStatus

func (d *Datastore) GetVerificationStatus(id uuid.UUID) (*Verification, error)

GetVerificationStatus fetches the verification record by ID, returning an error if expired or not found

func (*Datastore) HasRecoveryKey

func (d *Datastore) HasRecoveryKey(accountID uuid.UUID) (bool, error)

func (*Datastore) IncrementAttemptsCount

func (d *Datastore) IncrementAttemptsCount(eventID int64) error

func (*Datastore) IncrementVerificationCodeAttempts

func (d *Datastore) IncrementVerificationCodeAttempts(id uuid.UUID) (int16, error)

func (*Datastore) IncrementVerificationEmailAttempts

func (d *Datastore) IncrementVerificationEmailAttempts(id uuid.UUID) error

func (*Datastore) ListSessions

func (d *Datastore) ListSessions(accountID uuid.UUID) ([]Session, error)

func (*Datastore) MarkInterimPasswordStateAsAwaitingTwoFA

func (d *Datastore) MarkInterimPasswordStateAsAwaitingTwoFA(stateID uuid.UUID) error

func (*Datastore) MarkVerificationAsComplete

func (d *Datastore) MarkVerificationAsComplete(id uuid.UUID) error

MarkVerificationAsComplete marks the verification as verified

func (*Datastore) MaybeUpdateAccountLastUsed

func (d *Datastore) MaybeUpdateAccountLastUsed(accountID uuid.UUID, lastUsedTime time.Time) error

func (*Datastore) NewWebhookEventListener

func (d *Datastore) NewWebhookEventListener() (*WebhookEventListener, error)

func (*Datastore) NotifyAccountDeletionEvent

func (d *Datastore) NotifyAccountDeletionEvent(accountID uuid.UUID) error

func (*Datastore) SetAccountLocaleIfMissing

func (d *Datastore) SetAccountLocaleIfMissing(accountID uuid.UUID, locale string) error

func (*Datastore) SetRecoveryKey

func (d *Datastore) SetRecoveryKey(accountID uuid.UUID, recoveryKey *string) error

func (*Datastore) SetTOTPSetting

func (d *Datastore) SetTOTPSetting(accountID uuid.UUID, enabled bool) error

func (*Datastore) SetVerificationNewSessionID

func (d *Datastore) SetVerificationNewSessionID(id uuid.UUID, sessionID uuid.UUID) error

func (*Datastore) StoreTOTPKey

func (d *Datastore) StoreTOTPKey(accountID uuid.UUID, key *otp.Key) error

StoreTOTPKey stores a TOTP key for an account

func (*Datastore) StoreUserKey

func (d *Datastore) StoreUserKey(key *DBUserKey) error

StoreUserKey saves a user key to the database

func (*Datastore) UpdateAccountLastEmailVerifiedAt

func (d *Datastore) UpdateAccountLastEmailVerifiedAt(accountID uuid.UUID) error

func (*Datastore) UpdateInterimPasswordState

func (d *Datastore) UpdateInterimPasswordState(stateID uuid.UUID, state []byte) error

func (*Datastore) UpdateOpaqueRegistration

func (d *Datastore) UpdateOpaqueRegistration(accountID uuid.UUID, oprfSeedID int, opaqueRegistration []byte) error

type InterimPasswordState

type InterimPasswordState struct {
	// ID uniquely identifies the login state instance
	ID uuid.UUID `json:"id"`
	// AccountID links to the associated account
	AccountID *uuid.UUID `json:"-"`
	// Email associated with the account
	Email string `json:"-"`
	// OprfSeedID references the seed used for the Oblivious PRF
	OprfSeedID int `json:"-"`
	// State stores the serialized AKE state data
	State []byte `json:"-"`
	// AwaitingTwoFA indicates whether the login is awaiting two-factor authentication
	AwaitingTwoFA bool `json:"-" gorm:"column:awaiting_twofa"`
	// RequiresTwoFA indicates whether the account requires two-factor authentication
	RequiresTwoFA bool `json:"-" gorm:"column:requires_twofa"`
	// IsRegistration indicates whether the state is for a registration operation
	IsRegistration bool `json:"-" gorm:"column:is_registration"`
	// CreatedAt records when this login state was initialized
	CreatedAt time.Time `json:"createdAt" gorm:"<-:update"`
}

InterimPasswordState represents the state of an OPAQUE Authenticated Key Exchange or Registration operation

type JWTKey

type JWTKey struct {
	// ID is the unique identifier for the JWT key
	ID int
	// SecretKey contains the raw bytes of the signing key
	SecretKey []byte
	// PublicKey contains the raw bytes of the verification key
	PublicKey []byte
	// CreatedAt stores the timestamp when the key was created (read-only)
	CreatedAt time.Time `gorm:"<-:false"`
	// ECDSASecretKey is the decoded secret key, if public key crypto is being used
	ECDSASecretKey *ecdsa.PrivateKey `gorm:"-"`
	// ECDSAPublicKey is the decoded public key, if public key crypto is being used
	ECDSAPublicKey *ecdsa.PublicKey `gorm:"-"`
}

JWTKey represents a JSON Web Token signing key stored in the database

type OPRFSeed

type OPRFSeed struct {
	// ID uniquely identifies the OPRF seed
	ID int
	// Seed contains the raw bytes of the OPRF seed value
	Seed []byte
	// CreatedAt records when the seed was created (read-only)
	CreatedAt time.Time `gorm:"<-:false"`
}

OPRFSeed stores seed data for the Oblivious Pseudorandom Function

type PendingWebhookEvent

type PendingWebhookEvent struct {
	// Unique identifier for the webhook event
	ID int64 `json:"-"`
	// Type of event
	EventType string `json:"type"`
	// JSON-encoded event payload
	Details interface{} `gorm:"serializer:json" json:"details"`
	// Destination URL for the webhook
	URL string `json:"-"`
	// Number of times delivery has been attempted
	Attempts int `json:"-"`
	// Timestamp when the event was created (managed by database)
	CreatedAt time.Time `gorm:"<-:false" json:"-"`
	// Timestamp of the last update (managed by database)
	UpdatedAt time.Time `gorm:"autoUpdateTime:false" json:"-"`
}

PendingWebhookEvent represents a webhook event that needs to be sent to a URL It tracks the event data, destination URL, number of delivery attempts, and timestamps

type Session

type Session struct {
	// Session UUID
	ID uuid.UUID `json:"id"`
	// AccountID is excluded from JSON
	AccountID uuid.UUID `json:"-"`
	// User agent of client
	UserAgent string `json:"userAgent"`
	// The accounts "phase" the session was created in
	Version int `json:"-"`
	// Session creation timestamp
	CreatedAt time.Time `json:"createdAt" gorm:"<-:false"`
}

Session represents a user's authenticated session in the system

type SessionWithAccountInfo

type SessionWithAccountInfo struct {
	// Session UUID
	ID uuid.UUID `json:"id"`
	// AccountID is excluded from JSON
	AccountID uuid.UUID `json:"-"`
	// The accounts "phase" the session was created in
	Version int `json:"-"`
	// Account email
	Email string
	// Account last usage time
	LastUsedAt time.Time
}

SessionWithAccountInfo extends the basic session data with additional user account details

type TOTPKey

type TOTPKey struct {
	// AccountID is the UUID of the account that owns this TOTP key
	AccountID uuid.UUID `json:"-" gorm:"primaryKey;table:totp_keys"`
	// Key contains the TOTP key material as text
	Key string `json:"key"`
	// CreatedAt is the timestamp when the key was created
	CreatedAt time.Time `json:"createdAt" gorm:"<-:false"`
}

TOTPKey represents a TOTP key in the database

type TOTPUsedCode

type TOTPUsedCode struct {
	AccountID uuid.UUID `gorm:"primaryKey"`
	Code      string    `gorm:"primaryKey"`
	CreatedAt time.Time `gorm:"<-:false"`
}

TOTPUsedCode represents a used TOTP code in the database

type TwoFADetails

type TwoFADetails struct {
	// TOTP indicates whether Time-based One-Time Password is enabled
	TOTP bool `json:"totp"`
	// TOTPEnabledAt indicates when TOTP was enabled
	TOTPEnabledAt *time.Time `json:"totpEnabledAt,omitempty"`
	// RecoveryKeyCreatedAt indicates when the recovery key was created
	RecoveryKeyCreatedAt *time.Time `json:"recoveryKeyCreatedAt,omitempty"`
}

TwoFADetails represents the 2FA methods enabled for an account and related timestamps

type Verification

type Verification struct {
	// ID uniquely identifies the verification request
	ID uuid.UUID
	// Email stores the address to be verified
	Email string
	// Code contains the verification code sent to the user
	Code string
	// Verified indicates whether the email has been successfully verified
	Verified bool
	// Service identifies the actor that initiated the verification
	Service string
	// Intent describes the purpose of the verification
	Intent string
	// NewSessionID stores the session ID after verification with a registration/auth token intent is complete
	NewSessionID *uuid.UUID
	// EmailAttempts tracks the number of times the verification email has been sent
	EmailAttempts int16
	// CodeAttempts tracks the number of wrong-code submission attempts
	CodeAttempts int16
	// CreatedAt records when the verification was initiated
	CreatedAt time.Time `gorm:"<-:update"`
}

Verification represents an email verification record and its status

type WebhookEventListener

type WebhookEventListener struct {
	// contains filtered or unexported fields
}

WebhookEventListener handles Postgres notifications for webhook events

func (*WebhookEventListener) WaitForEvent

func (l *WebhookEventListener) WaitForEvent() (int64, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL